From 2c99c6a64835d907379277860831bd2e6dc86dfa Mon Sep 17 00:00:00 2001 From: mutallip Date: Wed, 4 Nov 2026 20:11:14 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=AD=90=20Agent=20?= =?UTF-8?q?=E5=8E=8B=E7=BC=A9=E5=90=8E=E5=AE=8C=E6=88=90=E6=8F=90=E9=86=92?= =?UTF-8?q?=E6=BC=8F=E6=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/pi-interactive-subagents/README.md | 2 + .../pi-interactive-subagents/README.zh-CN.md | 2 + .../locales/index.json | 4 + .../pi-interactive-subagents/package.json | 2 +- .../pi-extension/subagents/index.ts | 10 + .../pi-extension/subagents/subagent-done.ts | 129 +++++-- .../test/squash-done-integration.test.ts | 357 ++++++++++++++++++ .../test/subagent-done-nudge.test.ts | 159 +++++++- .../pi-interactive-subagents/test/test.ts | 33 ++ packages/pi-session-tools/README.md | 2 + packages/pi-session-tools/README.zh-CN.md | 2 + .../src/session-tail-compaction.ts | 59 +++ .../tests/session-tail-compaction.test.ts | 64 +++- 13 files changed, 800 insertions(+), 25 deletions(-) create mode 100644 packages/pi-interactive-subagents/test/squash-done-integration.test.ts diff --git a/packages/pi-interactive-subagents/README.md b/packages/pi-interactive-subagents/README.md index 4ceb351b..a5a46279 100644 --- a/packages/pi-interactive-subagents/README.md +++ b/packages/pi-interactive-subagents/README.md @@ -10,6 +10,8 @@ https://github.com/user-attachments/assets/30adb156-cfb4-4c47-84ca-dd4aa80cba9f Call `subagent()` and it **returns immediately**. The sub-agent runs in its own terminal pane. A live widget above the input shows all running agents with their current state — `starting`, `active`, `waiting`, `stalled`, or `running`. When a sub-agent finishes, its result is **steered back** into the main session as an async notification — triggering a new turn so the agent can process it. Completion reminders are injected only after the model stops normally; user aborts and provider errors stay quiet. +Spawn and resume pass the resolved mode as `PI_SUBAGENT_INTERACTIVE=1|0`; child extensions must use this explicit value rather than infer it from `PI_SUBAGENT_AUTO_EXIT`. When `pi-session-tools:squash-completed` reports a successful `next-user` squash, only autonomous (`0`) children may receive one delayed completion reminder. Disabled reminders, manual takeover, interruption, new activity, stale session/leaf events, and already-reported completion suppress it; `auto` squashes and interactive children never receive this compensation. + ``` ╭─ Subagents ──────────────────────────── 2 running ─╮ │ 00:23 Scout: Auth (scout) active · bash 7m │ diff --git a/packages/pi-interactive-subagents/README.zh-CN.md b/packages/pi-interactive-subagents/README.zh-CN.md index c518d5f4..cb37befe 100644 --- a/packages/pi-interactive-subagents/README.zh-CN.md +++ b/packages/pi-interactive-subagents/README.zh-CN.md @@ -8,6 +8,8 @@ 调用 `subagent()` 后**立即返回**,子 agent 在自己的终端分屏中运行。输入框上方的实时 widget 展示所有运行中的 agent 及其状态(`starting`、`active`、`waiting`、`stalled`、`running`)。子 agent 完成后,结果以异步通知形式**回流**到主会话,触发新一轮处理。完成提醒仅在模型正常停止后注入;用户手动终止或提供方异常不会触发。 +spawn 与 resume 会传入已解析的实际模式 `PI_SUBAGENT_INTERACTIVE=1|0`;子扩展必须使用该显式值,不能从 `PI_SUBAGENT_AUTO_EXIT` 猜测。收到 `pi-session-tools:squash-completed` 的成功 `next-user` 压缩事件时,只有自主子 agent(`0`)最多补偿一次延迟完成提醒。禁用提醒、人工接管、中断、新活动、过期 session/leaf 事件和已上报完成都会抑制提醒;`auto` 压缩和交互子 agent 不会收到此补偿。 + 由编排器启动的 agent 不出现在这个 widget 里:通过 `__pi_subagents` 桥并带上 `hiddenFromWidget: true` 启动的子 agent(目前是 `pi-dynamic-workflows` 的每个 `agent()`)会被排除,因为这些 agent 已由 Workflow 面板展示。隐藏只影响展示,子 agent 仍在运行集合中,监听、状态判定、中断和结果回流都照常工作。如果本次运行只有 workflow 子 agent,就完全不显示 Subagents widget。 ```typescript diff --git a/packages/pi-interactive-subagents/locales/index.json b/packages/pi-interactive-subagents/locales/index.json index b0858652..3a7da1dc 100644 --- a/packages/pi-interactive-subagents/locales/index.json +++ b/packages/pi-interactive-subagents/locales/index.json @@ -3,6 +3,10 @@ "zh-CN": "【自动提醒】\n• 已完成 → 调用 subagent_done 结束。\n• 结束前自检:是否在原地打转?若是,立刻收敛结果,用 caller_ping 抛回主 agent,不要过度思考。\n• 还在处理 → 忽略。", "en-US": "[Auto reminder]\n• Done → call subagent_done to finish.\n• Before finishing, self-check: are you spinning in place? If so, converge your result immediately and hand it back to the main agent with caller_ping — don't overthink.\n• Still working → ignore." }, + "squashCompletionNudge": { + "zh-CN": "【压缩完成提醒】\n• 任务状态已保存,且当前正在等待上级输入。\n• 若已完成 → 调用 subagent_done 上报结果。\n• 需要主 agent 协助 → 调用 caller_ping;仍在处理 → 忽略。", + "en-US": "[Compaction completion reminder]\n• Your task state has been saved and the session is waiting for the parent.\n• If done → call subagent_done to report your result.\n• Need help from the main agent → call caller_ping; still working → ignore." + }, "muxCommandDescription": { "zh-CN": "配置 subagent 使用的终端复用器及 Herdr 布局模式", "en-US": "Configure the subagent multiplexer and Herdr layout mode" diff --git a/packages/pi-interactive-subagents/package.json b/packages/pi-interactive-subagents/package.json index d53ada46..28c4690e 100644 --- a/packages/pi-interactive-subagents/package.json +++ b/packages/pi-interactive-subagents/package.json @@ -18,7 +18,7 @@ "SKILL.md" ], "scripts": { - "test": "tsx --test test/subagent-done-nudge.test.ts test/test.ts", + "test": "tsx --test test/subagent-done-nudge.test.ts test/squash-done-integration.test.ts test/test.ts", "test:integration": "tsx --test --test-concurrency=1 test/integration/*.test.ts", "typecheck": "tsc --noEmit --pretty false", "build": "npm run typecheck", diff --git a/packages/pi-interactive-subagents/pi-extension/subagents/index.ts b/packages/pi-interactive-subagents/pi-extension/subagents/index.ts index 5c187bbd..e4e78c6f 100644 --- a/packages/pi-interactive-subagents/pi-extension/subagents/index.ts +++ b/packages/pi-interactive-subagents/pi-extension/subagents/index.ts @@ -929,6 +929,11 @@ const NO_EXTENSIONS_FLAG = "--no-extensions"; const EXTENSION_FLAG = "--extension"; const SUBAGENT_DONE_EXTENSION_FILE = "subagent-done.ts"; +/** 将父端解析后的实际交互模式编码为子进程环境变量。 */ +function buildSubagentInteractiveEnvironment(isInteractive: boolean): string { + return `PI_SUBAGENT_INTERACTIVE=${isInteractive ? "1" : "0"}`; +} + /** * Build the child --tools allowlist. * @@ -1596,6 +1601,7 @@ export const __test__ = { resolveEffectiveSessionMode, resolveLaunchBehavior, resolveEffectiveInteractive, + buildSubagentInteractiveEnvironment, buildSubagentToolAllowlist, buildChildExtensionArgs, buildPiPromptArgs, @@ -1838,6 +1844,8 @@ async function launchSubagent( if (agentDefs?.autoExit) { envParts.push(`PI_SUBAGENT_AUTO_EXIT=1`); } + // 传递已解析的实际模式;子进程不得从 autoExit 推断是否为交互会话。 + envParts.push(buildSubagentInteractiveEnvironment(effectiveInteractive)); envParts.push(`PI_SUBAGENT_SESSION=${shellEscape(subagentSessionFile)}`); envParts.push(`PI_SUBAGENT_ID=${shellEscape(id)}`); envParts.push(`PI_SUBAGENT_ACTIVITY_FILE=${shellEscape(activityFile)}`); @@ -2564,6 +2572,8 @@ export default function subagentsExtension(pi: ExtensionAPI) { if (autoExit) { resumeEnvParts.push(`PI_SUBAGENT_AUTO_EXIT=1`); } + // resume 的模式由显式 autoExit 参数解析后传递,避免子进程自行猜测。 + resumeEnvParts.push(buildSubagentInteractiveEnvironment(interactive)); const resumeEnvPrefix = resumeEnvParts.join(" ") + " "; const command = `${resumeEnvPrefix}${parts.join(" ")}; echo '__SUBAGENT_DONE_'$?'__'`; diff --git a/packages/pi-interactive-subagents/pi-extension/subagents/subagent-done.ts b/packages/pi-interactive-subagents/pi-extension/subagents/subagent-done.ts index b74d0c28..3ecd572f 100644 --- a/packages/pi-interactive-subagents/pi-extension/subagents/subagent-done.ts +++ b/packages/pi-interactive-subagents/pi-extension/subagents/subagent-done.ts @@ -27,6 +27,22 @@ const i18n = createTranslator(loadCatalog(new URL("../../locales/index.json", im const ASSISTANT_ROLE = "assistant"; const NORMAL_STOP_REASON = "stop"; const ABORTED_STOP_REASON = "aborted"; +const SQUASH_COMPLETED_EVENT = "pi-session-tools:squash-completed"; + +type SquashCompletedEvent = { + sessionId: string; + leafId: string; + continuation: "auto" | "next-user"; +}; + +/** 只接受 session-tools 公共事件的完整、可验证载荷。 */ +function isSquashCompletedEvent(value: unknown): value is SquashCompletedEvent { + if (!value || typeof value !== "object") return false; + const event = value as Partial; + return typeof event.sessionId === "string" + && typeof event.leafId === "string" + && (event.continuation === "auto" || event.continuation === "next-user"); +} /** Treat input as manual takeover only after the first agent run has started. */ export function shouldMarkUserTookOver(agentStarted: boolean): boolean { @@ -87,6 +103,8 @@ export default function (pi: ExtensionAPI) { const deniedTools = new Set(parseDeniedTools(process.env.PI_DENY_TOOLS)); const denied = [...deniedTools]; const autoExit = process.env.PI_SUBAGENT_AUTO_EXIT === "1"; + // 仅信任父端显式传入的实际模式;兼容旧父端时保守视为交互会话,不补偿提醒。 + const isAutonomous = process.env.PI_SUBAGENT_INTERACTIVE === "0"; const recorder = createSubagentActivityRecorder({ runningChildId: process.env.PI_SUBAGENT_ID, activityFile: process.env.PI_SUBAGENT_ACTIVITY_FILE, @@ -103,7 +121,12 @@ export default function (pi: ExtensionAPI) { let doneCalled = false; let userInputAfterAgentEnd = false; + let isAgentAborted = false; + let isAgentActive = false; + let activityGeneration = 0; + let activeSessionContext: ExtensionContext | null = null; let nudgeTimer: ReturnType | null = null; + const handledSquashEvents = new Set(); /** Cancel and forget the pending completion reminder, if any. */ function clearNudgeTimer(): void { @@ -113,31 +136,68 @@ export default function (pi: ExtensionAPI) { } } + /** 新输入、运行或结束会使已排队的提醒候选失效。 */ + function invalidateNudge(): void { + activityGeneration += 1; + clearNudgeTimer(); + } + + /** 压缩事件到达时重新确认仍是同一空闲 session 和 leaf。 */ + function isCurrentSquashEvent(event: SquashCompletedEvent, generation: number): boolean { + const sessionManager = activeSessionContext?.sessionManager; + return generation === activityGeneration + && !doneCalled + && !userInputAfterAgentEnd + && !userTookOver + && !isAgentAborted + && !isAgentActive + && activeSessionContext?.isIdle() === true + && activeSessionContext.hasPendingMessages() === false + && sessionManager?.getSessionId() === event.sessionId + && sessionManager.getLeafId() === event.leafId; + } + /** - * After a subagent stops normally, schedule a nudge reminding it to call - * subagent_done if it hasn't already. Error and aborted runs are excluded. - * - * Each call replaces any pending nudge, so repeated agent_end events - * automatically reset the timer. The nudge only fires if no new agent - * activity or user input arrives within NUDGE_DELAY_MS. + * 在当前 idle 状态保持到延迟结束时才发送提醒,避免旧 session 的队列泄漏到新活动。 + * 每次调用替换旧 timer,保留正常 stop 的既有单次提醒语义。 */ - function scheduleAgentEndNudge(): void { + function scheduleAgentEndNudge( + messageKey: "agentEndNudge" | "squashCompletionNudge" = "agentEndNudge", + stillEligible: () => boolean = () => !doneCalled && !userInputAfterAgentEnd, + ): void { clearNudgeTimer(); // 不论 autoExit 是否启用,都必须 nudge — autoExit 已被移除, // agent 正常结束 turn 后只能靠主动调用 subagent_done 才能真正退出。 - if (NUDGE_DISABLED || doneCalled) return; + if (NUDGE_DISABLED || doneCalled || !stillEligible()) return; nudgeTimer = setTimeout(() => { nudgeTimer = null; - if (doneCalled || userInputAfterAgentEnd) return; + if (!stillEligible()) return; pi.sendUserMessage( - i18n.t("agentEndNudge"), + i18n.t(messageKey), { deliverAs: "followUp" }, ); }, NUDGE_DELAY_MS); } + /** 仅自主子 Agent 的成功 next-user 压缩可补偿一次完成提醒。 */ + function scheduleSquashCompletionNudge(event: SquashCompletedEvent): void { + if (event.continuation !== "next-user" || !isAutonomous || NUDGE_DISABLED) return; + + const eventKey = `${event.sessionId}:${event.leafId}:${event.continuation}`; + if (handledSquashEvents.has(eventKey)) return; + + const generation = activityGeneration; + if (!isCurrentSquashEvent(event, generation)) return; + + handledSquashEvents.add(eventKey); + scheduleAgentEndNudge( + "squashCompletionNudge", + () => isCurrentSquashEvent(event, generation), + ); + } + /** Render the subagent identity and tool availability widget. */ function renderWidget(ctx: Pick): void { ctx.ui.setWidget( @@ -198,39 +258,52 @@ export default function (pi: ExtensionAPI) { recorder.sessionStart(); doneCalled = false; userInputAfterAgentEnd = false; - clearNudgeTimer(); + isAgentAborted = false; + isAgentActive = false; + userTookOver = false; + activeSessionContext = ctx; + handledSquashEvents.clear(); + invalidateNudge(); const tools = pi.getAllTools(); toolNames = tools.map((t) => t.name).sort(); renderWidget(ctx); }); - pi.on("input", () => { + pi.on("input", (event): void => { recorder.input(); - // User typed something — they are in control, cancel any pending nudge. + // 任意输入都是新活动,保留普通 stop 原有的取消提醒语义。 userInputAfterAgentEnd = true; - clearNudgeTimer(); - // Ignore the initial task message that starts an autonomous subagent. - // Only inputs after the first agent run has started count as user takeover. - if (!shouldMarkUserTookOver(agentStarted)) return; + invalidateNudge(); + // extension 输入不是人工接管,不能把补偿提醒误判成用户已接手。 + if (event.source === "extension" || !shouldMarkUserTookOver(agentStarted)) return; userTookOver = true; }); pi.on("before_agent_start", () => { recorder.beforeAgentStart(); // Agent is about to generate — clear any pending nudge; the AI is active. - clearNudgeTimer(); + isAgentActive = true; + invalidateNudge(); }); pi.on("agent_start", () => { agentStarted = true; recorder.agentStart(); // Agent has started a new generation cycle — clear any pending nudge. + isAgentActive = true; + isAgentAborted = false; userInputAfterAgentEnd = false; - clearNudgeTimer(); + invalidateNudge(); }); pi.on("agent_end", (event, ctx) => { + isAgentActive = false; + isAgentAborted = !shouldScheduleAgentEndNudge(event.messages) + && event.messages?.some((message) => + message.role === ASSISTANT_ROLE && message.stopReason === ABORTED_STOP_REASON + ) === true; + activeSessionContext = ctx; // auto-exit 已彻底移除:agent 必须主动调用 subagent_done 工具才能结束 session。 // 之前的 autoExit 短路会在 agent 正常结束 turn 时直接写 { type: "done" } 到 // .exit 文件,绕过 subagent_done 工具。这会让 workflow 系统(启用 @@ -249,6 +322,12 @@ export default function (pi: ExtensionAPI) { } }); + pi.on("agent_settled", (event): void => { + if ((event as { aborted?: unknown }).aborted !== true) return; + isAgentAborted = true; + invalidateNudge(); + }); + pi.on("turn_start", (event) => { recorder.turnStart((event as any).turnIndex); }); @@ -290,10 +369,16 @@ export default function (pi: ExtensionAPI) { }); pi.on("session_shutdown", (event) => { - clearNudgeTimer(); + isAgentActive = false; + activeSessionContext = null; + invalidateNudge(); recorder.sessionShutdown((event as any).reason); }); + pi.events.on(SQUASH_COMPLETED_EVENT, (data): void => { + if (isSquashCompletedEvent(data)) scheduleSquashCompletionNudge(data); + }); + // Toggle expand/collapse with Ctrl+J pi.registerShortcut("ctrl+j", { description: "Toggle subagent tools widget", @@ -325,7 +410,7 @@ export default function (pi: ExtensionAPI) { } doneCalled = true; - clearNudgeTimer(); + invalidateNudge(); recorder.callerPing(); const exitData = { type: "ping" as const, @@ -431,7 +516,7 @@ export default function (pi: ExtensionAPI) { } doneCalled = true; - clearNudgeTimer(); + invalidateNudge(); recorder.subagentDone(); if (sessionFile) { diff --git a/packages/pi-interactive-subagents/test/squash-done-integration.test.ts b/packages/pi-interactive-subagents/test/squash-done-integration.test.ts new file mode 100644 index 00000000..76cfe33e --- /dev/null +++ b/packages/pi-interactive-subagents/test/squash-done-integration.test.ts @@ -0,0 +1,357 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { installNoticeRenderer, resetNoticeRenderer } from "pi-extensions-i18n"; +import contextFoldExtension from "../../pi-session-tools/src/session-tail-compaction.ts"; +import { SESSION_SQUASH_TYPE } from "../../pi-session-tools/src/session-tail-compaction-utils.ts"; +import registerSubagentDone from "../pi-extension/subagents/subagent-done.ts"; + +const SQUASH_COMPLETED_EVENT = "pi-session-tools:squash-completed"; +const SQUASH_COMPLETION_NUDGES = new Set([ + "【压缩完成提醒】\n• 任务状态已保存,且当前正在等待上级输入。\n• 若已完成 → 调用 subagent_done 上报结果。\n• 需要主 agent 协助 → 调用 caller_ping;仍在处理 → 忽略。", + "[Compaction completion reminder]\n• Your task state has been saved and the session is waiting for the parent.\n• If done → call subagent_done to report your result.\n• Need help from the main agent → call caller_ping; still working → ignore.", +]); + +type ExtensionHandler = (event: unknown, ctx: unknown) => unknown | Promise; + +function assertExpectedNudge(message: string | undefined, expected: ReadonlySet): void { + assert.ok(expected.has(message ?? "")); +} +type BusHandler = (data: unknown) => void; +type RegisteredTool = { + name: string; + execute?: ( + toolCallId: string, + params: { from: number; summary: string; continuation: "auto" | "next-user" }, + signal: undefined, + onUpdate: undefined, + ctx: unknown, + ) => Promise<{ terminate?: boolean; isError?: boolean }>; +}; +type SessionEntry = { + type: "message" | "custom_message"; + id: string; + parentId: string | null; + timestamp: string; + customType?: string; + content?: string; + details?: Record; + display?: boolean; + message?: { role: string; content: string; timestamp: number }; +}; +type HarnessOptions = { + consumerFirst?: boolean; + interactive?: "0" | "1" | undefined; + failBranch?: boolean; + appendSnapshot?: boolean; + isIdle?: boolean; + hasPendingMessages?: boolean; +}; + +function asRecord(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record + : {}; +} + +type Harness = { + context: { + sessionManager: { + getBranch(): SessionEntry[]; + getSessionId(): string; + getLeafId(): string; + branch(entryId: string): void; + }; + getContextUsage(): { tokens: number }; + isIdle(): boolean; + hasPendingMessages(): boolean; + mode: "tui"; + ui: { notify(message: string): void; setWidget(): void }; + }; + tools: RegisteredTool[]; + run(event: string, payload?: unknown): Promise; + sentUserMessages: string[]; + setIdle(value: boolean): void; + setPending(value: boolean): void; +}; + +async function withEnv( + values: Record, + run: () => T | Promise, +): Promise { + const saved = Object.fromEntries( + Object.keys(values).map((key) => [key, process.env[key]]), + ) as Record; + try { + for (const [key, value] of Object.entries(values)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + return await run(); + } finally { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +} + +function createHarness(options: HarnessOptions = {}): Harness { + const handlers = new Map(); + const busHandlers = new Map(); + const tools: RegisteredTool[] = []; + const sentUserMessages: string[] = []; + const initialBranch: SessionEntry[] = [ + { + type: "message", + id: "user-1", + parentId: null, + timestamp: "2026-01-01T00:00:00.000Z", + message: { role: "user", content: "完成任务", timestamp: 1 }, + }, + { + type: "message", + id: "assistant-1", + parentId: "user-1", + timestamp: "2026-01-01T00:00:01.000Z", + message: { role: "assistant", content: "处理中", timestamp: 2 }, + }, + ]; + let branch = [...initialBranch]; + let isIdle = options.isIdle ?? true; + let hasPendingMessages = options.hasPendingMessages ?? false; + let snapshotNumber = 0; + + const context = { + sessionManager: { + getBranch(): SessionEntry[] { + return branch; + }, + getSessionId(): string { + return "session-1"; + }, + getLeafId(): string { + return branch[branch.length - 1]?.id ?? ""; + }, + branch(entryId: string): void { + if (options.failBranch) throw new Error("branch failed"); + const start = branch.findIndex((entry) => entry.id === entryId); + branch = start >= 0 ? branch.slice(0, start + 1) : []; + }, + }, + getContextUsage(): { tokens: number } { + return { tokens: 10 }; + }, + isIdle(): boolean { + return isIdle; + }, + hasPendingMessages(): boolean { + return hasPendingMessages; + }, + mode: "tui" as const, + ui: { + notify(_message: string): void {}, + setWidget(): void {}, + }, + }; + + const api = { + on(event: string, handler: ExtensionHandler): void { + const eventHandlers = handlers.get(event) ?? []; + eventHandlers.push(handler); + handlers.set(event, eventHandlers); + }, + events: { + on(channel: string, handler: BusHandler): () => void { + const channelHandlers = busHandlers.get(channel) ?? []; + channelHandlers.push(handler); + busHandlers.set(channel, channelHandlers); + return () => undefined; + }, + emit(channel: string, data: unknown): void { + for (const handler of busHandlers.get(channel) ?? []) handler(data); + }, + }, + registerTool(tool: RegisteredTool): void { + tools.push(tool); + }, + registerCommand(): void {}, + registerShortcut(): void {}, + registerMessageRenderer(): void {}, + getActiveTools(): string[] { + return ["read", "session_log", "session_squash"]; + }, + setActiveTools(): void {}, + getAllTools(): Array<{ name: string }> { + return []; + }, + sendMessage(message: { customType?: string; content?: string; details?: Record }, sendOptions?: { triggerTurn?: boolean }): void { + if ( + options.appendSnapshot !== false + && message.customType === SESSION_SQUASH_TYPE + && sendOptions?.triggerTurn === false + ) { + snapshotNumber += 1; + branch.push({ + type: "custom_message", + id: `squash-${snapshotNumber}`, + parentId: "user-1", + timestamp: "2026-01-01T00:00:02.000Z", + customType: SESSION_SQUASH_TYPE, + content: message.content, + details: message.details, + display: true, + }); + } + }, + sendUserMessage(message: string): void { + sentUserMessages.push(message); + }, + appendEntry(customType: string, data: unknown): void { + snapshotNumber += 1; + branch.push({ + type: "custom_message", + id: `notice-${snapshotNumber}`, + parentId: branch[branch.length - 1]?.id ?? null, + timestamp: "2026-01-01T00:00:03.000Z", + customType, + content: "", + details: asRecord(data), + display: true, + }); + }, + registerEntryRenderer(): void {}, + }; + + const extensionApi = api as unknown as ExtensionAPI; + resetNoticeRenderer(); + installNoticeRenderer(api); + const loadExtensions = (): void => { + contextFoldExtension(extensionApi); + registerSubagentDone(extensionApi); + }; + const loadConsumerFirst = (): void => { + registerSubagentDone(extensionApi); + contextFoldExtension(extensionApi); + }; + (options.consumerFirst ? loadConsumerFirst : loadExtensions)(); + + return { + context, + tools, + sentUserMessages, + async run(event: string, payload: unknown = {}): Promise { + for (const handler of handlers.get(event) ?? []) await handler(payload, context); + }, + setIdle(value: boolean): void { + isIdle = value; + }, + setPending(value: boolean): void { + hasPendingMessages = value; + }, + }; +} + +async function runSuccessfulNextUserSquash( + harness: Harness, + shouldStartSession = true, +): Promise { + if (shouldStartSession) await harness.run("session_start"); + const squashTool = harness.tools.find((tool) => tool.name === "session_squash"); + assert.ok(squashTool?.execute); + const result = await squashTool.execute( + "squash-call", + { from: 0, summary: "完成", continuation: "next-user" }, + undefined, + undefined, + harness.context, + ); + assert.equal(result.terminate, true); + await harness.run("tool_call", { toolName: "session_squash" }); + await harness.run("agent_end", { messages: [{ role: "assistant", stopReason: "toolUse" }] }); + await harness.run("agent_settled"); +} + +test("session squash completion reaches autonomous subagent once through the shared event bus", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + // 两种注册顺序都共享同一 pi.events 实例,不能靠手工 emit 冒充生产者。 + for (const consumerFirst of [false, true]) { + await withEnv( + { PI_SUBAGENT_INTERACTIVE: "0", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, + async (): Promise => { + const harness = createHarness({ consumerFirst }); + await runSuccessfulNextUserSquash(harness); + t.mock.timers.tick(1000); + assert.equal(harness.sentUserMessages.length, 1); + assertExpectedNudge(harness.sentUserMessages[0], SQUASH_COMPLETION_NUDGES); + }, + ); + } +}); + +async function runInputScenario( + source: "interactive" | "extension", + tick: () => void, + expectedNudges?: ReadonlySet, +): Promise { + const harness = createHarness(); + await harness.run("session_start"); + await harness.run("agent_start"); + await harness.run("input", { source }); + await harness.run("agent_start"); + await runSuccessfulNextUserSquash(harness, false); + tick(); + assert.equal(harness.sentUserMessages.length, expectedNudges ? 1 : 0); + if (expectedNudges) assertExpectedNudge(harness.sentUserMessages[0], expectedNudges); +} + +test("manual takeover persists across a new run while extension input does not", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + await withEnv( + { PI_SUBAGENT_INTERACTIVE: "0", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, + () => runInputScenario("interactive", () => t.mock.timers.tick(1000)), + ); + await withEnv( + { PI_SUBAGENT_INTERACTIVE: "0", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, + () => runInputScenario("extension", () => t.mock.timers.tick(1000), SQUASH_COMPLETION_NUDGES), + ); +}); + +test("shared squash event bus rejects unsafe producer and consumer states", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const cases: Array<{ name: string; options: HarnessOptions; continuation: "auto" | "next-user" }> = [ + { name: "branch failure", options: { failBranch: true }, continuation: "next-user" }, + { name: "missing persisted snapshot", options: { appendSnapshot: false }, continuation: "next-user" }, + { name: "auto continuation", options: {}, continuation: "auto" }, + { name: "interactive child", options: { interactive: "1" }, continuation: "next-user" }, + { name: "busy child", options: { isIdle: false }, continuation: "next-user" }, + { name: "queued child", options: { hasPendingMessages: true }, continuation: "next-user" }, + ]; + + for (const item of cases) { + await withEnv( + { PI_SUBAGENT_INTERACTIVE: item.options.interactive ?? "0", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, + async (): Promise => { + const harness = createHarness(item.options); + await harness.run("session_start"); + const squashTool = harness.tools.find((tool) => tool.name === "session_squash"); + assert.ok(squashTool?.execute); + const result = await squashTool.execute( + "squash-call", + { from: 0, summary: "完成", continuation: item.continuation }, + undefined, + undefined, + harness.context, + ); + assert.equal(result.terminate, true); + if (item.options.failBranch) { + await assert.rejects(() => harness.run("agent_settled"), /branch failed/); + } else { + await harness.run("agent_settled"); + } + t.mock.timers.tick(1000); + assert.equal(harness.sentUserMessages.length, 0, item.name); + }, + ); + } +}); diff --git a/packages/pi-interactive-subagents/test/subagent-done-nudge.test.ts b/packages/pi-interactive-subagents/test/subagent-done-nudge.test.ts index 5f5c0cb8..9b6fa238 100644 --- a/packages/pi-interactive-subagents/test/subagent-done-nudge.test.ts +++ b/packages/pi-interactive-subagents/test/subagent-done-nudge.test.ts @@ -1,6 +1,121 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { shouldScheduleAgentEndNudge } from "../pi-extension/subagents/subagent-done.ts"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import registerSubagentDone, { + shouldScheduleAgentEndNudge, +} from "../pi-extension/subagents/subagent-done.ts"; + +const SQUASH_COMPLETED_EVENT = "pi-session-tools:squash-completed"; + +type EventHandler = (event: unknown, ctx: unknown) => void; +type BusHandler = (data: unknown) => void; +type EventRegistry = { + handlers: Map; + on(event: string, handler: EventHandler): void; + events: { + on(channel: string, handler: BusHandler): () => void; + emit(channel: string, data: unknown): void; + }; +}; +type NudgeFixture = { + api: { events: EventRegistry["events"] }; + ctx: { + sessionManager: { getSessionId(): string; getLeafId(): string }; + ui: { setWidget(): void }; + isIdle(): boolean; + hasPendingMessages(): boolean; + }; + handlers: Map; + registeredTools: unknown[]; + sentUserMessages: string[]; + setIdle(isIdle: boolean): void; + setPending(hasPendingMessages: boolean): void; +}; + +function createEventRegistry(): EventRegistry { + const handlers = new Map(); + const busHandlers = new Map(); + return { + handlers, + on(event: string, handler: EventHandler): void { + handlers.set(event, handler); + }, + events: { + on(channel: string, handler: BusHandler): () => void { + const channelHandlers = busHandlers.get(channel) ?? []; + channelHandlers.push(handler); + busHandlers.set(channel, channelHandlers); + return () => undefined; + }, + emit(channel: string, data: unknown): void { + for (const handler of busHandlers.get(channel) ?? []) handler(data); + }, + }, + }; +} + +function createNudgeFixture(): NudgeFixture { + const registry = createEventRegistry(); + const sentUserMessages: string[] = []; + const registeredTools: unknown[] = []; + let isIdle = true; + let hasPendingMessages = false; + const ctx = { + sessionManager: { getSessionId: () => "session-1", getLeafId: () => "squash-1" }, + ui: { setWidget() {} }, + isIdle: () => isIdle, + hasPendingMessages: () => hasPendingMessages, + }; + const api = { + ...registry, + registerTool(tool: unknown): void { registeredTools.push(tool); }, + registerShortcut(): void {}, + getAllTools(): unknown[] { return []; }, + sendUserMessage(message: string): void { sentUserMessages.push(message); }, + }; + registerSubagentDone(api as unknown as ExtensionAPI); + registry.handlers.get("session_start")?.({}, ctx); + return { + api, + ctx, + handlers: registry.handlers, + registeredTools, + sentUserMessages, + setIdle(value: boolean): void { isIdle = value; }, + setPending(value: boolean): void { hasPendingMessages = value; }, + }; +} + +function applyEnv(values: Record): void { + for (const [key, value] of Object.entries(values)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +} + +function withEnv(values: Record, run: () => void): void { + const saved = Object.fromEntries( + Object.keys(values).map((key) => [key, process.env[key]]), + ) as Record; + try { + applyEnv(values); + run(); + } finally { + applyEnv(saved); + } +} + +function emitSquashCompleted( + fixture: NudgeFixture, + overrides: Record = {}, +): void { + fixture.api.events.emit(SQUASH_COMPLETED_EVENT, { + sessionId: "session-1", + leafId: "squash-1", + continuation: "next-user", + ...overrides, + }); +} test("completion nudge runs after the agent stops normally", () => { assert.equal( @@ -29,3 +144,45 @@ test("completion nudge ignores output-limit stops", () => { false, ); }); + +test("successful next-user squash emits one autonomous completion nudge", (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + withEnv({ PI_SUBAGENT_INTERACTIVE: "0", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, () => { + const fixture = createNudgeFixture(); + emitSquashCompleted(fixture); + emitSquashCompleted(fixture); + t.mock.timers.tick(1000); + assert.equal(fixture.sentUserMessages.length, 1); + assert.match(fixture.sentUserMessages[0] ?? "", /subagent_done/); + }); +}); + +test("squash completion nudge keeps mode and activity safety boundaries", (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + withEnv({ PI_SUBAGENT_INTERACTIVE: "1", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, () => { + const interactive = createNudgeFixture(); + emitSquashCompleted(interactive); + t.mock.timers.tick(1000); + assert.equal(interactive.sentUserMessages.length, 0); + }); + + withEnv({ PI_SUBAGENT_INTERACTIVE: "0", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, () => { + const fixture = createNudgeFixture(); + emitSquashCompleted(fixture, { continuation: "auto" }); + fixture.handlers.get("input")?.({ source: "extension" }, fixture.ctx); + emitSquashCompleted(fixture); + t.mock.timers.tick(1000); + assert.equal(fixture.sentUserMessages.length, 0); + }); + + withEnv({ PI_SUBAGENT_INTERACTIVE: "0", PI_SUBAGENT_NUDGE_DELAY_MS: "1000" }, () => { + const busy = createNudgeFixture(); + busy.setIdle(false); + emitSquashCompleted(busy); + const queued = createNudgeFixture(); + queued.setPending(true); + emitSquashCompleted(queued); + t.mock.timers.tick(1000); + assert.equal(busy.sentUserMessages.length + queued.sentUserMessages.length, 0); + }); +}); diff --git a/packages/pi-interactive-subagents/test/test.ts b/packages/pi-interactive-subagents/test/test.ts index 76b04616..7108adb8 100644 --- a/packages/pi-interactive-subagents/test/test.ts +++ b/packages/pi-interactive-subagents/test/test.ts @@ -1395,6 +1395,12 @@ describe("subagent-done.ts", () => { setWidget() {}, hasUI: false, }, + isIdle(): boolean { + return true; + }, + hasPendingMessages(): boolean { + return false; + }, }; return { handlers, @@ -1414,6 +1420,12 @@ describe("subagent-done.ts", () => { sentUserMessages.push(message); }, sendMessage() {}, + events: { + on(): () => void { + return () => undefined; + }, + emit(): void {}, + }, getAllTools() { return []; }, @@ -1662,6 +1674,27 @@ describe("tool registration", () => { }); }); + it("passes the resolved interactive mode without inferring it from auto-exit", () => { + const testApi = subagentsModule.__test__; + assert.equal(testApi.buildSubagentInteractiveEnvironment(false), "PI_SUBAGENT_INTERACTIVE=0"); + assert.equal(testApi.buildSubagentInteractiveEnvironment(true), "PI_SUBAGENT_INTERACTIVE=1"); + assert.equal( + testApi.buildSubagentInteractiveEnvironment( + testApi.resolveEffectiveInteractive( + { name: "A", task: "T", interactive: true }, + { autoExit: true }, + ), + ), + "PI_SUBAGENT_INTERACTIVE=1", + ); + assert.equal( + testApi.buildSubagentInteractiveEnvironment( + testApi.resolveResumeLaunchBehavior({ autoExit: true }).interactive, + ), + "PI_SUBAGENT_INTERACTIVE=0", + ); + }); + it("uses the global switch to gate all subagent lifecycle tools", () => { const testApi = getToolRegistrationTestApi(); const denied = testApi.resolveDenyTools(null, false); diff --git a/packages/pi-session-tools/README.md b/packages/pi-session-tools/README.md index c11d19e7..b5c063cf 100644 --- a/packages/pi-session-tools/README.md +++ b/packages/pi-session-tools/README.md @@ -15,6 +15,8 @@ Call `session_log` first, use the index of a completed turn as `from`, and pass Squash at a safe task or phase checkpoint, such as after a phase or verification completes, a key decision is settled, or before entering the next phase; the whole task need not be delivered. The snapshot should focus on what was done in the squashed range, its target, final outcomes, and verification, then state the exact stopping point, remaining work, artifact state, and next action. Completed work must not be repeated under remaining work. Use `VERIFIED`, `INFERRED`, `UNKNOWN`, `NOT VERIFIED`, or `BLOCKED` when needed. Preserve effective task state rather than maintenance mechanics such as context thresholds, `session_log`, `session_squash`, or session switching. Explicitly select the continuation mode on every squash: use `continuation: "auto"` when work can resume immediately; when the current task is complete and the next action requires new user input, use `continuation: "next-user"` to save the snapshot without triggering another model turn. If the snapshot conflicts with workspace, Git, or test evidence, the evidence wins and the conflict must be reported. +After a `next-user` branch and its snapshot are both persisted successfully, the extension publishes the public `pi.events` event `pi-session-tools:squash-completed` with `{ sessionId, leafId, continuation }`. It verifies the persisted tail entry before publishing and does not emit for validation, branch, or summary-write failures. `auto` does not publish this event because its deferred append has no public completion hook. Consumers must treat the event as post-success only and re-check session identity before acting. + ## Install ```bash diff --git a/packages/pi-session-tools/README.zh-CN.md b/packages/pi-session-tools/README.zh-CN.md index 8794fc64..22ea8e5c 100644 --- a/packages/pi-session-tools/README.zh-CN.md +++ b/packages/pi-session-tools/README.zh-CN.md @@ -27,6 +27,8 @@ pi install npm:pi-session-tools 任务或阶段到达安全停点时都可以压缩,例如阶段完成、验证完成、关键决策落定或准备进入下一阶段;无需等整个任务交付。摘要重点说明被压缩范围内做了什么、作用对象、最终结果和验证,并明确当前准确停点、剩余事项、制品状态和下一步。已完成工作不得重复列入剩余事项;必要时使用 `VERIFIED`、`INFERRED`、`UNKNOWN`、`NOT VERIFIED` 或 `BLOCKED`。摘要只保留有效任务状态,不记录上下文阈值、`session_log`、`session_squash` 或会话切换等维护过程。每次压缩都必须显式选择接续模式:仍有可立即执行的工作时使用 `continuation: "auto"`;当前任务已完成且下一步必须等待用户新输入时使用 `continuation: "next-user"`,只保存快照而不额外触发模型回合。若摘要与 workspace、Git 或测试证据冲突,以实际证据为准并报告冲突。 +仅当 `next-user` 的新分支和摘要均成功持久化后,扩展才发布公共 `pi.events` 事件 `pi-session-tools:squash-completed`,载荷为 `{ sessionId, leafId, continuation }`。发布前会校验真实分支末尾快照;参数校验、切分支或写入摘要失败时不会发布。`auto` 的摘要由延迟动作追加,当前没有公共完成钩子,因此不发布该事件。消费者只能把它视为成功后的信号,动作前仍须复核会话身份。 + ## 上下文阈值提示 对话变长跨过阈值时(默认 150k / 200k / 250k / 300k tokens),会向主 agent 显示“已用 tokens / context window(占比)”,并提醒它在最近的任务或阶段安全停点压缩,不必等待整个任务结束。提醒不强制;仅在模型正常停止时触发,用户手动终止或提供方异常不会触发。可配置: diff --git a/packages/pi-session-tools/src/session-tail-compaction.ts b/packages/pi-session-tools/src/session-tail-compaction.ts index ee0a82c6..f17811e5 100644 --- a/packages/pi-session-tools/src/session-tail-compaction.ts +++ b/packages/pi-session-tools/src/session-tail-compaction.ts @@ -153,6 +153,9 @@ const TAIL_START_ERROR_I18N_KEY: Record = { const CONTINUATION_AUTO = "auto"; const CONTINUATION_NEXT_USER = "next-user"; +/** 压缩摘要持久化成功后广播,供同会话扩展补偿自主子 Agent 的完成提醒。 */ +const SQUASH_COMPLETED_EVENT = "pi-session-tools:squash-completed"; + type SquashContinuation = | typeof CONTINUATION_AUTO | typeof CONTINUATION_NEXT_USER; @@ -397,6 +400,26 @@ type PendingTailCompaction = { continuation: SquashContinuation; }; +/** 校验 next-user 同步写入的末尾快照,避免把 sendMessage 返回当作持久化成功。 */ +function isPersistedSquashEntry( + entry: SessionEntry | undefined, + summary: string, + data: TailCompactionData, +): entry is SessionEntry & { id: string } { + if (!entry || entry.type !== "custom_message" || entry.customType !== SESSION_SQUASH_TYPE) { + return false; + } + if (entry.content !== summary || !entry.details || typeof entry.details !== "object") { + return false; + } + const details = entry.details as Partial; + return typeof entry.id === "string" + && details.startEntryId === data.startEntryId + && details.sourceLeafId === data.sourceLeafId + && details.fromUserInputIndex === data.fromUserInputIndex + && details.summary === data.summary; +} + type ForceSquashState = { sessionId: string; previousActiveTools: string[]; @@ -668,6 +691,8 @@ export default function contextFoldExtension(pi: ExtensionAPI) { tokensBefore: ctx.getContextUsage()?.tokens ?? 0, }; + let persistedSquashEntryId: string | null = null; + try { // 起始 user turn 作为新分支锚点保留,确保后续 session_log 索引稳定; // continuation=next-user 会阻止已完成任务立即重答这条旧 prompt。 @@ -691,6 +716,17 @@ export default function contextFoldExtension(pi: ExtensionAPI) { { triggerTurn: request.continuation === CONTINUATION_AUTO }, ); pending = null; + + // next-user 的写入在当前调用内完成,必须从真实分支末尾取得成功证据。 + // auto 通过 deferred action 追加快照,当前没有可观察的公共完成钩子,因此不广播。 + const compactedBranch = ctx.sessionManager.getBranch(); + const persistedEntry = compactedBranch[compactedBranch.length - 1]; + if ( + request.continuation === CONTINUATION_NEXT_USER + && isPersistedSquashEntry(persistedEntry, summary, data) + ) { + persistedSquashEntryId = persistedEntry.id; + } } catch (error) { pending = null; throw new Error(i18n.t("branchFailed", { error: String(error) })); @@ -703,6 +739,29 @@ export default function contextFoldExtension(pi: ExtensionAPI) { }), "info", ); + + // TUI 通知会追加自定义条目并推进 leaf;通知后重新确认同一 session 仍保留已验证的摘要。 + if (persistedSquashEntryId && ctx.sessionManager.getSessionId() === request.sessionId) { + const currentBranch = ctx.sessionManager.getBranch(); + const persistedEntry = currentBranch.find((entry) => entry.id === persistedSquashEntryId); + const currentLeafId = ctx.sessionManager.getLeafId(); + if ( + currentLeafId + && isPersistedSquashEntry(persistedEntry, summary, data) + ) { + try { + pi.events.emit(SQUASH_COMPLETED_EVENT, { + sessionId: request.sessionId, + leafId: currentLeafId, + continuation: request.continuation, + }); + } catch (error) { + process.stderr.write( + `[pi-session-tools] squash-completed event failed: ${String(error)}\n`, + ); + } + } + } }); pi.on("session_shutdown", () => { diff --git a/packages/pi-session-tools/tests/session-tail-compaction.test.ts b/packages/pi-session-tools/tests/session-tail-compaction.test.ts index eda252d2..896665bc 100644 --- a/packages/pi-session-tools/tests/session-tail-compaction.test.ts +++ b/packages/pi-session-tools/tests/session-tail-compaction.test.ts @@ -53,6 +53,18 @@ type RegisteredCommand = { handler: (args: string, context: unknown) => Promise; }; +type SquashMessage = { + customType?: string; + content?: string; + details?: Record; +}; + +function isSquashMessage(message: unknown): message is SquashMessage { + return !!message + && typeof message === "object" + && (message as { customType?: string }).customType === SESSION_SQUASH_TYPE; +} + const VALID_HANDOFF_SUMMARY = [ "# Handoff: test", "## Timeline of user and agent work", @@ -106,6 +118,8 @@ test("强制模式限制工具,并按 continuation 控制压缩后接续", asy const commands = new Map(); const handlers = new Map(); const sentMessages: Array<{ message: unknown; options: unknown }> = []; + const emittedEvents: Array<{ channel: string; data: unknown }> = []; + let nextSquashEntryId = 1; let activeTools = ["read", "bash", "session_log", "session_squash"]; const pi = { /** 收集扩展注册的工具定义,供测试直接调用。 */ @@ -131,6 +145,26 @@ test("强制模式限制工具,并按 continuation 控制压缩后接续", asy /** 记录扩展发送的强制任务和压缩摘要消息。 */ sendMessage(message: unknown, options: unknown) { sentMessages.push({ message, options }); + if (isSquashMessage(message) && options && (options as { triggerTurn?: boolean }).triggerTurn === false) { + branch.push({ + type: "custom_message", + id: `squash-${nextSquashEntryId++}`, + parentId: "a1", + timestamp: "2026-01-01T00:00:02.000Z", + customType: SESSION_SQUASH_TYPE, + content: message.content ?? "", + display: true, + details: message.details ?? {}, + }); + } + }, + events: { + emit(channel: string, data: unknown): void { + emittedEvents.push({ channel, data }); + }, + on(): () => void { + return () => undefined; + }, }, } as unknown as ExtensionAPI; @@ -212,13 +246,15 @@ test("强制模式限制工具,并按 continuation 控制压缩后接续", asy const branchTargets: string[] = []; const notifications: string[] = []; let abortCount = 0; + let shouldFailBranch = false; const sessionManager = { getBranch: () => branch, getSessionId: () => "session-1", - getLeafId: () => "a1", + getLeafId: () => branch[branch.length - 1]?.id ?? "", /** 记录折叠时选择的分支起点。 */ branch(entryId: string) { branchTargets.push(entryId); + if (shouldFailBranch) throw new Error("branch failed"); }, buildContextEntries: () => branch, }; @@ -399,6 +435,26 @@ test("强制模式限制工具,并按 continuation 控制压缩后接续", asy ); assert.equal(allSquashMessages.length, 3); assert.deepEqual(allSquashMessages[2]?.options, { triggerTurn: true }); + assert.deepEqual( + emittedEvents, + [ + { channel: "pi-session-tools:squash-completed", data: { sessionId: "session-1", leafId: "squash-1", continuation: "next-user" } }, + { channel: "pi-session-tools:squash-completed", data: { sessionId: "session-1", leafId: "squash-2", continuation: "next-user" } }, + ], + ); + + const emittedBeforeFailedBranch = emittedEvents.length; + shouldFailBranch = true; + const failedResult = await squashTool.execute( + "tool-3", + { from: 0, summary: VALID_HANDOFF_SUMMARY, continuation: "next-user" }, + undefined, + undefined, + context, + ); + assert.equal(failedResult.terminate, true); + await assert.rejects(() => settled({}, context), /branch failed/); + assert.equal(emittedEvents.length, emittedBeforeFailedBranch); }); test("session-squash 快照以 compaction summary 语义注入上下文", async () => { @@ -720,6 +776,12 @@ test("压缩后的请求用压缩前抓到的 system 消息补回提示与工具 branch = [userEntry, squashEntry]; } }, + events: { + emit(): void {}, + on(): () => void { + return () => undefined; + }, + }, } as unknown as ExtensionAPI; sessionTailCompaction(pi);