fix(agent-loop): open turns before pre-step

This commit is contained in:
_Kerman
2026-08-04 13:49:35 +08:00
parent 0ac95437b4
commit d4fa26023d
154 changed files with 1104 additions and 1099 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/hooks/hook-protocol/README.md
README.md: 8cf4b95c95d43b8fbc27bbdcaf727dabf7d96805
README.zh.md: 15a537b67677a401ab434a3e73af1973030780c0
README.md: e807d9597eb5f811195bab9a0ad2b30b545e1205
README.zh.md: f9990c046d4e52a2fa911776e92fcf397d159633

View File

@@ -29,7 +29,7 @@ Why a shared lib at all: Codex deliberately reimplements a *subset* of the Claud
Declaration-merged into `SessionEventMap` (log-only, like `compact/*` — NOT a `SurfaceEventType`, no `surfaceOp`): `hook/invoked` (a hook command ran) and `hook/result` (its outcome, paired by `handlerId`, with `appendHookResult` owning the decision rule). Payloads and per-event JSDoc are in the generated [persistence log event catalog](../../../docs/persistence-catalog.md); `stderrSummary` is truncated to the record's `stderrSummaryMaxChars` (the bridge's config, reference default `DEFAULT_STDERR_SUMMARY_MAX_CHARS` = 500; omitted when empty).
Hook provenance records must sit inside an open turn. The mid-turn points (`PreToolUse`/`PostToolUse`/`Stop`) satisfy that owner-defined relation by construction. `SessionStart` and the pre-turn `UserPromptSubmit` admission seam get no `hook/*` record; allowed context is instead evidenced by its sourced `user/message` — see the hooks Agent Note.
Hook provenance records must sit inside an open turn. `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, and `Stop` satisfy that owner-defined relation by construction. `SessionStart` runs before turn 1 and gets no `hook/*` record; its allowed context remains pending in the inbox until a waking delivery opens a turn — see the hooks Agent Note.
## Model Experience

View File

@@ -29,7 +29,7 @@ Claude CodeCodex hook 协议格式wire format的**共享核心**。它
通过 declaration merging 合并到 `SessionEventMap`(仅日志,与 `compact/*` 相同;不是 `SurfaceEventType`,没有 `surfaceOp``hook/invoked`hook 命令已运行)与 `hook/result`(其结果,按 `handlerId` 配对,决策规则由 `appendHookResult` 负责。Payload 与每事件 JSDoc 位于生成的 [持久化日志事件目录](../../../docs/persistence-catalog.md)`stderrSummary` 会截断到记录的 `stderrSummaryMaxChars`(桥接配置,参考默认值 `DEFAULT_STDERR_SUMMARY_MAX_CHARS` = 500为空时省略
Hook 溯源记录必须位于一个尚未结束的轮次内。轮次中的点(`PreToolUse``PostToolUse``Stop`按构造满足这条由所有者定义的关系。`SessionStart` 轮次前的 `UserPromptSubmit` 准入 seam 没有 `hook/*` 记录;获准的上下文改由其带来源的 `user/message` 作为证据,详见 hooks Agent Note。
Hook 溯源记录必须位于一个尚未结束的轮次内。`UserPromptSubmit``PreToolUse``PostToolUse``Stop` 按构造满足这条由所有者定义的关系。`SessionStart` 轮次 1 之前运行,因此没有 `hook/*` 记录;获准的上下文会在 inbox 中保持待处理,直到唤醒交付打开一个轮次,详见 hooks Agent Note。
## 模型体验

View File

@@ -129,8 +129,7 @@ export function apply(ctx: Context, config: Config): void {
* Run every command hook configured for `point` whose matcher selects
* `matchQuery`, with the per-event `payload` on stdin, and fold the results.
* Writes a `hook/invoked`/`hook/result` pair per hook when `opts.turn` names
* an open turn. Pre-turn `UserPromptSubmit` and detached lifecycle points
* omit the pair. Returns the merged outcome (a neutral,
* an open turn. Detached lifecycle points omit the pair. Returns the merged outcome (a neutral,
* already-most-restrictive view) for the caller to map onto its seam
* decision. `matchQuery` is the event's matcher subject (tool name, session
* source, …); `''` for events that ignore matchers.
@@ -217,10 +216,10 @@ export function apply(ctx: Context, config: Config): void {
// --- UserPromptSubmit → PreStepDecision. The prompt text is the payload; no
// matcher subject (CC ignores matchers for this event). ---
ctx.on('agent/pre-step', async (agent, messages, { signal }, next): Promise<PreStepDecision> => {
ctx.on('agent/pre-step', async (agent, messages, { turn, signal }, next): Promise<PreStepDecision> => {
if (messages.length === 0) return next()
const content = messages.flatMap(message => message.content)
const merged = await runPoint('UserPromptSubmit', '', promptPayload(ctx, agent, content), { agent, signal })
const merged = await runPoint('UserPromptSubmit', '', promptPayload(ctx, agent, content), { agent, turn, signal })
if (merged.decision === 'deny') {
return { kind: 'reject' }
}

View File

@@ -89,7 +89,7 @@ async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10):
}
describe('hooks-claude bridge — UserPromptSubmit', () => {
it('a UserPromptSubmit hook that exits 2 rejects step entry without a turn', async () => {
it('a UserPromptSubmit hook that exits 2 closes a blocked turn without a step', async () => {
// UserPromptSubmit ignores its malformed matcher field, then exit 2 blocks
// with the reason on stderr.
const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
@@ -105,11 +105,11 @@ describe('hooks-claude bridge — UserPromptSubmit', () => {
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do something' }], source: { kind: 'user' } }))
await waitForIdle(ctx, agent)
// The prompt was blocked before the model and before a turn opened.
// The prompt was blocked inside its turn before any model step.
expect(adapter.requests).toHaveLength(0)
expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
// Pre-step has no open turn in which turn-scoped hook provenance could live.
expect(events(agent).some(e => e.type === 'hook/invoked' || e.type === 'hook/result')).toBe(false)
expect(events(agent).filter(e => e.type === 'turn/start' || e.type === 'hook/invoked'
|| e.type === 'hook/result' || e.type === 'turn/end').map(e => e.type))
.toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
})
it('a UserPromptSubmit hook printing additionalContext injects it for the model', async () => {
@@ -399,7 +399,9 @@ describe('hooks-claude bridge — load resilience', () => {
await waitForIdle(ctx, agent)
expect(adapter.requests).toHaveLength(0)
expect(events(agent).some(event => event.type === 'turn/start')).toBe(false)
expect(events(agent).filter(event => event.type === 'turn/start' || event.type === 'hook/invoked'
|| event.type === 'hook/result' || event.type === 'turn/end').map(event => event.type))
.toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('invalid claude regex matcher'))
})

View File

@@ -322,7 +322,9 @@ export function defineCoverageCases(group: CoverageGroup): void {
const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
await waitForIdle(ctx, agent)
expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
expect(events(agent).filter(e => e.type === 'turn/start' || e.type === 'hook/invoked'
|| e.type === 'hook/result' || e.type === 'turn/end').map(e => e.type))
.toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
})
it('a PreToolUse ask with NO reason omits the reason (false arm)', async () => {
@@ -505,7 +507,9 @@ export function defineCoverageCases(group: CoverageGroup): void {
// recorded, and the (sole, fully-blocked) prompt closed the turn `rejected`
expect(adapter.requests).toHaveLength(0)
expect(events(agent).some(e => e.type === 'user/message' && e.data.source.kind !== 'user')).toBe(false)
expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
expect(events(agent).filter(e => e.type === 'turn/start' || e.type === 'hook/invoked'
|| e.type === 'hook/result' || e.type === 'turn/end').map(e => e.type))
.toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
})
it('preserves separate bridge and downstream prompt contexts with framing and metadata', async () => {

View File

@@ -108,7 +108,7 @@ export function apply(ctx: Context, config: Config): void {
* Run and fold one configured Codex hook point.
*
* A supplied turn records the hook provenance pair inside that open turn.
* Pre-turn `UserPromptSubmit` and detached lifecycle points omit it.
* Detached lifecycle points omit it.
*/
async function runPoint(
point: string,
@@ -203,7 +203,9 @@ export function apply(ctx: Context, config: Config): void {
turn_id: String(turn),
prompt: blocksToText(messages.flatMap(message => message.content)),
}
const merged = await runPoint('UserPromptSubmit', '', payload, { agent, plainStdoutAsContext: true, signal })
const merged = await runPoint('UserPromptSubmit', '', payload, {
agent, turn, plainStdoutAsContext: true, signal,
})
/* jscpd:ignore-start */
if (merged.decision === 'deny') {
return { kind: 'reject' }

View File

@@ -125,8 +125,9 @@ describe('hooks-codex bridge', () => {
expect(() => process.kill(pid, 0)).toThrow()
expect(adapter.requests).toHaveLength(0)
expect(events(agent).some(event => event.type === 'turn/start')).toBe(false)
expect(events(agent).some(event => event.type === 'hook/invoked' || event.type === 'hook/result')).toBe(false)
expect(events(agent).filter(event => event.type === 'turn/start' || event.type === 'hook/invoked'
|| event.type === 'hook/result' || event.type === 'turn/end').map(event => event.type))
.toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
})
it('only the five bridge-supported Codex events are honored — a SubagentStop entry is ignored', async () => {

View File

@@ -81,7 +81,7 @@ export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGro
expect((await capture()).payload.transcript_path).toBeNull()
}, 15_000) // Two real agent/hook subprocess loops need process startup and teardown headroom.
it('UserPromptSubmit block (exit 2) rejects step entry without a turn', async () => {
it('UserPromptSubmit block (exit 2) closes a blocked turn without a step', async () => {
const d = dir()
hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'b.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
const adapter = new MockAdapter([textResponse('no')])
@@ -89,7 +89,9 @@ export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGro
const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })); await waitForIdle(ctx, agent)
expect(adapter.requests).toHaveLength(0)
expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
expect(events(agent).filter(e => e.type === 'turn/start' || e.type === 'hook/invoked'
|| e.type === 'hook/result' || e.type === 'turn/end').map(e => e.type))
.toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
})
it('UserPromptSubmit additionalContext is injected; a no-op hook proceeds', async () => {
@@ -116,7 +118,9 @@ export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGro
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })); await waitForIdle(ctx, agent)
expect(adapter.requests).toHaveLength(0)
expect(events(agent).some(e => e.type === 'user/message')).toBe(false)
expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
expect(events(agent).filter(e => e.type === 'turn/start' || e.type === 'hook/invoked'
|| e.type === 'hook/result' || e.type === 'turn/end').map(e => e.type))
.toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
})
it('preserves separate bridge and downstream prompt contexts with framing and metadata', async () => {