Skip to content

Commit cb64162

Browse files
fix(server): Claude monitors show as monitors, not commands (pingdotgg#14191)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent e49357f commit cb64162

7 files changed

Lines changed: 451 additions & 12 deletions

File tree

‎apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import {
6767
CLAUDE_BACKGROUND_SUBAGENT_LIFECYCLE_RESUME_PROMPT,
6868
CLAUDE_BACKGROUND_SUBAGENT_LIFECYCLE_STOP_PROMPT,
6969
} from "../src/orchestration-v2/testkit/fixtures/claude_background_subagent_lifecycle/input.ts";
70+
import { CLAUDE_BACKGROUND_MONITOR_WAKE_PROMPT } from "../src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/input.ts";
7071
import { CLAUDE_BACKGROUND_TASK_INTERRUPT_PROMPT } from "../src/orchestration-v2/testkit/fixtures/claude_background_task_interrupt/input.ts";
7172
import { CLAUDE_BACKGROUND_WAKE_BEFORE_QUEUED_PROMPT_LAUNCH_PROMPT } from "../src/orchestration-v2/testkit/fixtures/claude_background_wake_before_queued_prompt/input.ts";
7273
import {
@@ -192,6 +193,13 @@ const CLAUDE_RECORDINGS = {
192193
enableTools: true,
193194
backgroundWakeCounts: [1, 0],
194195
},
196+
claude_background_monitor_wake: {
197+
prompts: [CLAUDE_BACKGROUND_MONITOR_WAKE_PROMPT],
198+
defaultTranscriptFile: "fixtures/claude_background_monitor_wake/claude_transcript.ndjson",
199+
queryMode: "streaming",
200+
enableTools: true,
201+
backgroundWakeCounts: [1],
202+
},
195203
claude_background_subagent_lifecycle: {
196204
prompts: [
197205
CLAUDE_BACKGROUND_SUBAGENT_LIFECYCLE_LAUNCH_PROMPT,

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3308,6 +3308,141 @@ describe("ClaudeAdapterV2 background wake turns", () => {
33083308
),
33093309
);
33103310

3311+
// Frame shapes follow the claude_background_monitor_wake recording: Claude
3312+
// runs a Monitor as a local_bash task, linked to its call by tool_use_id.
3313+
it.effect("keeps a running Claude monitor typed after many newer monitors end", () =>
3314+
Effect.scoped(
3315+
Effect.gen(function* () {
3316+
const harness = yield* makeWakeHarness;
3317+
const now = yield* DateTime.now;
3318+
let frameNumber = 0;
3319+
const nextUuid = () => `00000000-0000-4000-8000-${String(++frameNumber).padStart(12, "0")}`;
3320+
const monitorFrames = (index: number) => {
3321+
const taskId = `monitor-task-${index}`;
3322+
const toolUseId = `toolu_monitor_${index}`;
3323+
const description = `Monitor ${index}`;
3324+
return {
3325+
taskId,
3326+
start: [
3327+
claudeSdkFrame({
3328+
type: "assistant",
3329+
message: {
3330+
model: "claude-sonnet-4-6",
3331+
id: `msg_monitor_${index}`,
3332+
type: "message",
3333+
role: "assistant",
3334+
content: [
3335+
{
3336+
type: "tool_use",
3337+
id: toolUseId,
3338+
name: "Monitor",
3339+
input: { description, command: "sleep 8 && echo MONITOR_DONE" },
3340+
},
3341+
],
3342+
stop_reason: null,
3343+
stop_sequence: null,
3344+
usage: { input_tokens: 1, output_tokens: 1 },
3345+
},
3346+
parent_tool_use_id: null,
3347+
uuid: nextUuid(),
3348+
session_id: WAKE_NATIVE_SESSION,
3349+
}),
3350+
claudeSdkFrame({
3351+
type: "system",
3352+
subtype: "task_started",
3353+
task_id: taskId,
3354+
tool_use_id: toolUseId,
3355+
description,
3356+
is_backgrounded: true,
3357+
task_type: "local_bash",
3358+
uuid: nextUuid(),
3359+
session_id: WAKE_NATIVE_SESSION,
3360+
}),
3361+
claudeSdkFrame({
3362+
type: "user",
3363+
message: {
3364+
role: "user",
3365+
content: [
3366+
{
3367+
type: "tool_result",
3368+
tool_use_id: toolUseId,
3369+
content: `Monitor started (task ${taskId}).`,
3370+
},
3371+
],
3372+
},
3373+
parent_tool_use_id: null,
3374+
uuid: nextUuid(),
3375+
session_id: WAKE_NATIVE_SESSION,
3376+
tool_use_result: { taskId, persistent: false },
3377+
}),
3378+
],
3379+
end: claudeSdkFrame({
3380+
type: "system",
3381+
subtype: "task_notification",
3382+
task_id: taskId,
3383+
tool_use_id: toolUseId,
3384+
status: "completed",
3385+
output_file: `/tmp/claude-replay/tasks/${taskId}.output`,
3386+
summary: `Monitor "${description}" stream ended`,
3387+
uuid: nextUuid(),
3388+
session_id: WAKE_NATIVE_SESSION,
3389+
}),
3390+
};
3391+
};
3392+
3393+
yield* harness.runtime.startTurn(
3394+
makeClaudeTestTurnInput({
3395+
threadId: harness.threadId,
3396+
providerThread: harness.providerThread,
3397+
now,
3398+
attemptId: RunAttemptId.make("attempt-claude-many-monitors"),
3399+
text: "Watch the deploy, then re-arm short watches.",
3400+
attachments: [],
3401+
}),
3402+
);
3403+
const longRunning = monitorFrames(0);
3404+
for (const frame of longRunning.start) {
3405+
yield* Queue.offer(harness.sdkMessages, frame);
3406+
}
3407+
// More newer monitors start and end than any fixed id cap would hold.
3408+
for (let index = 1; index <= 65; index++) {
3409+
const monitor = monitorFrames(index);
3410+
for (const frame of monitor.start) {
3411+
yield* Queue.offer(harness.sdkMessages, frame);
3412+
}
3413+
yield* Queue.offer(harness.sdkMessages, monitor.end);
3414+
}
3415+
yield* Queue.offer(
3416+
harness.sdkMessages,
3417+
claudeSdkFrame({
3418+
type: "system",
3419+
subtype: "background_tasks_changed",
3420+
tasks: [
3421+
{
3422+
task_id: longRunning.taskId,
3423+
task_type: "local_bash",
3424+
description: "Monitor 0",
3425+
},
3426+
],
3427+
uuid: nextUuid(),
3428+
session_id: WAKE_NATIVE_SESSION,
3429+
}),
3430+
);
3431+
yield* Queue.offer(
3432+
harness.sdkMessages,
3433+
makeResultFrame({ uuid: nextUuid(), result: "Watching." }),
3434+
);
3435+
yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
3436+
3437+
const roster = providerThreadRosterEvents(harness.events).at(-1)?.providerThread
3438+
.pendingBackgroundTasks;
3439+
assert.deepEqual(roster, [
3440+
{ taskId: longRunning.taskId, kind: "monitor", description: "Monitor 0" },
3441+
]);
3442+
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
3443+
),
3444+
);
3445+
33113446
it.effect("stops background work after the turn settled", () =>
33123447
Effect.scoped(
33133448
Effect.gen(function* () {

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 107 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1576,6 +1576,7 @@ const CLAUDE_KNOWN_TOOL_CLASSIFICATIONS: Record<
15761576
glob: { itemType: "dynamic_tool", requestKind: "file-read" },
15771577
grep: { itemType: "dynamic_tool", requestKind: "file-read" },
15781578
ls: { itemType: "dynamic_tool", requestKind: "file-read" },
1579+
monitor: { itemType: "dynamic_tool", requestKind: "command" },
15791580
multiedit: { itemType: "file_change", requestKind: "file-change" },
15801581
notebookedit: { itemType: "file_change", requestKind: "file-change" },
15811582
read: { itemType: "dynamic_tool", requestKind: "file-read" },
@@ -1700,14 +1701,18 @@ function isClaudeOpaqueBackgroundTaskType(taskType: string | null | undefined):
17001701
function claudePendingBackgroundTask(input: {
17011702
readonly taskId: string;
17021703
readonly taskType: string | null;
1704+
// Claude runs a Monitor as a local_bash task, so only the Monitor tool call
1705+
// that started it tells it apart from a background Bash command.
1706+
readonly startedByMonitor: boolean;
17031707
readonly description: string | undefined;
17041708
}): OrchestrationV2PendingBackgroundTask {
17051709
return {
17061710
taskId: input.taskId,
1707-
kind:
1708-
(input.taskType === null
1709-
? undefined
1710-
: CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS.get(input.taskType)) ?? "background_task",
1711+
kind: input.startedByMonitor
1712+
? "monitor"
1713+
: ((input.taskType === null
1714+
? undefined
1715+
: CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS.get(input.taskType)) ?? "background_task"),
17111716
...(input.description !== undefined && input.description.trim().length > 0
17121717
? { description: input.description }
17131718
: {}),
@@ -1742,6 +1747,7 @@ function claudePendingBackgroundTasksFromRoster(
17421747

17431748
function parseClaudeBackgroundTaskEntry(
17441749
entry: unknown,
1750+
monitorTasks: ReadonlyMap<string, unknown>,
17451751
): OrchestrationV2PendingBackgroundTask | null {
17461752
if (entry === null || typeof entry !== "object") {
17471753
return null;
@@ -1761,6 +1767,7 @@ function parseClaudeBackgroundTaskEntry(
17611767
return claudePendingBackgroundTask({
17621768
taskId,
17631769
taskType,
1770+
startedByMonitor: monitorTasks.has(taskId),
17641771
description: typeof description === "string" ? description : undefined,
17651772
});
17661773
}
@@ -2944,6 +2951,68 @@ export function makeClaudeAdapterV2(
29442951
const lastKnownOpaqueTasks = yield* Ref.make(
29452952
new Map<string, OrchestrationV2PendingBackgroundTask>(),
29462953
);
2954+
// Live Claude monitors. A Monitor call waits in `calls` until its
2955+
// task_started links it to a task, or its tool_result ends the call
2956+
// without one. A task stays in `tasks` until it leaves its native
2957+
// thread's roster or its task_notification arrives, so a monitor is
2958+
// never forgotten while it runs.
2959+
const claudeMonitors = yield* Ref.make<{
2960+
readonly calls: ReadonlySet<string>;
2961+
readonly tasks: ReadonlyMap<
2962+
string,
2963+
{ readonly toolUseId: string; readonly nativeThreadId: string }
2964+
>;
2965+
}>({ calls: new Set(), tasks: new Map() });
2966+
const trackClaudeMonitorCalls = (message: SDKMessage) => {
2967+
const started = claudeToolUseBlocksFromAssistantMessage(message).flatMap((toolUse) =>
2968+
toolUse.name === "Monitor" ? [toolUse.id] : [],
2969+
);
2970+
const returned = [
2971+
...claudeToolResultBlocksFromAssistantMessage(message),
2972+
...claudeToolResultBlocksFromUserMessage(message),
2973+
].map((toolResult) => toolResult.tool_use_id);
2974+
if (started.length === 0 && returned.length === 0) return Effect.void;
2975+
return Ref.update(claudeMonitors, (current) => {
2976+
// A replayed tool_use frame must not reopen a call whose task already started.
2977+
const linked = new Set([...current.tasks.values()].map((task) => task.toolUseId));
2978+
const opened = started.filter((id) => !linked.has(id) && !current.calls.has(id));
2979+
const closed = returned.filter((id) => current.calls.has(id));
2980+
if (opened.length === 0 && closed.length === 0) return current;
2981+
const calls = new Set([...current.calls, ...opened]);
2982+
for (const id of closed) calls.delete(id);
2983+
return { ...current, calls };
2984+
});
2985+
};
2986+
/** True when a Monitor call started this task; links the task to that call. */
2987+
const isClaudeMonitorTask = (input: {
2988+
readonly nativeThreadId: string;
2989+
readonly taskId: string;
2990+
readonly toolUseId: string | undefined;
2991+
}) =>
2992+
Ref.modify(claudeMonitors, (current) => {
2993+
if (current.tasks.has(input.taskId)) return [true, current] as const;
2994+
if (input.toolUseId === undefined || !current.calls.has(input.toolUseId)) {
2995+
return [false, current] as const;
2996+
}
2997+
const calls = new Set(current.calls);
2998+
calls.delete(input.toolUseId);
2999+
const tasks = new Map(current.tasks).set(input.taskId, {
3000+
toolUseId: input.toolUseId,
3001+
nativeThreadId: input.nativeThreadId,
3002+
});
3003+
return [true, { calls, tasks }] as const;
3004+
});
3005+
/** Drops monitor tasks that ended: gone from the thread's roster, or notified. */
3006+
const endClaudeMonitorTasks = (
3007+
ended: (taskId: string, task: { readonly nativeThreadId: string }) => boolean,
3008+
) =>
3009+
Ref.modify(claudeMonitors, (current) => {
3010+
const endedIds = [...current.tasks].filter(([taskId, task]) => ended(taskId, task));
3011+
if (endedIds.length === 0) return [current.tasks, current] as const;
3012+
const tasks = new Map(current.tasks);
3013+
for (const [taskId] of endedIds) tasks.delete(taskId);
3014+
return [tasks, { ...current, tasks }] as const;
3015+
});
29473016
const claudeTaskOutcome = (status: "completed" | "failed" | "stopped") =>
29483017
status === "completed" ? "completed" : status === "stopped" ? "cancelled" : "failed";
29493018
// Reads the roster, so call it before the notification clears the task from it.
@@ -3285,13 +3354,17 @@ export function makeClaudeAdapterV2(
32853354
});
32863355

32873356
const clearPendingBackgroundTasksForNativeThread = (nativeThreadId: string) =>
3288-
Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
3289-
if (!current.has(nativeThreadId)) {
3290-
return current;
3291-
}
3292-
const updated = new Map(current);
3293-
updated.delete(nativeThreadId);
3294-
return updated;
3357+
Effect.gen(function* () {
3358+
yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
3359+
if (!current.has(nativeThreadId)) {
3360+
return current;
3361+
}
3362+
const updated = new Map(current);
3363+
updated.delete(nativeThreadId);
3364+
return updated;
3365+
});
3366+
// The thread's process died or its turn failed; those monitors never notify.
3367+
yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId);
32953368
});
32963369

32973370
// Drop idle wake traffic for a dead native process so it cannot pin
@@ -4969,8 +5042,21 @@ export function makeClaudeAdapterV2(
49695042
return false;
49705043
}
49715044
const nextTasks: OrchestrationV2PendingBackgroundTask[] = [];
5045+
const listedTaskIds = new Set(
5046+
roster.flatMap((entry) => {
5047+
const taskId =
5048+
entry !== null && typeof entry === "object"
5049+
? Reflect.get(entry, "task_id")
5050+
: undefined;
5051+
return typeof taskId === "string" ? [taskId] : [];
5052+
}),
5053+
);
5054+
const monitorTasks = yield* endClaudeMonitorTasks(
5055+
(taskId, task) =>
5056+
task.nativeThreadId === input.nativeThreadId && !listedTaskIds.has(taskId),
5057+
);
49725058
for (const entry of roster) {
4973-
const task = parseClaudeBackgroundTaskEntry(entry);
5059+
const task = parseClaudeBackgroundTaskEntry(entry, monitorTasks);
49745060
if (task !== null) {
49755061
nextTasks.push(task);
49765062
}
@@ -4992,12 +5078,18 @@ export function makeClaudeAdapterV2(
49925078
claudePendingBackgroundTask({
49935079
taskId: message.task_id,
49945080
taskType: claudeTaskTypeFromSdkMessage(message),
5081+
startedByMonitor: yield* isClaudeMonitorTask({
5082+
nativeThreadId: input.nativeThreadId,
5083+
taskId: message.task_id,
5084+
toolUseId: message.tool_use_id,
5085+
}),
49955086
description:
49965087
typeof message.description === "string" ? message.description : undefined,
49975088
}),
49985089
);
49995090
rosterChanged = true;
50005091
} else if (message.type === "system" && message.subtype === "task_notification") {
5092+
yield* endClaudeMonitorTasks((taskId) => taskId === message.task_id);
50015093
const removed = yield* clearPendingBackgroundTask(
50025094
input.nativeThreadId,
50035095
message.task_id,
@@ -5054,6 +5146,9 @@ export function makeClaudeAdapterV2(
50545146
}
50555147

50565148
const message = input.message;
5149+
// Before any routing: a Monitor started during an idle wake turn
5150+
// reports its task before the drain replays the tool call.
5151+
yield* trackClaudeMonitorCalls(message);
50575152
if (message.type === "rate_limit_event") {
50585153
const rateLimitInfo = message.rate_limit_info;
50595154
if (!rateLimitInfo) return;

0 commit comments

Comments
 (0)