Skip to content

Commit 1baa55c

Browse files
Structured subagent announce output + include run outcome (#835)
* docs: clarify subagent announce status * Make subagent announce structured and include run outcome * fix: stabilize sub-agent announce status (#835) (thanks @roshanasingh4) --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 2e0325e commit 1baa55c

6 files changed

Lines changed: 244 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
- Browser: add tests for snapshot labels/efficient query params and labeled image responses.
1515
- Doctor: avoid re-adding WhatsApp config when only legacy ack reactions are set. (#927, fixes #900) — thanks @grp06.
1616
- Agents: scrub tuple `items` schemas for Gemini tool calls. (#926, fixes #746) — thanks @grp06.
17+
- Agents: stabilize sub-agent announce status from runtime outcomes and normalize Result/Notes. (#835) — thanks @roshanasingh4.
1718
- Embedded runner: suppress raw API error payloads from replies. (#924) — thanks @grp06.
1819
- Auth: normalize Claude Code CLI profile mode to oauth and auto-migrate config. (#855) — thanks @sebslight.
1920
- Daemon: clear persisted launchd disabled state before bootstrap (fixes `daemon install` after uninstall). (#849) — thanks @ndraiman.

‎docs/concepts/session-tool.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ Behavior:
145145
- Always non-blocking: returns `{ status: "accepted", runId, childSessionKey }` immediately.
146146
- After completion, Clawdbot runs a sub-agent **announce step** and posts the result to the requester chat channel.
147147
- Reply exactly `ANNOUNCE_SKIP` during the announce step to stay silent.
148+
- Announce replies are normalized to `Status`/`Result`/`Notes`; `Status` comes from runtime outcome (not model text).
148149
- Sub-agent sessions are auto-archived after `agents.defaults.subagents.archiveAfterMinutes` (default: 60).
149150
- Announce replies include a stats line (runtime, tokens, sessionKey/sessionId, transcript path, and optional cost).
150151

‎docs/tools/subagents.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,13 @@ Sub-agents report back via an announce step:
4949
- The announce step runs inside the sub-agent session (not the requester session).
5050
- If the sub-agent replies exactly `ANNOUNCE_SKIP`, nothing is posted.
5151
- Otherwise the announce reply is posted to the requester chat channel via the gateway `send` method.
52+
- Announce messages are normalized to a stable template:
53+
- `Status:` derived from the run outcome (`success`, `error`, `timeout`, or `unknown`).
54+
- `Result:` the summary content from the announce step (or `(not available)` if missing).
55+
- `Notes:` error details and other useful context.
56+
- `Status` is not inferred from model output; it comes from runtime outcome signals.
5257

53-
Announce payloads include a stats line at the end:
58+
Announce payloads include a stats line at the end (even when wrapped):
5459
- Runtime (e.g., `runtime 5m12s`)
5560
- Token usage (input/output/total)
5661
- Estimated cost when model pricing is configured (`models.providers.*.models[].cost`)
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+
const sendSpy = vi.fn(async () => ({}));
4+
5+
vi.mock("../gateway/call.js", () => ({
6+
callGateway: vi.fn(async (req: unknown) => {
7+
const typed = req as { method?: string; params?: { message?: string } };
8+
if (typed.method === "send") {
9+
return await sendSpy(typed);
10+
}
11+
if (typed.method === "agent.wait") {
12+
return { status: "error", startedAt: 10, endedAt: 20, error: "boom" };
13+
}
14+
if (typed.method === "sessions.patch") return {};
15+
if (typed.method === "sessions.delete") return {};
16+
return {};
17+
}),
18+
}));
19+
20+
vi.mock("./tools/agent-step.js", () => ({
21+
runAgentStep: vi.fn(async () => "did some stuff"),
22+
readLatestAssistantReply: vi.fn(async () => "raw subagent reply"),
23+
}));
24+
25+
vi.mock("./tools/sessions-announce-target.js", () => ({
26+
resolveAnnounceTarget: vi.fn(async () => ({
27+
provider: "telegram",
28+
to: "+15550001111",
29+
accountId: "default",
30+
})),
31+
}));
32+
33+
vi.mock("./tools/sessions-send-helpers.js", () => ({
34+
isAnnounceSkip: () => false,
35+
}));
36+
37+
vi.mock("../config/sessions.js", () => ({
38+
loadSessionStore: vi.fn(async () => ({ entries: {} })),
39+
resolveAgentIdFromSessionKey: () => "main",
40+
resolveStorePath: () => "/tmp/sessions.json",
41+
}));
42+
43+
vi.mock("../config/config.js", () => ({
44+
loadConfig: () => ({
45+
session: { mainKey: "agent:main:main" },
46+
}),
47+
}));
48+
49+
describe("subagent announce formatting", () => {
50+
beforeEach(() => {
51+
sendSpy.mockClear();
52+
});
53+
54+
it("wraps unstructured announce into Status/Result/Notes", async () => {
55+
const { runSubagentAnnounceFlow } = await import("./subagent-announce.js");
56+
await runSubagentAnnounceFlow({
57+
childSessionKey: "agent:main:subagent:test",
58+
childRunId: "run-123",
59+
requesterSessionKey: "agent:main:main",
60+
requesterDisplayKey: "main",
61+
task: "do thing",
62+
timeoutMs: 1000,
63+
cleanup: "keep",
64+
waitForCompletion: true,
65+
startedAt: 10,
66+
endedAt: 20,
67+
});
68+
69+
expect(sendSpy).toHaveBeenCalled();
70+
const msg = sendSpy.mock.calls[0]?.[0]?.params?.message as string;
71+
expect(msg).toContain("Status:");
72+
expect(msg).toContain("Status: error");
73+
expect(msg).toContain("Result:");
74+
expect(msg).toContain("Notes:");
75+
expect(msg).toContain("boom");
76+
});
77+
78+
it("keeps runtime status even when announce reply is structured", async () => {
79+
const agentStep = await import("./tools/agent-step.js");
80+
vi.mocked(agentStep.runAgentStep).mockResolvedValueOnce(
81+
"- **Status:** success\n\n- **Result:** did some stuff\n\n- **Notes:** all good",
82+
);
83+
84+
const { runSubagentAnnounceFlow } = await import("./subagent-announce.js");
85+
await runSubagentAnnounceFlow({
86+
childSessionKey: "agent:main:subagent:test",
87+
childRunId: "run-456",
88+
requesterSessionKey: "agent:main:main",
89+
requesterDisplayKey: "main",
90+
task: "do thing",
91+
timeoutMs: 1000,
92+
cleanup: "keep",
93+
waitForCompletion: true,
94+
startedAt: 10,
95+
endedAt: 20,
96+
});
97+
98+
const msg = sendSpy.mock.calls[0]?.[0]?.params?.message as string;
99+
expect(msg).toContain("Status: error");
100+
expect(msg).toContain("Result:");
101+
expect(msg).toContain("Notes:");
102+
});
103+
});

‎src/agents/subagent-announce.ts‎

Lines changed: 116 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,85 @@ export function buildSubagentSystemPrompt(params: {
183183
return lines.join("\n");
184184
}
185185

186+
export type SubagentRunOutcome = {
187+
status: "ok" | "error" | "timeout" | "unknown";
188+
error?: string;
189+
};
190+
191+
const ANNOUNCE_SECTION_RE = /^\s*[-*]?\s*(?:\*\*)?(status|result|notes)(?:\*\*)?\s*:\s*(.*)$/i;
192+
193+
function parseAnnounceSections(announce: string) {
194+
const sections = {
195+
status: [] as string[],
196+
result: [] as string[],
197+
notes: [] as string[],
198+
};
199+
let current: keyof typeof sections | null = null;
200+
let sawSection = false;
201+
202+
for (const line of announce.split(/\r?\n/)) {
203+
const match = line.match(ANNOUNCE_SECTION_RE);
204+
if (match) {
205+
const key = match[1]?.toLowerCase() as keyof typeof sections;
206+
current = key;
207+
sawSection = true;
208+
const rest = match[2]?.trim();
209+
if (rest) sections[key].push(rest);
210+
continue;
211+
}
212+
if (current) sections[current].push(line);
213+
}
214+
215+
const normalize = (lines: string[]) => {
216+
const joined = lines.join("\n").trim();
217+
return joined.length > 0 ? joined : undefined;
218+
};
219+
220+
return {
221+
sawSection,
222+
status: normalize(sections.status),
223+
result: normalize(sections.result),
224+
notes: normalize(sections.notes),
225+
};
226+
}
227+
228+
function normalizeAnnounceBody(params: {
229+
outcome: SubagentRunOutcome;
230+
announceReply: string;
231+
statsLine?: string;
232+
}) {
233+
const announce = params.announceReply.trim();
234+
const statsLine = params.statsLine?.trim();
235+
236+
const statusLabel =
237+
params.outcome.status === "ok"
238+
? "success"
239+
: params.outcome.status === "timeout"
240+
? "timeout"
241+
: params.outcome.status === "unknown"
242+
? "unknown"
243+
: "error";
244+
245+
const parsed = parseAnnounceSections(announce);
246+
const resultText = parsed.result ?? (announce || "(not available)");
247+
const notesParts: string[] = [];
248+
if (parsed.notes) notesParts.push(parsed.notes);
249+
if (params.outcome.error) notesParts.push(`- Error: ${params.outcome.error}`);
250+
const notesBlock = notesParts.length ? notesParts.join("\n") : "- (none)";
251+
252+
const message = [
253+
`Status: ${statusLabel}`,
254+
"",
255+
"Result:",
256+
resultText,
257+
"",
258+
"Notes:",
259+
notesBlock,
260+
].join("\n");
261+
262+
return statsLine ? `${message}\n\n${statsLine}` : message;
263+
}
264+
186265
function buildSubagentAnnouncePrompt(params: {
187266
requesterSessionKey?: string;
188267
requesterChannel?: string;
@@ -202,6 +281,10 @@ function buildSubagentAnnouncePrompt(params: {
202281
"",
203282
"**You MUST announce your result.** The requester is waiting for your response.",
204283
"Provide a brief, useful summary of what you accomplished.",
284+
"Reply with Result and Notes only (no Status line; status is added by the system).",
285+
"Format:",
286+
"Result: <summary>",
287+
"Notes: <extra context>",
205288
'Only reply "ANNOUNCE_SKIP" if the task completely failed with no useful output.',
206289
"Your reply will be posted to the requester chat.",
207290
].filter(Boolean);
@@ -222,10 +305,12 @@ export async function runSubagentAnnounceFlow(params: {
222305
startedAt?: number;
223306
endedAt?: number;
224307
label?: string;
308+
outcome?: SubagentRunOutcome;
225309
}): Promise<boolean> {
226310
let didAnnounce = false;
227311
try {
228312
let reply = params.roundOneReply;
313+
let outcome: SubagentRunOutcome | undefined = params.outcome;
229314
if (!reply && params.waitForCompletion !== false) {
230315
const waitMs = Math.min(params.timeoutMs, 60_000);
231316
const wait = (await callGateway({
@@ -235,8 +320,30 @@ export async function runSubagentAnnounceFlow(params: {
235320
timeoutMs: waitMs,
236321
},
237322
timeoutMs: waitMs + 2000,
238-
})) as { status?: string };
239-
if (wait?.status !== "ok") return false;
323+
})) as {
324+
status?: string;
325+
error?: string;
326+
startedAt?: number;
327+
endedAt?: number;
328+
};
329+
if (wait?.status === "timeout") {
330+
outcome = { status: "timeout" };
331+
} else if (wait?.status === "error") {
332+
outcome = { status: "error", error: wait.error };
333+
} else if (wait?.status === "ok") {
334+
outcome = { status: "ok" };
335+
}
336+
if (typeof wait?.startedAt === "number" && !params.startedAt) {
337+
params.startedAt = wait.startedAt;
338+
}
339+
if (typeof wait?.endedAt === "number" && !params.endedAt) {
340+
params.endedAt = wait.endedAt;
341+
}
342+
if (wait?.status === "timeout") {
343+
// No lifecycle end seen before timeout. Still attempt an announce so
344+
// requesters are not left hanging.
345+
if (!outcome) outcome = { status: "timeout" };
346+
}
240347
reply = await readLatestAssistantReply({
241348
sessionKey: params.childSessionKey,
242349
});
@@ -248,6 +355,8 @@ export async function runSubagentAnnounceFlow(params: {
248355
});
249356
}
250357

358+
if (!outcome) outcome = { status: "unknown" };
359+
251360
const announceTarget = await resolveAnnounceTarget({
252361
sessionKey: params.requesterSessionKey,
253362
displayKey: params.requesterDisplayKey,
@@ -278,7 +387,11 @@ export async function runSubagentAnnounceFlow(params: {
278387
startedAt: params.startedAt,
279388
endedAt: params.endedAt,
280389
});
281-
const message = statsLine ? `${announceReply.trim()}\n\n${statsLine}` : announceReply.trim();
390+
const message = normalizeAnnounceBody({
391+
outcome,
392+
announceReply,
393+
statsLine,
394+
});
282395

283396
await callGateway({
284397
method: "send",

‎src/agents/subagent-registry.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { loadConfig } from "../config/config.js";
22
import { callGateway } from "../gateway/call.js";
33
import { onAgentEvent } from "../infra/agent-events.js";
4-
import { runSubagentAnnounceFlow } from "./subagent-announce.js";
4+
import { runSubagentAnnounceFlow, type SubagentRunOutcome } from "./subagent-announce.js";
55
import {
66
loadSubagentRegistryFromDisk,
77
saveSubagentRegistryToDisk,
@@ -20,6 +20,7 @@ export type SubagentRunRecord = {
2020
createdAt: number;
2121
startedAt?: number;
2222
endedAt?: number;
23+
outcome?: SubagentRunOutcome;
2324
archiveAtMs?: number;
2425
announceCompletedAt?: number;
2526
announceHandled: boolean;
@@ -62,6 +63,7 @@ function resumeSubagentRun(runId: string) {
6263
startedAt: entry.startedAt,
6364
endedAt: entry.endedAt,
6465
label: entry.label,
66+
outcome: entry.outcome,
6567
});
6668
void announce.then((didAnnounce) => {
6769
finalizeSubagentAnnounce(runId, entry.cleanup, didAnnounce);
@@ -176,6 +178,12 @@ function ensureListener() {
176178
const endedAt =
177179
typeof evt.data?.endedAt === "number" ? (evt.data.endedAt as number) : Date.now();
178180
entry.endedAt = endedAt;
181+
if (phase === "error") {
182+
const error = typeof evt.data?.error === "string" ? (evt.data.error as string) : undefined;
183+
entry.outcome = { status: "error", error };
184+
} else {
185+
entry.outcome = { status: "ok" };
186+
}
179187
persistSubagentRuns();
180188

181189
if (!beginSubagentAnnounce(evt.runId)) {
@@ -194,6 +202,7 @@ function ensureListener() {
194202
startedAt: entry.startedAt,
195203
endedAt: entry.endedAt,
196204
label: entry.label,
205+
outcome: entry.outcome,
197206
});
198207
void announce.then((didAnnounce) => {
199208
finalizeSubagentAnnounce(evt.runId, entry.cleanup, didAnnounce);
@@ -272,7 +281,7 @@ async function waitForSubagentCompletion(runId: string, waitTimeoutMs: number) {
272281
timeoutMs,
273282
},
274283
timeoutMs: timeoutMs + 10_000,
275-
})) as { status?: string; startedAt?: number; endedAt?: number };
284+
})) as { status?: string; startedAt?: number; endedAt?: number; error?: string };
276285
if (wait?.status !== "ok" && wait?.status !== "error") return;
277286
const entry = subagentRuns.get(runId);
278287
if (!entry) return;
@@ -289,6 +298,11 @@ async function waitForSubagentCompletion(runId: string, waitTimeoutMs: number) {
289298
entry.endedAt = Date.now();
290299
mutated = true;
291300
}
301+
entry.outcome =
302+
wait.status === "error"
303+
? { status: "error", error: wait.error }
304+
: { status: "ok" };
305+
mutated = true;
292306
if (mutated) persistSubagentRuns();
293307
if (!beginSubagentAnnounce(runId)) return;
294308
const announce = runSubagentAnnounceFlow({
@@ -304,6 +318,7 @@ async function waitForSubagentCompletion(runId: string, waitTimeoutMs: number) {
304318
startedAt: entry.startedAt,
305319
endedAt: entry.endedAt,
306320
label: entry.label,
321+
outcome: entry.outcome,
307322
});
308323
void announce.then((didAnnounce) => {
309324
finalizeSubagentAnnounce(runId, entry.cleanup, didAnnounce);

0 commit comments

Comments
 (0)