Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(daemon): preserve native outcomes and audit bounded text (#964)

Gustavo Yef69992b18004
diff --git a/src/daemon/agent-driver/src/adapters/agy/index.test.ts b/src/daemon/agent-driver/src/adapters/agy/index.test.ts
index 327975bb7..a6b281170 100644
--- a/src/daemon/agent-driver/src/adapters/agy/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/agy/index.test.ts
@@ -64,15 +64,43 @@ describe("agy native stream ownership", () => {
expect(driver.normalizeLine(step(1, { step_type: "tool", tool_name: "bash" }))).toEqual([{ kind: "tool_output", callId: "native:1", name: "bash" }]);
expect(driver.normalizeLine(result(1))).toMatchObject([{ kind: "assistant_message_completed" }, { kind: "turn_end" }]);
});
- it.each(["ERROR", "CANCELLED", "TIMEOUT"])("discards partial content on %s and never treats it as success", (status) => {
+ it.each([
+ { status: "ERROR", error: "native failure" },
+ { status: "ERROR", error: "network interrupted unexpectedly" },
+ { status: "TIMEOUT", error: "interrupted" },
+ ])("discards partial content on $status/$error without misclassifying failure", ({ status, error }) => {
const driver = new AgyDriver();
driver.normalizeLine(line({ event: "init", conversation_id: "native" }));
begin(driver);
driver.normalizeLine(step(1, { text_delta: "partial" }));
- expect(driver.normalizeLine(result(1, { status, error: "native failure" }))).toEqual([
- { kind: "error", message: "native failure" }, { kind: "turn_end", sessionId: "native", pendingContent: "discard" },
+ expect(driver.normalizeLine(result(1, { status, error }))).toEqual([
+ { kind: "error", message: error }, { kind: "turn_end", sessionId: "native", pendingContent: "discard" },
]);
});
+ it.each([{ status: "CANCELLED" }, { status: "ERROR", error: "interrupted" }])("keeps native $status cancellation distinct from failure and discards unfinished content", (terminal) => {
+ const driver = new AgyDriver();
+ driver.normalizeLine(line({ event: "init", conversation_id: "native" }));
+ begin(driver);
+ driver.normalizeLine(step(1, { text_delta: "partial" }));
+ expect(driver.normalizeLine(result(1, terminal))).toEqual([
+ { kind: "turn_end", sessionId: "native", pendingContent: "discard", outcome: "interrupted" },
+ ]);
+ });
+ it.each([true, false])("pairs a completed tool exactly once (ACTIVE first: %s)", (activeFirst) => {
+ const driver = new AgyDriver();
+ driver.normalizeLine(line({ event: "init", conversation_id: "native" }));
+ begin(driver);
+ const tool = { step_type: "tool", tool_name: "run_command", tool_info: { parameters: { CommandLine: "echo audit" } } };
+ const events = activeFirst ? driver.normalizeLine(step(1, { ...tool, state: "ACTIVE" })) : [];
+ if (activeFirst) expect(driver.normalizeLine(step(1, { ...tool, state: "ACTIVE" }))).toEqual([]);
+ events.push(...driver.normalizeLine(step(1, tool)));
+ expect(events).toEqual([
+ { kind: "tool_call", callId: "native:1", name: "run_command", input: { CommandLine: "echo audit" } },
+ { kind: "tool_output", callId: "native:1", name: "run_command" },
+ ]);
+ expect(driver.normalizeLine(step(1, tool))).toEqual([]);
+ });
+
it("rejects malformed streams, invalid input identity and unowned results", async () => {
const invalid = new AgyDriver();
expect(invalid.normalizeLine("broken")).toMatchObject([{ kind: "error" }]);
@@ -99,6 +127,7 @@ if(process.argv.includes('--version')){console.log('1.3.4');process.exit(0)}
if(process.argv.includes('--help')){console.error('--input-format --output-format stream-json --conversation');process.exit(0)}
fs.writeFileSync('argv.json',JSON.stringify(process.argv.slice(2)));
const emit=x=>console.log(JSON.stringify(x));
+const mode=${JSON.stringify(mode)};
const requested=process.argv[process.argv.indexOf('--conversation')+1];
const resumed=process.argv.includes('--conversation');
const id=${JSON.stringify(mode)}==='mismatch'?'substitute':resumed?requested:'native';
@@ -109,9 +138,15 @@ require('node:readline').createInterface({input:process.stdin}).on('line',line=>
const input=JSON.parse(line);fs.appendFileSync('inputs.jsonl',JSON.stringify(input)+'\\n');turn++;
emit({event:'step_update',step_update:{conversation_id:id,step_index:index,state:'DONE',step_type:'user_input'}});
const done=()=>{
- const update={event:'step_update',step_update:{conversation_id:id,step_index:index+1,state:'DONE',step_type:'agent_response',text_delta:'reply '+turn,usage:{input_tokens:7,output_tokens:4,cache_read_tokens:10}}};
+ if(mode==='tools'){
+ const tool={conversation_id:id,step_index:index+1,step_type:'tool',tool_name:'run_command',tool_info:{parameters:{CommandLine:'echo fixture'}}};
+ if(turn>1){emit({event:'step_update',step_update:{...tool,state:'ACTIVE'}});emit({event:'step_update',step_update:{...tool,state:'ACTIVE'}})}
+ emit({event:'step_update',step_update:{...tool,state:'DONE'}});emit({event:'step_update',step_update:{...tool,state:'DONE'}});
+ }
+ const update={event:'step_update',step_update:{conversation_id:id,step_index:index+(mode==='tools'?2:1),state:'DONE',step_type:'agent_response',text_delta:'reply '+turn,usage:{input_tokens:7,output_tokens:4,cache_read_tokens:10}}};
emit(update);emit(update);
- const result={event:'result',result:{conversation_id:id,status:'SUCCESS',response:'reply '+turn,num_turns:turn,usage:{input_tokens:99999}}};
+ const terminal=turn===1?{'native-interrupted':{status:'ERROR',error:'interrupted',response:''},'native-cancelled':{status:'CANCELLED',response:''},'native-error':{status:'ERROR',error:'network interrupted unexpectedly',response:''}}[mode]:undefined;
+ const result={event:'result',result:{conversation_id:id,status:'SUCCESS',response:'reply '+turn,num_turns:turn,usage:{input_tokens:99999},...terminal}};
emit(result);emit(result);index+=3;
};
if(!resumed&&turn===1){const timer=setInterval(()=>{if(fs.existsSync('release')){clearInterval(timer);done()}},5)}else done();
@@ -121,6 +156,58 @@ require('node:readline').createInterface({input:process.stdin}).on('line',line=>
}
describe.skipIf(process.platform === "win32")("agy registered SDK with a real fixture process", () => {
+ it.each([
+ { mode: "native-interrupted", outcome: "interrupted" },
+ { mode: "native-cancelled", outcome: "interrupted" },
+ { mode: "native-error", outcome: "failed" },
+ ])("projects $mode through public turns and preserves next-turn progress", async ({ mode, outcome }) => {
+ const f = fixture(mode);
+ const opened = await createBuiltinAgentDriverSdk({ host: createFakeAgentDriverHost() }).open({ backend: "agy",
+ config: { model: { kind: "default" }, command: f.executable },
+ launch: { workingDirectory: f.directory, instructions: { format: "markdown", content: "" }, launchId: mode },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const session = opened.session;
+ const events: AgentEvent<BuiltinBackendSpecs, "agy">[] = [];
+ const collecting = (async () => { for await (const event of session.events) events.push(event); })();
+ try {
+ expect(await session.start({ id: "first", kind: "user", text: "first" })).toMatchObject({ status: "accepted" });
+ expect(await session.send({ id: "next", kind: "user", text: "next" })).toMatchObject({ status: "queued" });
+ writeFileSync(join(f.directory, "release"), "go");
+ await vi.waitFor(() => expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2));
+ expect(events.filter((event) => event.type === "turn_completed")).toMatchObject([
+ { commandIds: ["first"], result: { outcome } },
+ { commandIds: ["next"], result: { outcome: "success" } },
+ ]);
+ expect(events.filter((event) => event.type === "assistant_message_completed").map((event) => event.text)).toEqual(["reply 2"]);
+ expect(session.snapshot().diagnostics.metrics.physicalOpenCount).toBe(1);
+ } finally { await session.stop({ reason: "shutdown", forceAfterMs: 10 }); await session.closed; await collecting; }
+ });
+ it("publishes DONE-only and normal tool lifecycles once across persistent turns", async () => {
+ const f = fixture("tools");
+ const opened = await createBuiltinAgentDriverSdk({ host: createFakeAgentDriverHost() }).open({ backend: "agy",
+ config: { model: { kind: "default" }, command: f.executable },
+ launch: { workingDirectory: f.directory, instructions: { format: "markdown", content: "" }, launchId: "agy-tools" },
+ });
+ if (!opened.ok) throw new Error(opened.error.message);
+ const session = opened.session;
+ const events: AgentEvent<BuiltinBackendSpecs, "agy">[] = [];
+ const collecting = (async () => { for await (const event of session.events) events.push(event); })();
+ try {
+ await session.start({ id: "first", kind: "user", text: "first" });
+ await session.send({ id: "next", kind: "user", text: "next" });
+ writeFileSync(join(f.directory, "release"), "go");
+ await vi.waitFor(() => expect(events.filter((event) => event.type === "turn_completed")).toHaveLength(2));
+ expect(events.filter((event) => event.type === "tool_started")).toMatchObject([
+ { callId: "native:1", name: "run_command", input: { CommandLine: "echo fixture" } },
+ { callId: "native:4", name: "run_command", input: { CommandLine: "echo fixture" } },
+ ]);
+ expect(events.filter((event) => event.type === "tool_finished")).toMatchObject([
+ { callId: "native:1", name: "run_command" }, { callId: "native:4", name: "run_command" },
+ ]);
+ expect(session.snapshot().diagnostics.metrics).toMatchObject({ outstandingToolUses: 0, toolLifecycleMismatchCount: 0 });
+ } finally { await session.stop({ reason: "shutdown", forceAfterMs: 10 }); await session.closed; await collecting; }
+ });
it("reports a failed initial input write, fences further input and releases its process", async () => {
const f = fixture();
const driver = new AgyDriver();
diff --git a/src/daemon/agent-driver/src/adapters/agy/index.ts b/src/daemon/agent-driver/src/adapters/agy/index.ts
index f6b8f7b31..b0b9460ca 100644
--- a/src/daemon/agent-driver/src/adapters/agy/index.ts
+++ b/src/daemon/agent-driver/src/adapters/agy/index.ts
@@ -34,6 +34,7 @@ export class AgyDriver implements BackendAdapter<"agy"> {
private inputAt = "";
private usageSource = "";
private readonly usage = new SettledUsageProjector();
+ private readonly tools = new Map<number, "active" | "done">();
constructor(private readonly launchSpec?: ReturnType<typeof agySpawnSpec>) {}
@@ -76,6 +77,7 @@ export class AgyDriver implements BackendAdapter<"agy"> {
this.pending = true;
this.inputIndex = undefined;
this.usage.reset();
+ this.tools.clear();
return JSON.stringify({ event: "user", message: { content: text } });
}
@@ -111,8 +113,14 @@ export class AgyDriver implements BackendAdapter<"agy"> {
const tool = asRecord(step.tool_info);
const name = typeof step.tool_name === "string" ? step.tool_name : "tool";
const callId = `${this.sessionId}:${index}`;
- if (step.state === "ACTIVE") result.push({ kind: "tool_call", callId, name, input: tool?.parameters });
- if (step.state === "DONE") result.push({ kind: "tool_output", callId, name });
+ if ((step.state === "ACTIVE" || step.state === "DONE") && !this.tools.has(index as number)) {
+ this.tools.set(index as number, "active");
+ result.push({ kind: "tool_call", callId, name, input: tool?.parameters });
+ }
+ if (step.state === "DONE" && this.tools.get(index as number) === "active") {
+ this.tools.set(index as number, "done");
+ result.push({ kind: "tool_output", callId, name });
+ }
}
const usage = asRecord(step.usage);
if (step.state === "DONE" && usage) {
@@ -138,11 +146,15 @@ export class AgyDriver implements BackendAdapter<"agy"> {
this.previousTurns = turns as number;
this.pending = false;
const events: AdapterEvent[] = [];
+ const interrupted = result.status === "CANCELLED" || (result.status === "ERROR" && result.error === "interrupted");
if (result.status === "SUCCESS") {
if (typeof result.response !== "string") return this.fail("Antigravity CLI result is missing response text");
events.push({ kind: "assistant_message_completed", text: result.response });
- } else events.push({ kind: "error", message: typeof result.error === "string" ? result.error : `Antigravity CLI status: ${String(result.status)}` });
- events.push({ kind: "turn_end", sessionId: this.currentSessionId!, ...(result.status !== "SUCCESS" ? { pendingContent: "discard" as const } : {}) });
+ } else if (!interrupted) events.push({ kind: "error", message: typeof result.error === "string" ? result.error : `Antigravity CLI status: ${String(result.status)}` });
+ events.push({ kind: "turn_end", sessionId: this.currentSessionId!,
+ ...(result.status !== "SUCCESS" ? { pendingContent: "discard" as const } : {}),
+ ...(interrupted ? { outcome: "interrupted" as const } : {}),
+ });
return events;
}
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts b/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts
index ed077d61d..16f766e74 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/acp-lane.ts
@@ -408,10 +408,6 @@ export class AntigravityAcpLane implements RuntimeLane {
);
return;
}
- if (result.stopReason === "cancelled") {
- this.failPrompt(prompt, new Error("Antigravity ACP prompt was cancelled"), "antigravity.cancelled");
- return;
- }
const terminalOwner = this.terminalOwner ?? prompt.receipt;
this.currentPromptRequestId = null;
this.terminalOwner = null;
@@ -420,6 +416,7 @@ export class AntigravityAcpLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
+ ...(result.stopReason === "cancelled" ? { outcome: "interrupted" as const, pendingContent: "discard" as const } : {}),
} satisfies AdapterEvent);
}
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts
index a12b35bd1..d5ca12008 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/session.test.ts
@@ -70,7 +70,7 @@ createInterface({ input: process.stdin }).on("line", (line) => {
expect(events.filter((event) => event.type === "assistant_reasoning_completed").map((event) => event.text))
.toEqual(successful ? ["first reasoning", "next reasoning"] : ["next reasoning"]);
expect(events.filter((event) => event.type === "turn_completed")).toMatchObject([
- { commandIds: ["first"], result: { outcome: terminal === "interrupt" ? "interrupted" : successful ? "success" : "failed" } },
+ { commandIds: ["first"], result: { outcome: terminal === "interrupt" || terminal === "cancelled" ? "interrupted" : successful ? "success" : "failed" } },
{ commandIds: ["second"], result: { outcome: "success" } },
]);
expect(events.filter((event) => event.type === "command_accepted").map((event) => event.commandId)).toEqual(["first", "second"]);
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.test.ts b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
index 9c5bc7f88..d687ba21b 100644
--- a/src/daemon/agent-driver/src/adapters/claude/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
@@ -253,6 +253,7 @@ describe("ClaudeDriver", () => {
kind: "turn_end",
sessionId: undefined,
turnOwner: receipt,
+ outcome: "interrupted",
}]);
expect(driver.normalizeLine(terminal)).toEqual([]);
expect(process.kill).not.toHaveBeenCalled();
@@ -291,6 +292,7 @@ describe("ClaudeDriver", () => {
kind: "turn_end",
sessionId: undefined,
turnOwner: receipt,
+ outcome: "interrupted",
}]);
expect(driver.normalizeLine(terminal)).toEqual([]);
expect(process.kill).not.toHaveBeenCalled();
diff --git a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
index a57e21b8e..eb7e63cdd 100644
--- a/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.ts
@@ -192,6 +192,7 @@ export class ClaudeEventNormalizer {
kind: "turn_end",
sessionId: event.session_id ?? this.currentSession ?? undefined,
...(turnOwner ? { turnOwner } : {}),
+ ...(interruptedTerminal ? { outcome: "interrupted" as const } : {}),
});
}
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
index f8de4ac1c..6100e497d 100644
--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
@@ -526,12 +526,12 @@ describe("CodexEventNormalizer — complete owned event family", () => {
expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "contextCompaction" } }))).toEqual([{ kind: "compaction_finished" }]);
expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "exitedReviewMode" } }))).toEqual([{ kind: "review_finished" }]);
expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "agentMessage", text: "final" } }))).toEqual([{ kind: "assistant_message_completed", text: "final" }]);
- expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "reasoning", text: "thought" } }))).toEqual([{ kind: "assistant_reasoning_completed", text: "thought" }]);
+ expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "reasoning", summary: ["thought"], content: [] } }))).toEqual([{ kind: "assistant_reasoning_completed", text: "thought" }]);
expect(n.normalizeLine(notify("item/completed", { threadId: "root", turnId: "turn", item: { type: "unknown" } }))).toEqual([]);
expect(n.normalizeLine(notify("thread/tokenUsage/updated", { threadId: "root", tokenUsage: {} }))).toEqual([]);
expect(n.normalizeLine(notify("account/rateLimits/updated", { threadId: "root", rateLimits: {} }))).toEqual([]);
expect(n.normalizeLine(notify("turn/completed", { threadId: "root", turn: { id: "turn", status: "interrupted" } }))).toEqual([
- { kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn" },
+ { kind: "turn_end", sessionId: "root", turnOwner: "codex:root:turn", outcome: "interrupted" },
]);
});
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
index 261c265dc..1f3dbee73 100644
--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.ts
@@ -337,7 +337,9 @@ export class CodexEventNormalizer {
{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) },
];
}
- return [{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id) }];
+ return [{ kind: "turn_end", sessionId: this.threadId ?? undefined, turnOwner: this.turnReceipt(params.threadId, params.turn.id),
+ ...(params.turn.status === "interrupted" ? { outcome: "interrupted" as const } : {}),
+ }];
case "error":
if (params?.willRetry === true) {
@@ -527,8 +529,12 @@ export class CodexEventNormalizer {
return [{ kind: "tool_output", ...identity, name: "collab_tool_call" }];
case "agentMessage":
return [{ kind: "assistant_message_completed", text: params?.item?.text ?? "" }];
- case "reasoning":
- return [{ kind: "assistant_reasoning_completed", text: params?.item?.text ?? "" }];
+ case "reasoning": {
+ const blocks = [params?.item?.summary, params?.item?.content]
+ .find((value) => Array.isArray(value) && value.some((text: unknown) => typeof text === "string" && text.length > 0));
+ const text = blocks?.filter((value: unknown) => typeof value === "string").join("\n\n") ?? "";
+ return text.length > 0 ? [{ kind: "assistant_reasoning_completed", text }] : [];
+ }
default:
return [];
}
diff --git a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
index f70fe0b4a..ce3fd07f1 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
@@ -107,7 +107,7 @@ function isMissingSessionError(error: unknown): boolean {
export class CursorAcpLane implements RuntimeLane {
private readonly events = new EventEmitter();
private readonly pending = new Map<number, PendingRequest>();
- private readonly openToolCalls = new Set<string>();
+ private readonly toolCalls = new Map<string, string | null>();
private process: SpawnedProcessHandle | null = null;
private stdoutBuffer = "";
private requestSequence = 0;
@@ -217,7 +217,7 @@ export class CursorAcpLane implements RuntimeLane {
this.ready = false;
this.currentPromptRequestId = null;
this.terminalOwner = null;
- this.openToolCalls.clear();
+ this.toolCalls.clear();
this.rejectAllPending(new Error("Cursor ACP lane stopped"));
this.stopPromise ??= this.stopPhysicalOnce(input);
return this.stopPromise;
@@ -336,10 +336,12 @@ export class CursorAcpLane implements RuntimeLane {
};
const previousPromptRequestId = this.currentPromptRequestId;
const previousTerminalOwner = this.terminalOwner;
- const previousOpenToolCalls = new Set(this.openToolCalls);
+ const previousToolCalls = new Map(this.toolCalls);
if (delivery === "prompt") this.terminalOwner = prompt.receipt;
this.currentPromptRequestId = requestId;
- this.openToolCalls.clear();
+ if (delivery === "prompt") {
+ this.toolCalls.clear();
+ }
this.pending.set(requestId, { kind: "prompt", method: "session/prompt", prompt });
try {
this.write({
@@ -356,8 +358,8 @@ export class CursorAcpLane implements RuntimeLane {
if (this.currentPromptRequestId === requestId) {
this.currentPromptRequestId = previousPromptRequestId;
this.terminalOwner = previousTerminalOwner;
- this.openToolCalls.clear();
- for (const toolCallId of previousOpenToolCalls) this.openToolCalls.add(toolCallId);
+ this.toolCalls.clear();
+ for (const [toolCallId, name] of previousToolCalls) this.toolCalls.set(toolCallId, name);
}
throw error;
}
@@ -378,11 +380,12 @@ export class CursorAcpLane implements RuntimeLane {
const terminalOwner = this.terminalOwner ?? prompt.receipt;
this.currentPromptRequestId = null;
this.terminalOwner = null;
- this.openToolCalls.clear();
+ this.toolCalls.clear();
this.events.emit("runtime_event", {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
+ ...(result.stopReason === "cancelled" ? { outcome: "interrupted" as const } : {}),
} satisfies AdapterEvent);
}
@@ -391,7 +394,7 @@ export class CursorAcpLane implements RuntimeLane {
const terminalOwner = this.terminalOwner ?? prompt.receipt;
this.currentPromptRequestId = null;
this.terminalOwner = null;
- this.openToolCalls.clear();
+ this.toolCalls.clear();
this.events.emit("runtime_event", {
kind: "error",
code,
@@ -486,7 +489,7 @@ export class CursorAcpLane implements RuntimeLane {
this.ready = false;
this.currentPromptRequestId = null;
this.terminalOwner = null;
- this.openToolCalls.clear();
+ this.toolCalls.clear();
this.stopPromise ??= this.stopPhysicalOnce({ reason: "runtime_error", forceAfterMs: 0 });
void this.stopPromise.catch(() => {});
this.events.emit("error", normalized);
@@ -503,7 +506,7 @@ export class CursorAcpLane implements RuntimeLane {
this.ready = false;
this.currentPromptRequestId = null;
this.terminalOwner = null;
- this.openToolCalls.clear();
+ this.toolCalls.clear();
this.rejectAllPending(new Error("Cursor ACP process exited"));
if (this.suppressExit || !this.processActivated) return;
this.events.emit("exit", {
@@ -661,23 +664,32 @@ export class CursorAcpLane implements RuntimeLane {
this.diagnostic("warning", "Cursor ACP emitted a malformed tool_call update");
return;
}
- this.openToolCalls.add(update.toolCallId);
- this.events.emit("runtime_event", {
- kind: "tool_call",
- name: update.title,
- input: update.rawInput,
- } satisfies AdapterEvent);
+ if (!this.toolCalls.has(update.toolCallId)) {
+ this.toolCalls.set(update.toolCallId, update.title);
+ this.events.emit("runtime_event", {
+ kind: "tool_call", callId: update.toolCallId, name: update.title, input: update.rawInput,
+ } satisfies AdapterEvent);
+ }
+ if ((update.status === "completed" || update.status === "failed") && this.toolCalls.get(update.toolCallId) !== null) {
+ this.toolCalls.set(update.toolCallId, null);
+ this.events.emit("runtime_event", {
+ kind: "tool_output", callId: update.toolCallId, name: update.title,
+ } satisfies AdapterEvent);
+ }
return;
}
case "tool_call_update": {
if (
typeof update.toolCallId === "string"
&& (update.status === "completed" || update.status === "failed")
- && this.openToolCalls.delete(update.toolCallId)
) {
+ const name = this.toolCalls.get(update.toolCallId);
+ if (name === undefined || name === null) return;
+ this.toolCalls.set(update.toolCallId, null);
this.events.emit("runtime_event", {
kind: "tool_output",
- name: typeof update.title === "string" ? update.title : "Cursor tool",
+ callId: update.toolCallId,
+ name: typeof update.title === "string" ? update.title : name,
} satisfies AdapterEvent);
}
return;
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
index a483c043e..63179fc8e 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
@@ -322,7 +322,7 @@ describe("CursorDriver persistent ACP transport", () => {
},
},
})}\n`);
- expect(events).toContainEqual({ kind: "tool_output", name: "Current tool" });
+ expect(events).toContainEqual({ kind: "tool_output", callId: "current-tool", name: "Current tool" });
completePrompt(process, server.prompts[3]!, "cancelled");
await settle();
@@ -330,6 +330,7 @@ describe("CursorDriver persistent ACP transport", () => {
kind: "turn_end",
sessionId: "cursor-acp-session",
turnOwner: "cursor:acp:4",
+ outcome: "interrupted",
}]);
completePrompt(process, server.prompts[0]!);
@@ -416,7 +417,7 @@ describe("CursorDriver persistent ACP transport", () => {
},
},
})}\n`);
- expect(events).toContainEqual({ kind: "tool_output", name: "Root tool" });
+ expect(events).toContainEqual({ kind: "tool_output", callId: "root-tool", name: "Root tool" });
completePrompt(process, server.prompts[0]!);
await settle();
@@ -1340,8 +1341,8 @@ describe("CursorDriver persistent ACP transport", () => {
expect(events).toContainEqual({ kind: "assistant_message_delta", text: "hello" });
expect(events).toContainEqual({ kind: "assistant_reasoning_delta", text: "thinking" });
- expect(events).toContainEqual({ kind: "tool_call", name: "Read", input: { path: "README.md" } });
- expect(events).toContainEqual({ kind: "tool_output", name: "Read" });
+ expect(events).toContainEqual({ kind: "tool_call", callId: "tool-1", name: "Read", input: { path: "README.md" } });
+ expect(events).toContainEqual({ kind: "tool_output", callId: "tool-1", name: "Read" });
expect(events).toContainEqual({ kind: "internal_progress", source: "cursor.acp", itemType: "plan" });
expect(events).toContainEqual(expect.objectContaining({
kind: "runtime_diagnostic",
diff --git a/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts b/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts
index 3c825976f..be417a3fe 100644
--- a/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts
@@ -451,6 +451,7 @@ export class GrokAcpLane implements RuntimeLane {
kind: "turn_end",
sessionId: this.sessionId ?? undefined,
turnOwner: terminalOwner,
+ ...(result.stopReason === "cancelled" ? { outcome: "interrupted" as const } : {}),
} satisfies AdapterEvent);
void this.refreshBilling();
}
diff --git a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts
index 6284c0eea..d6c820943 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.test.ts
@@ -355,7 +355,7 @@ describe("OpenCode CLI v2 persisted message authority", () => {
expect(native.interruptQuery).toBe("?resume=false");
expect(native.ends).toHaveLength(0);
native.deliver(); native.finish("msg_interrupted", "interrupted");
- await vi.waitFor(() => expect(native.ends).toEqual([{ kind: "turn_end", sessionId: native.id, turnOwner: "msg_root" }]));
+ await vi.waitFor(() => expect(native.ends).toEqual([{ kind: "turn_end", sessionId: native.id, turnOwner: "msg_root", outcome: "interrupted" }]));
expect(await lane.interrupt({ reason: "user_interrupt" })).toBe(false);
expect(native.errors).toHaveLength(0);
});
diff --git a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts
index a477d376c..3a9ba3ca2 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/v2-service-lane.ts
@@ -298,6 +298,7 @@ export class OpenCodeV2ServiceLane extends OpenCodeServiceLane {
}
this.events.emit("runtime_event", {
kind: "turn_end", sessionId: this.sessionId!, turnOwner: root.receipt,
+ ...(idle.outcome === "interrupted" ? { outcome: "interrupted" as const } : {}),
} satisfies AdapterEvent);
} catch (error) {
if (!current() || this.stopping) return;
diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.ts
index 93f3a75ec..337c1a2ee 100644
--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts
+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts
@@ -529,7 +529,7 @@ describe("root-turn text assembly", () => {
await session.start({ id: "one", kind: "user", text: "start" });
lane.emit({ kind: "assistant_message_delta", text: "still " });
lane.emit({ kind: "assistant_reasoning_delta", text: "thinking " });
- lane.emit({ kind: "turn_end", turnOwner: "stale-owner", pendingContent });
+ lane.emit({ kind: "turn_end", turnOwner: "stale-owner", pendingContent, outcome: "interrupted" });
lane.emit({ kind: "assistant_message_delta", text: "working" });
lane.emit({ kind: "assistant_reasoning_delta", text: "now" });
lane.emit({ kind: "turn_end", turnOwner: "claude:test:1" });
@@ -540,6 +540,31 @@ describe("root-turn text assembly", () => {
expect(observed.filter((event) => event.type === "assistant_reasoning_completed"))
.toMatchObject([{ text: "thinking now" }]);
expect(observed.filter((event) => event.type === "turn_completed")).toHaveLength(1);
+ expect(observed.filter((event) => event.type === "turn_completed"))
+ .toMatchObject([{ result: { outcome: "success" } }]);
+ });
+
+ it("preserves an owned native interruption and drains the next queued command", async () => {
+ const lane = new ControlledRuntimeLane();
+ const { session } = makeSession("claude", { lane });
+ const observed: Array<AgentEvent<BuiltinBackendSpecs, BuiltinBackendId>> = [];
+ const collecting = (async () => { for await (const event of session.events) observed.push(event); })();
+ await session.start({ id: "one", kind: "user", text: "start" });
+ lane.emit({ kind: "tool_call", callId: "running", name: "Read", input: {} });
+ expect(await session.send({ id: "two", kind: "user", text: "next" })).toMatchObject({ status: "queued" });
+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:1", outcome: "interrupted" });
+ await vi.waitFor(() => expect(session.snapshot().activeTurn?.commandIds).toEqual(["two"]));
+ lane.emit({ kind: "assistant_message_delta", text: "new text" });
+ lane.emit({ kind: "assistant_reasoning_delta", text: "new reasoning" });
+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:1", outcome: "interrupted", pendingContent: "discard" });
+ expect(session.snapshot().activeTurn?.commandIds).toEqual(["two"]);
+ lane.emit({ kind: "turn_end", turnOwner: "claude:test:2" });
+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });
+ await collecting;
+ expect(observed.filter((event) => event.type === "turn_completed"))
+ .toMatchObject([{ commandIds: ["one"], result: { outcome: "interrupted" } }, { commandIds: ["two"], result: { outcome: "success" } }]);
+ expect(observed.filter((event) => event.type === "assistant_message_completed")).toMatchObject([{ text: "new text" }]);
+ expect(observed.filter((event) => event.type === "assistant_reasoning_completed")).toMatchObject([{ text: "new reasoning" }]);
});
it("drops an unfinished delta buffer when the runtime crashes before a boundary", async () => {
diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.ts
index bc2726b77..8de04ba34 100644
--- a/src/daemon/agent-driver/src/controller/logical-session.ts
+++ b/src/daemon/agent-driver/src/controller/logical-session.ts
@@ -908,6 +908,7 @@ implements AgentSession<Specs, Id> {
return;
case "turn_end":
if (!this.activeTurn?.terminalOwner || event.turnOwner !== this.activeTurn.terminalOwner) return;
+ if (event.outcome === "interrupted") this.interruptedTurnId = this.activeTurn.turnId;
if (event.pendingContent === "discard") {
this.activeTurn.pendingReasoning = emptySemanticAssembler();
this.activeTurn.pendingMessage = emptySemanticAssembler();
diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.ts
index d845a07a1..e4c3cb3f3 100644
--- a/src/daemon/agent-driver/src/internal/adapter.ts
+++ b/src/daemon/agent-driver/src/internal/adapter.ts
@@ -75,7 +75,7 @@ export type AdapterEvent =
| { kind: "runtime_recovery"; stage: "retrying" | "recovered"; source?: string }
| { kind: "runtime_metric"; name: "sse_reconnect"; increment: 1 }
| { kind: "turn_owner"; receipt: string; nativeTurnId?: string }
- | { kind: "turn_end"; sessionId?: string; turnOwner?: string; pendingContent?: "discard" }
+ | { kind: "turn_end"; sessionId?: string; turnOwner?: string; pendingContent?: "discard"; outcome?: "interrupted" }
| { kind: "error"; code?: string; message: string }
| { kind: "telemetry"; name: "token_usage"; source: string; usage: TokenUsageDelta; identity?: TokenUsageIdentity }
| { kind: "telemetry"; name: "token_usage_status"; source: string; status: "available" | "unavailable" }
diff --git a/src/daemon/agent-driver/src/internal/probe.windows.test.ts b/src/daemon/agent-driver/src/internal/probe.windows.test.ts
index 9ecd27f58..07fe0d44a 100644
--- a/src/daemon/agent-driver/src/internal/probe.windows.test.ts
+++ b/src/daemon/agent-driver/src/internal/probe.windows.test.ts
@@ -109,7 +109,7 @@ describe("native process snapshot ownership", () => {
function windowsDescendants(pid: number): WindowsProcessIdentity[] {
if (process.platform !== "win32") return [];
const script = `$found = @(Get-CimInstance Win32_Process | Where-Object { $_.CreationDate } | ForEach-Object { @{pid=[int]$_.ProcessId;parent=[int]$_.ParentProcessId;name=$_.Name;created=$_.CreationDate.ToUniversalTime().ToString("o")} }); ConvertTo-Json -InputObject $found -Compress`;
- const snapshot = JSON.parse(execFileSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: 10_000 })) as WindowsProcessIdentity[];
+ const snapshot = JSON.parse(execFileSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: 30_000 })) as WindowsProcessIdentity[];
return descendantsFromSnapshot(snapshot, pid);
}
@@ -122,7 +122,7 @@ async function stop(child: ChildProcess) {
const alive = owned.filter(process => isAlive(process.pid));
if (alive.length) {
const script = `$found = @(); foreach ($id in @(${alive.map(process => process.pid).join(",")})) { foreach ($process in @(Get-CimInstance Win32_Process -Filter ("ProcessId=" + $id))) { $found += @{pid=$id;name=$process.Name;created=$process.CreationDate.ToString("o")} } }; ConvertTo-Json -InputObject @($found) -Compress`;
- const current = JSON.parse(execFileSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: 10_000 }));
+ const current = JSON.parse(execFileSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: 30_000 }));
console.log(JSON.stringify({ stage: "owned-descendant-still-alive", binary: diagnostics.get(child)?.binary, captured: alive, current }));
}
expect(alive).toEqual([]);
diff --git a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
index 2f1b7cdef..add3c05e6 100644
--- a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
+++ b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts
@@ -577,6 +577,77 @@ function emitStaleTerminal(backend: BuiltinBackendId, harness: VendorHarness): v
harness.duplicateTurn(1);
}
+describe("native primitive regressions through registered public sessions", () => {
+ it.each(["codex", "cursor", "grok", "antigravity"] as const)("preserves provider-originated %s cancellation and permits the next turn", async (backend) => {
+ const fixture = await openRegisteredHarness(backend, "native-cancel");
+ try {
+ const first = fixture.session.start({ id: "first", kind: "user", text: "first" });
+ await settlePromptAdmission(backend, fixture.harness, 1, first);
+ const cancel = () => {
+ if (backend === "codex") {
+ fixture.harness.emitProvider({ jsonrpc: "2.0", method: "turn/completed", params: {
+ threadId: "codex-resumed", turn: { id: "codex-turn-1", status: "interrupted" },
+ } });
+ } else fixture.harness.duplicateTurn(1, { stopReason: "cancelled" });
+ };
+ cancel();
+ await vi.waitFor(() => expect(fixture.events.filter((event) => event.type === "turn_completed"))
+ .toMatchObject([{ commandIds: ["first"], result: { outcome: "interrupted" } }]));
+ const next = fixture.session.send({ id: "next", kind: "user", text: "next" });
+ await settlePromptAdmission(backend, fixture.harness, 2, next);
+ cancel();
+ expect(fixture.session.snapshot().activeTurn?.commandIds).toEqual(["next"]);
+ fixture.harness.completeTurn(2);
+ await vi.waitFor(() => expect(fixture.events.filter((event) => event.type === "turn_completed"))
+ .toMatchObject([{ result: { outcome: "interrupted" } }, { commandIds: ["next"], result: { outcome: "success" } }]));
+ } finally { await stopRegisteredHarness(backend, fixture); }
+ });
+
+ it.each([
+ { summary: ["first section", "second section"], content: ["raw text"], expected: "first section\n\nsecond section" },
+ { summary: [], content: ["raw first", "raw second"], expected: "raw first\n\nraw second" },
+ { summary: [], content: [], expected: "streamed reasoning" },
+ ])("preserves Codex native reasoning completion without duplicate text ($expected)", async ({ summary, content, expected }) => {
+ const fixture = await openRegisteredHarness("codex", "native-reasoning");
+ try {
+ await settlePromptAdmission("codex", fixture.harness, 1, fixture.session.start({ id: "first", kind: "user", text: "first" }));
+ fixture.harness.emitProvider({ jsonrpc: "2.0", method: "item/reasoning/summaryTextDelta", params: {
+ threadId: "codex-resumed", turnId: "codex-turn-1", itemId: "reason", delta: "streamed reasoning", summaryIndex: 0,
+ } });
+ fixture.harness.emitProvider({ jsonrpc: "2.0", method: "item/completed", params: {
+ threadId: "codex-resumed", turnId: "codex-turn-1", item: { id: "reason", type: "reasoning", summary, content },
+ } });
+ fixture.harness.completeTurn(1);
+ await vi.waitFor(() => expect(fixture.events.filter((event) => event.type === "assistant_reasoning_completed"))
+ .toMatchObject([{ text: expected, truncated: false }]));
+ expect(fixture.events.filter((event) => event.type === "assistant_reasoning_completed")).toHaveLength(1);
+ } finally { await stopRegisteredHarness("codex", fixture); }
+ });
+
+ it("keeps Cursor tool identity through repeated starts and a steer", async () => {
+ const fixture = await openRegisteredHarness("cursor", "native-tools");
+ const update = (value: unknown) => fixture.harness.emitProvider({ jsonrpc: "2.0", method: "session/update", params: {
+ sessionId: "cursor-resumed", update: value,
+ } });
+ try {
+ await fixture.session.start({ id: "root", kind: "user", text: "root" });
+ const start = { sessionUpdate: "tool_call", toolCallId: "call-1", title: "Read", rawInput: { path: "x" } };
+ update(start); update(start);
+ expect(fixture.session.snapshot().diagnostics.metrics.outstandingToolUses).toBe(1);
+ expect(await fixture.session.send({ id: "steer", kind: "user", text: "more" })).toMatchObject({ status: "accepted" });
+ const finish = { sessionUpdate: "tool_call_update", toolCallId: "call-1", status: "completed" };
+ update(finish); update(finish); update(start);
+ update({ sessionUpdate: "tool_call", toolCallId: "call-2", title: "Fast tool", status: "completed" });
+ update({ sessionUpdate: "tool_call_update", toolCallId: "call-2", status: "completed" });
+ expect(fixture.session.snapshot().diagnostics.metrics).toMatchObject({ outstandingToolUses: 0, toolLifecycleMismatchCount: 0 });
+ fixture.harness.completeTurn(2);
+ await vi.waitFor(() => expect(fixture.events.filter((event) => event.type === "turn_completed")).toHaveLength(1));
+ expect(fixture.events.filter((event) => event.type === "tool_started")).toMatchObject([{ callId: "call-1" }, { callId: "call-2" }]);
+ expect(fixture.events.filter((event) => event.type === "tool_finished")).toMatchObject([{ callId: "call-1", name: "Read" }, { callId: "call-2" }]);
+ } finally { await stopRegisteredHarness("cursor", fixture); }
+ });
+});
+
describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi", "antigravity"] as const)(
"%s shared persistent stress conformance",
(backend) => {
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index ca329e091..29641b3be 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -518,7 +518,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
};
}
| { kind: "tool_call"; payload: { name: string; target?: string } }
- | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }
+ | { kind: "text"; payload: { text: string; truncated: boolean; chars: number } }
| { kind: "turn_interrupt"; payload: { status: "accepted" } }
| { kind: "session_reset"; payload: { trigger: "idle_timeout" } }
| {
@@ -1048,7 +1048,6 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
recordProviderQuota(backendId, quota);
reportTelemetryForIdleAgent(agentId);
},
- // Bot audit log — Producer A (runtime thinking + non-Bash tool_call).
// Bash suppression + thinking truncation happen inside managerRuntime.
onBotAuditEvent: (agentId, event, context) => emitBotAuditEvent(agentId, event, context),
// Idle hibernation / stall-recovery stops the subprocess without a
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index 91452a09c..6f3aebd35 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -9,7 +9,7 @@ import * as path from "node:path";
import { setImmediate as drainEventTasks } from "node:timers/promises";
import {
AgentProcessManager,
- truncateThinking,
+ truncateAuditText,
canonicalToolName,
extractToolAudit,
isAlookShellInvocation,
@@ -2805,94 +2805,59 @@ describe("AgentProcessManager — onAgentActivity (derived activity reporting)",
});
});
-describe("truncateThinking", () => {
- it("returns text unchanged when under the byte budget", async () => {
- const { text, truncated, chars } = truncateThinking("short");
- expect(text).toBe("short");
- expect(truncated).toBe(false);
- expect(chars).toBe(5);
+describe("truncateAuditText", () => {
+ it("retains exactly 1024 ASCII bytes without a truncation flag", () => {
+ const input = "a".repeat(1024);
+ expect(truncateAuditText(input)).toEqual({ text: input, truncated: false, chars: 1024 });
});
- it("truncates > 4KB text and reports the original char count", async () => {
- const long = "a".repeat(5000);
- const { text, truncated, chars } = truncateThinking(long);
- expect(truncated).toBe(true);
- expect(chars).toBe(5000);
- expect(Buffer.byteLength(text, "utf8")).toBeLessThanOrEqual(4096);
- });
-
- it("never splits a multi-byte UTF-8 sequence", async () => {
- // Build a string whose 4096-byte boundary lands inside a 4-byte emoji.
- // Each 😀 is 4 bytes. 1023 emojis = 4092 bytes; add "a" to get to 4093;
- // then more emojis to push past 4096 mid-glyph.
- const emoji = "😀";
- const prefix = "a".repeat(4093) + emoji + emoji + emoji;
- const { text } = truncateThinking(prefix);
- // The returned string must be decodable — i.e. no replacement chars
- // introduced by a mid-codepoint cut. `Buffer.from(text, "utf8")` and
- // reading it back should round-trip.
- expect(text).toBe(Buffer.from(text, "utf8").toString("utf8"));
+ it.each([
+ { input: "a".repeat(1025), expected: "a".repeat(1024), chars: 1025 },
+ { input: "中".repeat(341) + "😀", expected: "中".repeat(341), chars: 342 },
+ { input: "a".repeat(1021) + "😀", expected: "a".repeat(1021), chars: 1022 },
+ { input: "😀".repeat(256) + "x", expected: "😀".repeat(256), chars: 257 },
+ ])("keeps a complete UTF-8 prefix and original code-point count ($chars)", ({ input, expected, chars }) => {
+ const result = truncateAuditText(input);
+ expect(result).toEqual({ text: expected, truncated: true, chars });
+ expect(Buffer.byteLength(result.text, "utf8")).toBeLessThanOrEqual(1024);
+ expect(result.text).not.toContain("\ufffd");
});
});
describe("AgentProcessManager — bot audit event emission", () => {
- it("contains audit observer failures for reasoning and tool-start events", async () => {
+ it("contains audit observer failures for completed text and tool-start events", async () => {
const logger = stubLogger();
const onBotAuditEvent = vi.fn(() => { throw new Error("observer failed"); });
const { mgr, session } = makeManager({ logger, onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
-
- await expect(session.fire("runtime_event", { kind: "thinking", text: "completed reasoning" }))
- .resolves.toBeUndefined();
- await expect(session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/x" } }))
- .resolves.toBeUndefined();
-
+ await expect(session.fire("runtime_event", { kind: "text", text: "completed text" })).resolves.toBeUndefined();
+ await expect(session.fire("runtime_event", { kind: "tool_call", name: "Read", input: { file_path: "/x" } })).resolves.toBeUndefined();
expect(logger.calls.debug.map(([message]) => message)).toEqual(expect.arrayContaining([
- "audit emit failed (thinking)",
- "audit emit failed (tool_call)",
+ "audit emit failed (text)", "audit emit failed (tool_call)",
]));
});
- it("emits completed reasoning with truncated+chars fields immediately", async () => {
+ it("emits completed text with source truncation metadata", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
-
- await session.fire("runtime_event", { kind: "thinking", text: "think about it" });
-
- expect(onBotAuditEvent).toHaveBeenCalledWith(
- "a1",
- expect.objectContaining({
- kind: "thinking",
- payload: expect.objectContaining({
- text: "think about it",
- truncated: false,
- chars: 14,
- }),
- }),
- expect.objectContaining({ sessionId: null, launchId: null })
- );
+ await session.pushAgentEvent({ type: "assistant_message_completed", turnId: "test-turn", text: "hello", truncated: true });
+ expect(onBotAuditEvent).toHaveBeenCalledWith("a1", {
+ kind: "text", payload: { text: "hello", truncated: true, chars: 5 },
+ }, expect.objectContaining({ sessionId: null, launchId: null }));
});
- it("emits one bounded audit row per completed reasoning item and drops empty items", async () => {
+ it("uploads only one bounded row per nonempty completed text and never uploads thinking", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
-
- await session.fire("runtime_event", { kind: "thinking", text: "" });
- await session.fire("runtime_event", { kind: "thinking", text: "let me count" });
- await session.fire("runtime_event", { kind: "thinking", text: "" });
-
- const thinkingCalls = onBotAuditEvent.mock.calls.filter(
- ([, ev]) => (ev as { kind?: string })?.kind === "thinking"
- );
- expect(thinkingCalls).toHaveLength(1);
- expect(thinkingCalls[0]![1]).toEqual(
- expect.objectContaining({
- kind: "thinking",
- payload: expect.objectContaining({ text: "let me count", chars: 12 }),
- })
- );
+ await session.fire("runtime_event", { kind: "text", text: "" });
+ await session.fire("runtime_event", { kind: "thinking", text: "local reasoning only" });
+ await session.fire("runtime_event", { kind: "text", text: "中".repeat(400) });
+ await session.fire("runtime_event", { kind: "text", text: "" });
+ expect(onBotAuditEvent.mock.calls.map(([, event]) => event)).toEqual([
+ { kind: "text", payload: { text: "中".repeat(341), truncated: true, chars: 400 } },
+ ]);
});
it("emits `tool_call` with canonical name + resolved target", async () => {
@@ -3029,13 +2994,13 @@ describe("AgentProcessManager — bot audit event emission", () => {
]);
});
- it("does NOT emit for non-audit event kinds (session_init, text, turn_end)", async () => {
+ it("does not upload thinking or lifecycle-only events", async () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
await session.fire("runtime_event", { kind: "session_init", sessionId: "s1" });
- await session.fire("runtime_event", { kind: "text", text: "hi human" });
+ await session.fire("runtime_event", { kind: "thinking", text: "local reasoning" });
await session.fire("runtime_event", { kind: "turn_end" });
expect(onBotAuditEvent).not.toHaveBeenCalled();
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index 9b94c4811..0400c9b29 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -1,3 +1,4 @@
+import { BOT_AUDIT_TEXT_MAX_BYTES } from "@alook/shared";
import { MEMORY_MAINTENANCE_PROMPT } from "./memoryMaintenancePrompt.js";
import {
reduceManager,
@@ -245,7 +246,7 @@ export interface ManagerRuntimeOpts {
agentId: string,
event:
| { kind: "tool_call"; payload: { name: string; target?: string } }
- | { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }
+ | { kind: "text"; payload: { text: string; truncated: boolean; chars: number } }
| { kind: "turn_interrupt"; payload: { status: "accepted" } }
| { kind: "session_reset"; payload: { trigger: "idle_timeout" } }
| {
@@ -292,7 +293,6 @@ export interface TimelineRecorder {
pendingIdleResetEvent?: { eventId: string; occurredAt: string },
): boolean;
}
-const THINKING_MAX_BYTES = 4096;
const AUDIT_ERROR_MESSAGE_MAX_LEN = 2000;
const MAX_TARGET_CODE_UNITS = 200;
export function canonicalToolName(rawName: string): string {
@@ -440,15 +440,15 @@ export function extractToolAudit(
}
return { name, target: truncateTargetToCodeUnits(target), suppressed: false };
}
-export function truncateThinking(
+export function truncateAuditText(
text: string
): { text: string; truncated: boolean; chars: number } {
const chars = [...text].length;
const buf = Buffer.from(text, "utf8");
- if (buf.byteLength <= THINKING_MAX_BYTES) {
+ if (buf.byteLength <= BOT_AUDIT_TEXT_MAX_BYTES) {
return { text, truncated: false, chars };
}
- let end = THINKING_MAX_BYTES;
+ let end = BOT_AUDIT_TEXT_MAX_BYTES;
while (end > 0 && (buf[end] & 0xc0) === 0x80) end--;
const truncatedText = buf.subarray(0, end).toString("utf8");
return { text: truncatedText, truncated: true, chars };
@@ -2022,18 +2022,18 @@ export class AgentProcessManager {
}
}
if (this.opts.onBotAuditEvent) {
- if (event.type === "assistant_reasoning_completed" && event.text.length > 0) {
- const { text, truncated, chars } = truncateThinking(event.text);
+ if (event.type === "assistant_message_completed" && event.text.length > 0) {
+ const { text, truncated, chars } = truncateAuditText(event.text);
try {
this.opts.onBotAuditEvent(agentId, {
- kind: "thinking",
+ kind: "text",
payload: { text, truncated: truncated || event.truncated, chars },
}, {
sessionId: this.liveSessions.get(agentId) ?? null,
launchId: this.launchIds.get(agentId) ?? null,
});
} catch (err) {
- this.log.debug("audit emit failed (thinking)", { agentId, err: String(err) });
+ this.log.debug("audit emit failed (text)", { agentId, err: String(err) });
}
}
if (event.type === "tool_started") {
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 15838f24a..172d83b7d 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -941,6 +941,8 @@ export interface HostAgentActivity {
* through `HostControlChannel.reportBotAuditEvent`; ws-do stamps `createdAt`
* and appends to `community_bot_activity_event`.
*/
+export const BOT_AUDIT_TEXT_MAX_BYTES = 1024;
+
export type BotAuditEventPayload =
| {
kind: "cli_invocation";
@@ -951,6 +953,7 @@ export type BotAuditEventPayload =
}
| { kind: "tool_call"; payload: { name: string; target?: string } }
| { kind: "thinking"; payload: { text: string; truncated: boolean; chars: number } }
+ | { kind: "text"; payload: { text: string; truncated: boolean; chars: number } }
| { kind: "turn_interrupt"; payload: { status: "accepted" } }
| {
kind: "wake_trigger";
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index edff711b0..2950b3932 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -434,7 +434,7 @@ const communityBotAuditEventSchema = z.strictObject({
type: z.literal("community:bot.audit_event"),
botId: string,
id: string,
- kind: z.enum(["cli_invocation", "tool_call", "thinking", "turn_interrupt", "wake_trigger", "session_reset", "nap", "model_changed", "provider_changed", "error"]),
+ kind: z.enum(["cli_invocation", "tool_call", "thinking", "text", "turn_interrupt", "wake_trigger", "session_reset", "nap", "model_changed", "provider_changed", "error"]),
payload: z.unknown(),
sessionId: nullableString.optional(),
launchId: nullableString.optional(),
diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.ts
index 9c0e09ae4..1b83d0f2e 100644
--- a/src/shared/src/db/queries/community/bot-audit-log.ts
+++ b/src/shared/src/db/queries/community/bot-audit-log.ts
@@ -31,7 +31,7 @@ export type BotActivityEventInput = {
botId: string;
sessionId?: string | null;
launchId?: string | null;
- kind: "cli_invocation" | "tool_call" | "thinking" | "turn_interrupt" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error";
+ kind: "cli_invocation" | "tool_call" | "thinking" | "text" | "turn_interrupt" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error";
payload: string;
createdAt?: string;
};
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index c5e47fc4c..99227d7c9 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -327,6 +327,7 @@ export {
AuditLogCliInvocationPayloadSchema,
AuditLogToolCallPayloadSchema,
AuditLogThinkingPayloadSchema,
+ AuditLogTextPayloadSchema,
AuditLogTurnInterruptPayloadSchema,
AuditLogWakeTriggerPayloadSchema,
AuditLogModelChangedPayloadSchema,
@@ -496,6 +497,7 @@ export type {
} from "./community-cli-contract";
export {
AGENT_EVENT_PROMPT_MAX_LENGTH,
+ BOT_AUDIT_TEXT_MAX_BYTES,
CONTROL_HEARTBEAT_CAPABILITY,
AgentInterruptRequestSchema,
DM_SERVER,
diff --git a/src/shared/src/schemas.test.ts b/src/shared/src/schemas.test.ts
index b514592aa..2e0882418 100644
--- a/src/shared/src/schemas.test.ts
+++ b/src/shared/src/schemas.test.ts
@@ -11,6 +11,7 @@ import {
UpdateWorkspaceRequestSchema,
BotAuditEventSchema,
BotAuditEventKindSchema,
+ HostBotAuditEventFrameSchema,
CommunityAgentNapRequestSchema,
CommunityMachineRuntimeSchema,
RuntimeReasoningCatalogSchema,
@@ -395,3 +396,25 @@ it("accepts the four supported provider quotas in a ready snapshot and bounds ex
expect(HostReadyMessageSchema.safeParse({ type: "ready", runtimeReport: [], providerQuotas }).success).toBe(true)
expect(HostReadyMessageSchema.safeParse({ type: "ready", runtimeReport: [], providerQuotas: [...providerQuotas, providerQuotas[0]] }).success).toBe(false)
})
+
+
+describe("completed text audit payload", () => {
+ const frame = (text: string) => ({
+ type: "bot_audit_event", agentId: "bot", event: {
+ kind: "text", payload: { text, truncated: false, chars: [...text].length },
+ },
+ });
+
+ it.each(["a".repeat(1024), "中".repeat(341) + "a", "😀".repeat(256)])("accepts a full 1024-byte Unicode prefix", (text) => {
+ expect(HostBotAuditEventFrameSchema.safeParse(frame(text)).success).toBe(true);
+ });
+
+ it.each(["a".repeat(1025), "中".repeat(342), "😀".repeat(256) + "a", ""])("rejects text outside the byte budget before server storage", (text) => {
+ expect(HostBotAuditEventFrameSchema.safeParse(frame(text)).success).toBe(false);
+ });
+
+ it("registers text while preserving legacy thinking rows", () => {
+ expect(BotAuditEventKindSchema.safeParse("text").success).toBe(true);
+ expect(BotAuditEventSchema.safeParse({ kind: "thinking", payload: { text: "legacy", truncated: false, chars: 6 } }).success).toBe(true);
+ });
+});
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index b312b7522..95f28f73a 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -2,7 +2,7 @@ import { z } from "zod";
import { IssueStatus, TASK_TYPES } from "./constants";
import { sanitizeSlug } from "./utils/slug";
import { DiagnosticReportIdSchema } from "./diagnostics-contract";
-import { AGENT_EVENT_PROMPT_MAX_LENGTH } from "./community-cli-contract";
+import { AGENT_EVENT_PROMPT_MAX_LENGTH, BOT_AUDIT_TEXT_MAX_BYTES } from "./community-cli-contract";
import {
DAILY_TOKEN_USAGE_WINDOW_DAYS,
DailyUsageSnapshotSchema,
@@ -1517,6 +1517,14 @@ export const AuditLogThinkingPayloadSchema = z.object({
truncated: z.boolean(),
chars: z.number().int().nonnegative(),
});
+export const AuditLogTextPayloadSchema = z.object({
+ text: z.string().min(1).max(BOT_AUDIT_TEXT_MAX_BYTES).refine(
+ (text) => new TextEncoder().encode(text).byteLength <= BOT_AUDIT_TEXT_MAX_BYTES,
+ { message: "Text exceeds 1024 UTF-8 bytes" },
+ ),
+ truncated: z.boolean(),
+ chars: z.number().int().nonnegative(),
+});
export const AuditLogTurnInterruptPayloadSchema = z.object({
status: z.literal("accepted"),
});
@@ -1609,6 +1617,7 @@ export const BotAuditEventSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("cli_invocation"), payload: AuditLogCliInvocationPayloadSchema }),
z.object({ kind: z.literal("tool_call"), payload: AuditLogToolCallPayloadSchema }),
z.object({ kind: z.literal("thinking"), payload: AuditLogThinkingPayloadSchema }),
+ z.object({ kind: z.literal("text"), payload: AuditLogTextPayloadSchema }),
z.object({ kind: z.literal("turn_interrupt"), payload: AuditLogTurnInterruptPayloadSchema }),
z.object({ kind: z.literal("wake_trigger"), payload: AuditLogWakeTriggerPayloadSchema }),
z.object({ kind: z.literal("session_reset"), payload: AuditLogSessionResetPayloadSchema }),
@@ -1623,6 +1632,7 @@ export const BotAuditEventKindSchema = z.enum([
"cli_invocation",
"tool_call",
"thinking",
+ "text",
"turn_interrupt",
"wake_trigger",
"session_reset",
diff --git a/src/web/src/components/community/bots/bot-activity-row.dom.test.ts b/src/web/src/components/community/bots/bot-activity-row.dom.test.ts
index 0b8d678df..0e96a9bf9 100644
--- a/src/web/src/components/community/bots/bot-activity-row.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-activity-row.dom.test.ts
@@ -17,6 +17,35 @@ function modelRowText(renderer: ReturnType<typeof renderDom>): string {
return rowText(renderer, "bot-activity-event-model_changed")
}
+describe("BotActivityRow — text and historical thinking", () => {
+ function textEvent(payload: unknown, kind: "text" | "thinking" = "text"): AuditEvent {
+ return { id: "text-1", kind, payload, sessionId: null, launchId: null, createdAt: "2026-10-14T00:00:00.000Z" }
+ }
+
+ it("renders the retained Unicode body literally without interpreting markup", () => {
+ const text = "正文🙂\n<script>private body</script>"
+ const renderer = render(textEvent({ text, truncated: false, chars: [...text].length }))
+ expect(renderer.getByTestId("bot-activity-event-text").textContent).toBe(text)
+ expect(renderer.container.querySelector("script")).toBeNull()
+ expect(renderer.container).not.toHaveTextContent("Truncated")
+ expect(renderer.container.querySelector('[aria-label="text"]')).not.toBeNull()
+ })
+
+ it("shows retention truncation even when the short retained prefix fits the row", () => {
+ const renderer = render(textEvent({ text: "short prefix", truncated: true, chars: 200 }))
+ expect(renderer.getByTestId("bot-activity-event-text")).toHaveTextContent("short prefix")
+ expect(renderer.getByTestId("bot-activity-event-text").querySelector("button")).toBeDisabled()
+ expect(renderer.container).toHaveTextContent("Truncated")
+ })
+
+ it("keeps historical thinking readable without relabeling it as text", () => {
+ const renderer = render(textEvent({ text: "retained thinking", truncated: false, chars: 17 }, "thinking"))
+ expect(renderer.container).toHaveTextContent("retained thinking")
+ expect(renderer.container.querySelector('[aria-label="think"]')).not.toBeNull()
+ expect(renderer.container.querySelector('[data-testid="bot-activity-event-text"]')).toBeNull()
+ })
+})
+
describe("BotActivityRow — model_changed", () => {
it("renders the raw stored ids from → to", () => {
const renderer = render({
diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsx
index 3ab358336..149cf4cb2 100644
--- a/src/web/src/components/community/bots/bot-activity-row.tsx
+++ b/src/web/src/components/community/bots/bot-activity-row.tsx
@@ -63,6 +63,7 @@ function KindTag({ kind }: { kind: AuditKind }) {
function kindMeta(kind: AuditKind): { label: string; tone: string } {
if (kind === "cli_invocation") return { label: "daemon", tone: "text-foreground/70" }
if (kind === "tool_call") return { label: "tool", tone: "text-muted-foreground" }
+ if (kind === "text") return { label: "text", tone: "text-foreground/70" }
if (kind === "turn_interrupt") return { label: "stop", tone: "text-foreground/70" }
if (kind === "wake_trigger") return { label: "wake", tone: "text-foreground/70" }
if (kind === "session_reset") return { label: "reset", tone: "text-foreground/70" }
@@ -218,6 +219,14 @@ function RowBody({ event }: { event: AuditEvent }) {
const fullText = omittedChars > 0
? `${text}\n… ${omittedChars} character${omittedChars === 1 ? "" : "s"} not retained in the audit log`
: text
+ if (event.kind === "text") {
+ return (
+ <div className="flex min-w-0 items-center gap-2" data-testid="bot-activity-event-text">
+ <TruncatedAuditLog fullText={fullText}>{text || "Text unavailable"}</TruncatedAuditLog>
+ {truncated && <span className="shrink-0 text-[11px] text-muted-foreground">Truncated</span>}
+ </div>
+ )
+ }
return (
<TruncatedAuditLog
fullText={fullText}
diff --git a/src/web/src/components/community/social/bot-audit-preview.dom.test.ts b/src/web/src/components/community/social/bot-audit-preview.dom.test.ts
index a29a857a7..da28db083 100644
--- a/src/web/src/components/community/social/bot-audit-preview.dom.test.ts
+++ b/src/web/src/components/community/social/bot-audit-preview.dom.test.ts
@@ -59,6 +59,17 @@ describe("BotAuditPreview", () => {
vi.useRealTimers()
})
+ it("shows a fixed text summary without the retained body or its private link", () => {
+ mocks.result.events = [{
+ ...event("e1"), kind: "text",
+ payload: { text: "private body https://private.example", truncated: true, chars: 500 },
+ }]
+ const renderer = render(React.createElement(BotAuditPreview, { botId: "bot-1", active: false, onOpen: () => {} }))
+ expect(renderer.container).toHaveTextContent("Completed text output")
+ expect(renderer.container).not.toHaveTextContent("private body")
+ expect(renderer.container.innerHTML).not.toContain("private.example")
+ })
+
it("uses exact system status pairs for active state", () => {
expect(isBotActivityActive("🌀", "Waking up")).toBe(true)
expect(isBotActivityActive("⚡", "Working on it")).toBe(true)
diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.ts
index 9d02fe49b..0139f87f7 100644
--- a/src/web/src/hooks/community/use-bot-audit-log.ts
+++ b/src/web/src/hooks/community/use-bot-audit-log.ts
@@ -14,7 +14,7 @@ import { communityKeys } from "@/lib/query-keys"
import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
import { ApiError } from "@/lib/errors"
-export type AuditKind = "cli_invocation" | "tool_call" | "thinking" | "turn_interrupt" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error"
+export type AuditKind = "cli_invocation" | "tool_call" | "text" | "thinking" | "turn_interrupt" | "wake_trigger" | "session_reset" | "nap" | "model_changed" | "provider_changed" | "error"
export type AuditEvent = {
id: string
diff --git a/src/web/src/lib/community/audit-event-summary.test.ts b/src/web/src/lib/community/audit-event-summary.test.ts
index add821518..1f79c2579 100644
--- a/src/web/src/lib/community/audit-event-summary.test.ts
+++ b/src/web/src/lib/community/audit-event-summary.test.ts
@@ -7,6 +7,7 @@ describe("summarizeAuditEvent", () => {
const kinds: AuditKind[] = [
"cli_invocation",
"tool_call",
+ "text",
"thinking",
"turn_interrupt",
"wake_trigger",
@@ -74,4 +75,10 @@ describe("summarizeAuditEvent", () => {
expect(summarizeAuditEvent(event)).toBe("Updated its reasoning")
expect(summarizeAuditEvent(event)).not.toMatch(/secret|private|credential|Users/)
})
+ it("keeps completed text and its truncation details out of the preview summary", () => {
+ expect(summarizeAuditEvent({
+ kind: "text",
+ payload: { text: "private body https://private.example", truncated: true, chars: 500 },
+ })).toBe("Completed text output")
+ })
})
diff --git a/src/web/src/lib/community/audit-event-summary.ts b/src/web/src/lib/community/audit-event-summary.ts
index 5f1fc9c57..059f87ff7 100644
--- a/src/web/src/lib/community/audit-event-summary.ts
+++ b/src/web/src/lib/community/audit-event-summary.ts
@@ -3,6 +3,7 @@ import type { AuditEvent, AuditKind } from "@/hooks/community/use-bot-audit-log"
const SUMMARY_BY_KIND: Record<AuditKind, string> = {
cli_invocation: "alook command",
tool_call: "tool",
+ text: "Completed text output",
thinking: "Updated its reasoning",
turn_interrupt: "Stop accepted by daemon",
wake_trigger: "Woke for a new message",
diff --git a/src/web/src/lib/community/audit-log-payload.test.ts b/src/web/src/lib/community/audit-log-payload.test.ts
index 2aaa9f420..e9ef62cd5 100644
--- a/src/web/src/lib/community/audit-log-payload.test.ts
+++ b/src/web/src/lib/community/audit-log-payload.test.ts
@@ -38,6 +38,18 @@ describe("parseAuditLogPayload", () => {
)
expect(p).toEqual({ text: "hmm", truncated: false, chars: 3 })
})
+ it("parses retained text with its original count and truncation state", () => {
+ const payload = { text: "正文🙂\nnext", truncated: true, chars: 600 }
+ expect(parseAuditLogPayload("text", JSON.stringify(payload))).toEqual(payload)
+ })
+ it("rejects overbyte or malformed text while allowing the exact Unicode byte boundary", () => {
+ const text = "中".repeat(340) + "🙂"
+ expect(new TextEncoder().encode(text)).toHaveLength(1024)
+ const payload = { text, truncated: true, chars: 400 }
+ expect(parseAuditLogPayload("text", JSON.stringify(payload))).toEqual(payload)
+ expect(parseAuditLogPayload("text", JSON.stringify({ ...payload, text: text + "x" }))).toBe(null)
+ expect(parseAuditLogPayload("text", JSON.stringify({ text, truncated: "yes", chars: 400 }))).toBe(null)
+ })
it("parses only daemon-accepted turn_interrupt payloads", () => {
expect(parseAuditLogPayload("turn_interrupt", JSON.stringify({ status: "accepted" }))).toEqual({
status: "accepted",
diff --git a/src/web/src/lib/community/audit-log-payload.ts b/src/web/src/lib/community/audit-log-payload.ts
index 8f4dad032..a5f3d0fb5 100644
--- a/src/web/src/lib/community/audit-log-payload.ts
+++ b/src/web/src/lib/community/audit-log-payload.ts
@@ -2,6 +2,7 @@ import {
AuditLogCliInvocationPayloadSchema,
AuditLogToolCallPayloadSchema,
AuditLogThinkingPayloadSchema,
+ AuditLogTextPayloadSchema,
AuditLogTurnInterruptPayloadSchema,
AuditLogWakeTriggerPayloadSchema,
AuditLogModelChangedPayloadSchema,
@@ -36,6 +37,10 @@ export function parseAuditLogPayload(
const r = AuditLogToolCallPayloadSchema.safeParse(json)
return r.success ? r.data : null
}
+ case "text": {
+ const r = AuditLogTextPayloadSchema.safeParse(json)
+ return r.success ? r.data : null
+ }
case "thinking": {
const r = AuditLogThinkingPayloadSchema.safeParse(json)
return r.success ? r.data : null
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
index a4990de3a..9940aa971 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -910,6 +910,27 @@ describe("WebSocketDurableObject", () => {
mockStubFetch.mockClear()
})
+ it("persists completed text and notifies only the bound bot owner", async () => {
+ const { durable, store, env } = createDO()
+ store.set("community-machine-identity", { userId: "u_1", machineId: "cm_1", credentialHash: "0".repeat(64) })
+ mockGetBotBindingWithOwner.mockResolvedValue({ machineId: "cm_1", ownerUserId: "owner_1", runtime: "agy", name: "Bot", discriminator: "0007" })
+ mockInsertBotActivityEventAndPrune.mockResolvedValue({ id: "bae_text", createdAt: "2026-10-14T05:00:00.000Z" })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "community-machine", machineId: "cm_1", userId: "u_1", authenticated: true })
+ const payload = { text: "😀".repeat(256), truncated: true, chars: 300 }
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "bot_audit_event", agentId: "bot_1", sessionId: "native", launchId: "launch",
+ event: { kind: "text", payload },
+ }))
+ expect(mockInsertBotActivityEventAndPrune).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ botId: "bot_1", sessionId: "native", launchId: "launch", kind: "text", payload: JSON.stringify(payload),
+ }), [])
+ expect(env.WS_DO.idFromName).toHaveBeenCalledExactlyOnceWith("user:owner_1")
+ const notified = mockStubFetch.mock.calls.map((call: any[]) => call[0] as Request).filter((request) => request.url.endsWith("/community-broadcast"))
+ expect(notified).toHaveLength(1)
+ expect(await notified[0]!.clone().json()).toMatchObject({ type: "community:bot.audit_event", botId: "bot_1", kind: "text", payload })
+ })
+
it("persists a daemon-accepted turn interrupt", async () => {
const { durable, store } = createDO()
store.set("community-machine-identity", {
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
index 35d3d827d..aeb790ac6 100644
--- a/src/ws-do/src/ws-durable/test-harness.ts
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -273,6 +273,8 @@ vi.mock("@alook/shared", async () => {
let ok = false
if (kind === "cli_invocation") ok = typeof payload.subcommand === "string"
else if (kind === "tool_call") ok = typeof payload.name === "string"
+ else if (kind === "text")
+ ok = typeof payload.text === "string" && payload.text.length > 0 && new TextEncoder().encode(payload.text).byteLength <= 1024 && typeof payload.truncated === "boolean" && typeof payload.chars === "number"
else if (kind === "thinking")
ok = typeof payload.text === "string" && typeof payload.truncated === "boolean" && typeof payload.chars === "number"
else if (kind === "turn_interrupt") ok = payload.status === "accepted"