Skip to content

Commit 8b1ab15

Browse files
committed
fix(claude-agent-sdk): keep backgrounded subagent spans open until task_notification
A foreground subagent moved to the background arrives as system/task_updated with patch.is_backgrounded (sdk.d.ts:6059; task_id only), or follows an app call to Query.backgroundTasks() (sdk.d.ts:3234). Both were ignored: the subagent span ended at the "running in the background" tool_result and the subagent's later turns were parented to an ended span. - task_started records task_id -> tool_use_id; task_updated with patch.is_backgrounded marks that subagent background. - The Query proxy intercepts backgroundTasks(toolUseId?): matching open foreground subagents are marked before the call is forwarded, and unmarked if it rejects or resolves false. The caller gets the original promise. - A task_notification with status failed/stopped now makes the subagent span ERROR in the foreground case too (it ended OK before when the tool_result itself was not an error). README documents background subagents. approved: Nikhil 2026-10-03 blanket Refs: TH-8235
1 parent 378acc5 commit 8b1ab15

6 files changed

Lines changed: 228 additions & 6 deletions

File tree

‎typescript/packages/traceai_claude_agent_sdk/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ await shutdown(); // flush before a short script exits
6767

6868
One API response that the SDK splits over several assistant messages (same `message.id`) is one turn.
6969

70+
### Background subagents
71+
72+
A foreground subagent span ends with its `tool.Agent` / `tool.Task` result. A subagent that runs in the background stays open after that tool result (which is only the "running in the background" placeholder) until its `system/task_notification`, so its later turns and tools still nest under a live span. A subagent counts as background when the tool input has `run_in_background: true`, `task_started.is_backgrounded` is true, a later `task_updated` carries `patch.is_backgrounded: true`, or the app calls `Query.backgroundTasks()` (all foreground subagents, or the one whose `tool_use_id` it was given; undone if the call rejects or returns `false`). The subagent span is ERROR when the notification status is `failed` or `stopped` (`claude_agent.subagent.status` has the value). A background subagent with no notification by the time the query ends is closed as ERROR "Subagent span not completed". The subagent span can therefore end after its parent tool span.
73+
7074
| Field | Attributes | Source |
7175
|---|---|---|
7276
| Model | `gen_ai.request.model`, `claude_agent.model` | `options.model`, the init message, each assistant message |

‎typescript/packages/traceai_claude_agent_sdk/src/__tests__/fixtures/messages.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
SDKSystemMessage,
1414
SDKTaskNotificationMessage,
1515
SDKTaskStartedMessage,
16+
SDKTaskUpdatedMessage,
1617
SDKUserMessage,
1718
} from "@anthropic-ai/claude-agent-sdk";
1819

@@ -217,6 +218,11 @@ export function taskNotification(
217218
// Journeys
218219
// ----------------------------------------------------------------------------
219220

221+
/** `system/task_updated` (sdk.d.ts SDKTaskUpdatedMessage): carries task_id only, no tool_use_id. */
222+
export function taskUpdated(taskId: string, patch: SDKTaskUpdatedMessage["patch"]): SDKTaskUpdatedMessage {
223+
return { type: "system", subtype: "task_updated", task_id: taskId, patch, uuid: uuid(), session_id: SESSION_ID };
224+
}
225+
220226
export const TOOL_INPUT_MARKER = "SECRET_TOOL_INPUT_MARKER.md";
221227
export const TOOL_OUTPUT_MARKER = "SECRET_TOOL_OUTPUT_MARKER";
222228
export const ASSISTANT_TEXT_MARKER = "SECRET_ASSISTANT_TEXT_MARKER";
@@ -259,6 +265,41 @@ export function subagentJourney(): SDKMessage[] {
259265
];
260266
}
261267

268+
export const BACKGROUND_PLACEHOLDER = "Agent is running in the background. You will be notified when it completes.";
269+
270+
/**
271+
* J2b: a foreground subagent moved to the background mid-run, either by
272+
* `system/task_updated` patch.is_backgrounded (sdk.d.ts:6059) or by the app
273+
* calling `Query.backgroundTasks()` (sdk.d.ts:3234). The Agent tool_result is
274+
* the "running in the background" placeholder; the subagent keeps working and
275+
* settles with `task_notification`.
276+
*/
277+
export function backgroundedSubagentJourney(
278+
options: { taskUpdated?: boolean; status?: SDKTaskNotificationMessage["status"] } = {},
279+
): SDKMessage[] {
280+
const { taskUpdated: withTaskUpdated = true, status = "completed" } = options;
281+
return [
282+
init(),
283+
assistant("msg_10", [
284+
toolUse(AGENT_TOOL_ID, "Agent", {
285+
description: "Review the diff",
286+
prompt: "Look for TODOs. SECRET_SUBAGENT_PROMPT_MARKER",
287+
subagent_type: "code-reviewer",
288+
run_in_background: false,
289+
}),
290+
]),
291+
taskStarted(AGENT_TOOL_ID, { is_backgrounded: false }),
292+
assistant("msg_11", [toolUse(SUBAGENT_GREP_ID, "Grep", { pattern: "TODO" })], AGENT_TOOL_ID),
293+
...(withTaskUpdated ? [taskUpdated("task-1", { is_backgrounded: true })] : []),
294+
toolResult(AGENT_TOOL_ID, BACKGROUND_PLACEHOLDER),
295+
assistant("msg_13", [text("The reviewer is running in the background.")]),
296+
toolResult(SUBAGENT_GREP_ID, "src/a.ts:3: TODO", AGENT_TOOL_ID),
297+
assistant("msg_12", [text("Found one TODO.")], AGENT_TOOL_ID),
298+
taskNotification(AGENT_TOOL_ID, status),
299+
resultSuccess("The reviewer is running in the background.", { num_turns: 2 }),
300+
];
301+
}
302+
262303
export const MCP_TOOL_ID = "toolu_mcp_1";
263304

264305
/** J3: an MCP tool that errors, then the run stops on max turns. */

‎typescript/packages/traceai_claude_agent_sdk/src/__tests__/wrapper.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,12 @@ import {
2525
TOOL_INPUT_MARKER,
2626
TOOL_OUTPUT_MARKER,
2727
TOTAL_COST_USD,
28+
backgroundedSubagentJourney,
2829
mcpErrorJourney,
2930
simpleToolJourney,
3031
streamingInputJourney,
3132
subagentJourney,
33+
taskNotification,
3234
} from "./fixtures/messages";
3335
import { StackContextManager, allAttributeText, byName, drain, memoryProvider, one, parentId } from "./helpers";
3436

@@ -341,6 +343,86 @@ describe("wrapQuery", () => {
341343
}
342344
expect(subagent.status.code).toBe(SpanStatusCode.OK);
343345
});
346+
347+
const endMsOf = (s: ReadableSpan) => s.endTime[0] * 1e3 + s.endTime[1] / 1e6;
348+
349+
/** Every subagent turn and tool sits under the subagent span and ends before it. */
350+
function expectSubagentOutlivesItsWork(spans: ReadableSpan[]) {
351+
const agentTool = one(spans, "tool.Agent");
352+
const subagent = one(spans, "claude_agent.subagent.code-reviewer");
353+
const grep = one(spans, "tool.Grep");
354+
const subTurns = byName(spans, "claude_agent.assistant_turn").filter(
355+
(t) => t.attributes["claude_agent.parent_tool_use_id"] === AGENT_TOOL_ID,
356+
);
357+
expect(subTurns).toHaveLength(2);
358+
expect(endMsOf(subagent)).toBeGreaterThan(endMsOf(agentTool));
359+
for (const turn of subTurns) {
360+
expect(parentId(turn)).toBe(subagent.spanContext().spanId);
361+
expect(endMsOf(turn)).toBeLessThanOrEqual(endMsOf(subagent));
362+
}
363+
expect(endMsOf(grep)).toBeLessThanOrEqual(endMsOf(subagent));
364+
return subagent;
365+
}
366+
367+
it("R6: keeps a subagent moved to the background (task_updated patch.is_backgrounded) open until task_notification", async () => {
368+
const { provider, exporter } = memoryProvider();
369+
const fake = makeFakeQuery(backgroundedSubagentJourney(), { delayMs: 2 });
370+
await drain(wrapQuery(fake.query, { tracerProvider: provider })({ prompt: PROMPT }));
371+
const subagent = expectSubagentOutlivesItsWork(exporter.getFinishedSpans());
372+
expect(subagent.status.code).toBe(SpanStatusCode.OK);
373+
expect(subagent.attributes["claude_agent.subagent.status"]).toBe("completed");
374+
});
375+
376+
it("R6: keeps subagents open after the app calls Query.backgroundTasks()", async () => {
377+
const { provider, exporter } = memoryProvider();
378+
const fake = makeFakeQuery(backgroundedSubagentJourney({ taskUpdated: false }), { delayMs: 2 });
379+
const q = wrapQuery(fake.query, { tracerProvider: provider })({ prompt: PROMPT });
380+
for (let i = 0; i < 4; i += 1) await q.next(); // init, Agent tool_use, task_started, subagent Grep turn
381+
await expect(q.backgroundTasks()).resolves.toBe(true);
382+
expect(fake.control.backgroundTasksCalls).toEqual([undefined]);
383+
await drain(q);
384+
const subagent = expectSubagentOutlivesItsWork(exporter.getFinishedSpans());
385+
expect(subagent.status.code).toBe(SpanStatusCode.OK);
386+
});
387+
388+
it("R6: treats a subagent as foreground again when backgroundTasks() rejects", async () => {
389+
const { provider, exporter } = memoryProvider();
390+
const disabled = new Error("background tasks are disabled");
391+
const fake = makeFakeQuery(subagentJourney(), { backgroundTasksResult: disabled });
392+
const q = wrapQuery(fake.query, { tracerProvider: provider })({ prompt: PROMPT });
393+
for (let i = 0; i < 3; i += 1) await q.next();
394+
await expect(q.backgroundTasks(AGENT_TOOL_ID)).rejects.toBe(disabled);
395+
await drain(q);
396+
const spans = exporter.getFinishedSpans();
397+
expect(endMsOf(one(spans, "claude_agent.subagent.code-reviewer"))).toBeLessThanOrEqual(
398+
endMsOf(one(spans, "tool.Agent")),
399+
);
400+
expect(one(spans, "claude_agent.subagent.code-reviewer").status.code).toBe(SpanStatusCode.OK);
401+
});
402+
403+
it.each(["failed", "stopped"] as const)(
404+
"marks a foreground subagent ERROR when task_notification reports %s",
405+
async (status) => {
406+
const journey = subagentJourney().map((m) =>
407+
m.type === "system" && m.subtype === "task_notification" ? taskNotification(AGENT_TOOL_ID, status) : m,
408+
);
409+
const { spans } = await run(journey);
410+
const subagent = one(spans, "claude_agent.subagent.code-reviewer");
411+
expect(subagent.attributes["claude_agent.subagent.status"]).toBe(status);
412+
expect(subagent.status.code).toBe(SpanStatusCode.ERROR);
413+
expect(subagent.status.message).toBe(`subagent ${status}`);
414+
},
415+
);
416+
417+
it.each(["failed", "stopped"] as const)(
418+
"marks a backgrounded subagent ERROR when task_notification reports %s",
419+
async (status) => {
420+
const { spans } = await run(backgroundedSubagentJourney({ status }));
421+
const subagent = one(spans, "claude_agent.subagent.code-reviewer");
422+
expect(subagent.attributes["claude_agent.subagent.status"]).toBe(status);
423+
expect(subagent.status.code).toBe(SpanStatusCode.ERROR);
424+
},
425+
);
344426
});
345427

346428
describe("J3: MCP tool error and error result", () => {

‎typescript/packages/traceai_claude_agent_sdk/src/queryWrapper.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,34 @@ function proxyQuery<G extends AsyncGenerator<unknown, unknown, unknown>>(
141141
return value.apply(target, args);
142142
};
143143
}
144+
// backgroundTasks() answers foreground tasks with a "running in the
145+
// background" tool_result: keep their subagent spans open until
146+
// task_notification. Undo if the call rejects or matched nothing.
147+
if (property === "backgroundTasks") {
148+
return function backgroundTasks(this: unknown, ...args: unknown[]) {
149+
let marked: string[] = [];
150+
safe(() => {
151+
marked = queryTracer.markBackgroundRequested(typeof args[0] === "string" ? args[0] : undefined);
152+
});
153+
let result: unknown;
154+
try {
155+
result = value.apply(target, args);
156+
} catch (error) {
157+
safe(() => queryTracer.cancelBackgroundRequest(marked));
158+
throw error;
159+
}
160+
if (marked.length > 0 && result && typeof (result as Promise<unknown>).then === "function") {
161+
// A side branch: the caller still gets the original promise and its rejection.
162+
(result as Promise<unknown>).then(
163+
(ok) => {
164+
if (ok === false) safe(() => queryTracer.cancelBackgroundRequest(marked));
165+
},
166+
() => safe(() => queryTracer.cancelBackgroundRequest(marked)),
167+
);
168+
}
169+
return result;
170+
};
171+
}
144172
return value.bind(target);
145173
},
146174
});

‎typescript/packages/traceai_claude_agent_sdk/src/spans.ts‎

Lines changed: 70 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,12 @@ interface ToolState {
113113
interface SubagentState {
114114
span: Span;
115115
startMs: number;
116+
/** In the background (run_in_background, task_started, task_updated): ends at task_notification. */
116117
backgrounded: boolean;
118+
/** The app called Query.backgroundTasks() and it has not failed (yet). */
119+
backgroundRequested: boolean;
117120
toolEnded: boolean;
121+
toolIsError: boolean;
118122
status?: string;
119123
ended: boolean;
120124
}
@@ -231,6 +235,8 @@ export class QueryTracer {
231235
private readonly scopes = new Map<Scope, ScopeState>();
232236
private readonly tools = new Map<string, ToolState>();
233237
private readonly subagents = new Map<string, SubagentState>();
238+
/** task_id -> tool_use_id from task_started; task_updated carries only task_id. */
239+
private readonly taskToolUseIds = new Map<string, string>();
234240

235241
constructor(args: {
236242
tracer: Tracer;
@@ -549,6 +555,9 @@ export class QueryTracer {
549555
break;
550556
}
551557
case "task_started": {
558+
if (typeof message.task_id === "string" && typeof message.tool_use_id === "string") {
559+
this.taskToolUseIds.set(message.task_id, message.tool_use_id);
560+
}
552561
const sub = message.tool_use_id ? this.subagents.get(message.tool_use_id) : undefined;
553562
if (sub && !sub.ended) {
554563
if (typeof message.task_id === "string") {
@@ -560,15 +569,26 @@ export class QueryTracer {
560569
}
561570
break;
562571
}
572+
case "task_updated": {
573+
// A foreground task moved to the background (sdk.d.ts:6059). Its tool_result
574+
// becomes a "running in the background" placeholder; the subagent keeps
575+
// running until task_notification.
576+
const id = typeof message.task_id === "string" ? this.taskToolUseIds.get(message.task_id) : undefined;
577+
const sub = id ? this.subagents.get(id) : undefined;
578+
if (sub && !sub.ended && message.patch?.is_backgrounded === true) {
579+
sub.backgrounded = true;
580+
}
581+
break;
582+
}
563583
case "task_notification": {
564584
const id = message.tool_use_id;
565585
const sub = id ? this.subagents.get(id) : undefined;
566586
if (sub && !sub.ended && typeof message.status === "string") {
567587
sub.status = message.status;
568588
sub.span.setAttribute(T.SUBAGENT_STATUS, message.status);
569589
// A backgrounded subagent outlives its tool_result; it ends here.
570-
if (sub.backgrounded || sub.toolEnded) {
571-
this.endSubagent(id!, message.status !== "completed");
590+
if (sub.backgrounded || sub.backgroundRequested || sub.toolEnded) {
591+
this.endSubagent(id!, sub.toolIsError);
572592
}
573593
}
574594
break;
@@ -716,7 +736,8 @@ export class QueryTracer {
716736
const sub = this.subagents.get(id);
717737
if (sub && !sub.ended) {
718738
sub.toolEnded = true;
719-
if (!sub.backgrounded) {
739+
sub.toolIsError = isError;
740+
if (!sub.backgrounded && !sub.backgroundRequested) {
720741
this.endSubagent(id, isError);
721742
}
722743
}
@@ -783,11 +804,52 @@ export class QueryTracer {
783804
span,
784805
startMs,
785806
backgrounded: fields.run_in_background === true,
807+
backgroundRequested: false,
786808
toolEnded: false,
809+
toolIsError: false,
787810
ended: false,
788811
});
789812
}
790813

814+
/**
815+
* The app called `Query.backgroundTasks(toolUseId?)` (sdk.d.ts:3234). Mark the
816+
* matching foreground subagents as background now: their "running in the
817+
* background" tool_result may arrive before any task_updated. Returns the ids
818+
* marked, for `cancelBackgroundRequest` if the call fails.
819+
*/
820+
markBackgroundRequested(toolUseId?: string): string[] {
821+
const marked: string[] = [];
822+
if (this.finished) return marked;
823+
try {
824+
for (const [id, sub] of this.subagents) {
825+
if (sub.ended || sub.toolEnded || sub.backgrounded || sub.backgroundRequested) continue;
826+
if (toolUseId !== undefined && id !== toolUseId) continue;
827+
sub.backgroundRequested = true;
828+
marked.push(id);
829+
}
830+
} catch (error) {
831+
diag.debug(`@traceai/claude-agent-sdk: failed to record backgroundTasks(): ${error}`);
832+
}
833+
return marked;
834+
}
835+
836+
/** `backgroundTasks()` rejected or matched nothing: those subagents stay foreground. */
837+
cancelBackgroundRequest(ids: string[]): void {
838+
if (this.finished) return;
839+
try {
840+
for (const id of ids) {
841+
const sub = this.subagents.get(id);
842+
if (!sub || sub.ended || !sub.backgroundRequested) continue;
843+
sub.backgroundRequested = false;
844+
if (sub.toolEnded && !sub.backgrounded) {
845+
this.endSubagent(id, sub.toolIsError);
846+
}
847+
}
848+
} catch (error) {
849+
diag.debug(`@traceai/claude-agent-sdk: failed to record backgroundTasks() failure: ${error}`);
850+
}
851+
}
852+
791853
private endSubagent(toolUseId: string, isError: boolean): void {
792854
const sub = this.subagents.get(toolUseId);
793855
if (!sub || sub.ended) return;
@@ -797,11 +859,14 @@ export class QueryTracer {
797859
this.endTurn(scopeState.currentTurn);
798860
}
799861
sub.ended = true;
862+
// task_notification status failed / stopped is an error even when the
863+
// tool_result itself was not.
864+
const failed = isError || (sub.status !== undefined && sub.status !== "completed");
800865
const endMs = clockMs();
801866
sub.span.setAttribute(A.TOOL_DURATION_MS, endMs - sub.startMs);
802-
sub.span.setAttribute(A.TOOL_IS_ERROR, isError);
867+
sub.span.setAttribute(A.TOOL_IS_ERROR, failed);
803868
sub.span.setStatus(
804-
isError
869+
failed
805870
? { code: SpanStatusCode.ERROR, message: sub.status ? `subagent ${sub.status}` : "subagent error" }
806871
: { code: SpanStatusCode.OK },
807872
);

‎typescript/packages/traceai_claude_agent_sdk/src/types.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,14 @@ export interface SystemMessageLike {
7979
model?: string;
8080
permissionMode?: string;
8181
mcp_servers?: { name: string; status?: string }[];
82-
/** task_started / task_notification / task_progress */
82+
/** task_started / task_notification / task_progress / task_updated */
8383
task_id?: string;
8484
tool_use_id?: string;
8585
status?: string;
8686
subagent_type?: string;
8787
is_backgrounded?: boolean;
88+
/** task_updated: the TaskState fields that changed (sdk.d.ts SDKTaskUpdatedMessage). */
89+
patch?: { is_backgrounded?: boolean; status?: string };
8890
}
8991

9092
export type SDKMessageLike =

0 commit comments

Comments
 (0)