@agentclientprotocol/claude-agent-acp 0.102.0 → 0.102.1-preview.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/acp-agent.d.ts +119 -439
- package/dist/acp-agent.d.ts.map +1 -1
- package/dist/acp-agent.js +380 -2412
- package/dist/acp-subagents.d.ts +1 -2
- package/dist/acp-subagents.d.ts.map +1 -1
- package/dist/auth-methods.d.ts +21 -0
- package/dist/auth-methods.d.ts.map +1 -0
- package/dist/auth-methods.js +68 -0
- package/dist/auth-status-reporter.d.ts +112 -0
- package/dist/auth-status-reporter.d.ts.map +1 -0
- package/dist/auth-status-reporter.js +253 -0
- package/dist/background-work.d.ts +12 -265
- package/dist/background-work.d.ts.map +1 -1
- package/dist/background-work.js +8 -558
- package/dist/client-system-prompt.d.ts +7 -0
- package/dist/client-system-prompt.d.ts.map +1 -1
- package/dist/client-system-prompt.js +24 -0
- package/dist/context-compaction.d.ts +20 -0
- package/dist/context-compaction.d.ts.map +1 -1
- package/dist/context-compaction.js +26 -0
- package/dist/context-window.d.ts +70 -0
- package/dist/context-window.d.ts.map +1 -0
- package/dist/context-window.js +132 -0
- package/dist/diff.d.ts +1 -1
- package/dist/diff.js +1 -1
- package/dist/elicitation.d.ts +66 -1
- package/dist/elicitation.d.ts.map +1 -1
- package/dist/elicitation.js +109 -0
- package/dist/file-change-audit.d.ts +4 -3
- package/dist/file-change-audit.d.ts.map +1 -1
- package/dist/file-change-audit.js +3 -2
- package/dist/mcp-oauth.d.ts +44 -0
- package/dist/mcp-oauth.d.ts.map +1 -0
- package/dist/mcp-oauth.js +142 -0
- package/dist/mcp-servers.d.ts +10 -0
- package/dist/mcp-servers.d.ts.map +1 -0
- package/dist/mcp-servers.js +29 -0
- package/dist/native-subagents.d.ts +18 -8
- package/dist/native-subagents.d.ts.map +1 -1
- package/dist/native-subagents.js +7 -35
- package/dist/permissions/presentation.d.ts +29 -0
- package/dist/permissions/presentation.d.ts.map +1 -1
- package/dist/permissions/presentation.js +38 -11
- package/dist/plans.d.ts +36 -6
- package/dist/plans.d.ts.map +1 -1
- package/dist/plans.js +49 -11
- package/dist/prompt-suggestions.d.ts +29 -0
- package/dist/prompt-suggestions.d.ts.map +1 -1
- package/dist/prompt-suggestions.js +45 -0
- package/dist/providers.d.ts +139 -0
- package/dist/providers.d.ts.map +1 -0
- package/dist/providers.js +286 -0
- package/dist/remote-control.d.ts +62 -0
- package/dist/remote-control.d.ts.map +1 -0
- package/dist/remote-control.js +78 -0
- package/dist/result-end.d.ts +39 -0
- package/dist/result-end.d.ts.map +1 -0
- package/dist/result-end.js +50 -0
- package/dist/serve.d.ts +7 -2
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +10 -5
- package/dist/session-config-ids.d.ts +1 -0
- package/dist/session-config-ids.d.ts.map +1 -1
- package/dist/session-config-ids.js +1 -0
- package/dist/session-config-options.d.ts +64 -0
- package/dist/session-config-options.d.ts.map +1 -0
- package/dist/session-config-options.js +162 -0
- package/dist/session-effort.d.ts +67 -0
- package/dist/session-effort.d.ts.map +1 -1
- package/dist/session-effort.js +98 -0
- package/dist/session-env.d.ts +22 -0
- package/dist/session-env.d.ts.map +1 -0
- package/dist/session-env.js +66 -0
- package/dist/session-fast-mode.d.ts +83 -0
- package/dist/session-fast-mode.d.ts.map +1 -0
- package/dist/session-fast-mode.js +142 -0
- package/dist/session-index/connection.d.ts +2 -5
- package/dist/session-index/connection.d.ts.map +1 -1
- package/dist/session-index/connection.js +3 -5
- package/dist/session-mode.d.ts +1 -0
- package/dist/session-mode.d.ts.map +1 -1
- package/dist/session-mode.js +1 -1
- package/dist/session-model.d.ts +41 -0
- package/dist/session-model.d.ts.map +1 -1
- package/dist/session-model.js +110 -45
- package/dist/session-notices.d.ts +44 -0
- package/dist/session-notices.d.ts.map +1 -1
- package/dist/session-notices.js +68 -0
- package/dist/session-titles.d.ts +34 -12
- package/dist/session-titles.d.ts.map +1 -1
- package/dist/session-titles.js +7 -6
- package/dist/session-usage.d.ts +125 -0
- package/dist/session-usage.d.ts.map +1 -0
- package/dist/session-usage.js +196 -0
- package/dist/streamed-text.d.ts +33 -0
- package/dist/streamed-text.d.ts.map +1 -0
- package/dist/streamed-text.js +71 -0
- package/dist/subagent-configuration.d.ts +32 -0
- package/dist/subagent-configuration.d.ts.map +1 -0
- package/dist/subagent-configuration.js +70 -0
- package/dist/subagent-replay.d.ts +18 -0
- package/dist/subagent-replay.d.ts.map +1 -1
- package/dist/subagent-replay.js +25 -15
- package/dist/tool-calls/client-capabilities.d.ts +8 -8
- package/dist/tool-calls/client-capabilities.js +4 -4
- package/dist/tool-calls/renderer.d.ts +4 -5
- package/dist/tool-calls/renderer.d.ts.map +1 -1
- package/dist/tool-calls/renderer.js +4 -5
- package/dist/turn-events.d.ts +6 -46
- package/dist/turn-events.d.ts.map +1 -1
- package/dist/v2/agent.d.ts +7 -11
- package/dist/v2/agent.d.ts.map +1 -1
- package/dist/v2/agent.js +751 -331
- package/dist/v2/air.d.ts +33 -0
- package/dist/v2/air.d.ts.map +1 -0
- package/dist/v2/air.js +29 -0
- package/dist/v2/auth.d.ts +97 -0
- package/dist/v2/auth.d.ts.map +1 -0
- package/dist/v2/auth.js +216 -0
- package/dist/v2/background.d.ts +27 -16
- package/dist/v2/background.d.ts.map +1 -1
- package/dist/v2/background.js +4 -32
- package/dist/v2/child-config.d.ts +55 -0
- package/dist/v2/child-config.d.ts.map +1 -0
- package/dist/v2/child-config.js +92 -0
- package/dist/v2/clear-context.d.ts +94 -0
- package/dist/v2/clear-context.d.ts.map +1 -0
- package/dist/v2/clear-context.js +176 -0
- package/dist/v2/commands.d.ts +46 -0
- package/dist/v2/commands.d.ts.map +1 -0
- package/dist/v2/commands.js +54 -0
- package/dist/v2/config.d.ts +187 -0
- package/dist/v2/config.d.ts.map +1 -0
- package/dist/v2/config.js +494 -0
- package/dist/v2/elicitation.d.ts +93 -0
- package/dist/v2/elicitation.d.ts.map +1 -0
- package/dist/v2/elicitation.js +160 -0
- package/dist/v2/file-changes.d.ts +61 -0
- package/dist/v2/file-changes.d.ts.map +1 -0
- package/dist/v2/file-changes.js +108 -0
- package/dist/v2/file-preview.d.ts +18 -0
- package/dist/v2/file-preview.d.ts.map +1 -0
- package/dist/v2/file-preview.js +29 -0
- package/dist/v2/initialize.d.ts +10 -24
- package/dist/v2/initialize.d.ts.map +1 -1
- package/dist/v2/initialize.js +4 -111
- package/dist/v2/outcome.d.ts +81 -0
- package/dist/v2/outcome.d.ts.map +1 -0
- package/dist/v2/outcome.js +165 -0
- package/dist/v2/permissions.d.ts +92 -0
- package/dist/v2/permissions.d.ts.map +1 -0
- package/dist/v2/permissions.js +162 -0
- package/dist/v2/prompt.d.ts +2 -42
- package/dist/v2/prompt.d.ts.map +1 -1
- package/dist/v2/prompt.js +2 -119
- package/dist/v2/remote-control.d.ts +41 -0
- package/dist/v2/remote-control.d.ts.map +1 -0
- package/dist/v2/remote-control.js +63 -0
- package/dist/v2/reports.d.ts +198 -0
- package/dist/v2/reports.d.ts.map +1 -0
- package/dist/v2/reports.js +487 -0
- package/dist/v2/restarts.d.ts +128 -0
- package/dist/v2/restarts.d.ts.map +1 -0
- package/dist/v2/restarts.js +348 -0
- package/dist/v2/session-requests.d.ts +20 -0
- package/dist/v2/session-requests.d.ts.map +1 -0
- package/dist/v2/session-requests.js +108 -0
- package/dist/v2/session-update.d.ts +2 -13
- package/dist/v2/session-update.d.ts.map +1 -1
- package/dist/v2/session-update.js +2 -22
- package/dist/v2/session.d.ts +340 -41
- package/dist/v2/session.d.ts.map +1 -1
- package/dist/v2/session.js +1223 -141
- package/dist/v2/setup.d.ts +49 -0
- package/dist/v2/setup.d.ts.map +1 -0
- package/dist/v2/setup.js +62 -0
- package/dist/v2/stopped-work.d.ts +123 -0
- package/dist/v2/stopped-work.d.ts.map +1 -0
- package/dist/v2/stopped-work.js +210 -0
- package/dist/v2/stream.d.ts +228 -0
- package/dist/v2/stream.d.ts.map +1 -0
- package/dist/v2/stream.js +506 -0
- package/dist/v2/subagent-replay.d.ts +115 -0
- package/dist/v2/subagent-replay.d.ts.map +1 -0
- package/dist/v2/subagent-replay.js +479 -0
- package/dist/v2/subscription-guard.d.ts +60 -0
- package/dist/v2/subscription-guard.d.ts.map +1 -0
- package/dist/v2/subscription-guard.js +84 -0
- package/dist/v2/tasks.d.ts +492 -0
- package/dist/v2/tasks.d.ts.map +1 -0
- package/dist/v2/tasks.js +1728 -0
- package/dist/v2/terminal.d.ts.map +1 -1
- package/dist/v2/terminal.js +6 -1
- package/dist/v2/tool-call.d.ts +3 -2
- package/dist/v2/tool-call.d.ts.map +1 -1
- package/dist/v2/update-translator.d.ts +36 -0
- package/dist/v2/update-translator.d.ts.map +1 -0
- package/dist/v2/update-translator.js +80 -0
- package/dist/workflow-progress.d.ts +23 -0
- package/dist/workflow-progress.d.ts.map +1 -1
- package/dist/workflow-progress.js +31 -8
- package/package.json +1 -1
- package/dist/v2/permission.d.ts +0 -28
- package/dist/v2/permission.d.ts.map +0 -1
- package/dist/v2/permission.js +0 -41
package/dist/v2/tasks.js
ADDED
|
@@ -0,0 +1,1728 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code's tasks of one root session, as ACP v2 reports them: its
|
|
3
|
+
* subagents as child sessions (the subagents RFD), and the work that runs in
|
|
4
|
+
* the background as the `background` list of each session's states.
|
|
5
|
+
*
|
|
6
|
+
* Claude Code reports each task with `task_started`, then `task_updated`
|
|
7
|
+
* patches, and its end with `task_notification` (or a terminal `task_updated`
|
|
8
|
+
* patch, the only one it promises per transition). `background_tasks_changed`
|
|
9
|
+
* is its live set of background tasks. From those:
|
|
10
|
+
*
|
|
11
|
+
* - A subagent (`local_agent`) is a child session whose id is its agent id,
|
|
12
|
+
* the same session for every delegation to it (a SendMessage resume starts
|
|
13
|
+
* it again under the same `task_id`). It is announced on the session that
|
|
14
|
+
* made the Agent or Task call that launched it, once both its `task_started`
|
|
15
|
+
* and that call came, with `subagent_update`, before any of its traffic.
|
|
16
|
+
* Its messages carry the `parent_tool_use_id` of that call, also after a
|
|
17
|
+
* resume, and go to its stream; those that come before the announcement
|
|
18
|
+
* wait for it. A child that ends before it is announced stays unexposed.
|
|
19
|
+
* Each run of it is the child's foreground work: `running` from its start
|
|
20
|
+
* to its end, on its stream and mirrored on the parent's `subagent_update`.
|
|
21
|
+
* - The parent is not shown the Agent call of an announced child: the call's
|
|
22
|
+
* prompt is the parent's outgoing `session_message` and the child's
|
|
23
|
+
* incoming one, and a foreground child's answer is its reply to the parent.
|
|
24
|
+
* The call of a child that was never exposed is shown with its final
|
|
25
|
+
* status. A SendMessage call whose message reaches an announced child,
|
|
26
|
+
* and a child's SubagentHandback call, are session messages too.
|
|
27
|
+
* - The work waits on a subagent that is not `is_backgrounded`, and on the
|
|
28
|
+
* ones that it waits on: their requests block it (`requires_action`), and
|
|
29
|
+
* a cancel of it withdraws them. A subagent in the background is listed in
|
|
30
|
+
* its parent's `background` while it works.
|
|
31
|
+
* - A command that went to the background is its display terminal, kept
|
|
32
|
+
* running from its Bash result until its task ends, with its output read
|
|
33
|
+
* from the file Claude Code writes it to.
|
|
34
|
+
* - A task that a tool call started, such as a `Monitor` or `Workflow` call,
|
|
35
|
+
* is that tool call, kept `in_progress` (or `paused`) until the task ends.
|
|
36
|
+
* A workflow's `task_progress` shows on its call (`workflowCard`).
|
|
37
|
+
* - Any other background task, such as one that a hook started or one that
|
|
38
|
+
* started after its tool call returned, gets a tool call that the adapter
|
|
39
|
+
* starts for it (`task_<taskId>`), as v2 lists background work only by an
|
|
40
|
+
* entity the client knows.
|
|
41
|
+
*
|
|
42
|
+
* Claude Code's interrupt spares background tasks (`perTaskStopAffordance`),
|
|
43
|
+
* so `session/cancel` leaves listed work running, as v2 asks. A session
|
|
44
|
+
* started without it reports no lists.
|
|
45
|
+
*/
|
|
46
|
+
import * as fs from "node:fs";
|
|
47
|
+
import * as path from "node:path";
|
|
48
|
+
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
|
49
|
+
import { backgroundBashTaskFromToolResult, taskProgressFields } from "../async-tasks.js";
|
|
50
|
+
import { BackgroundOutputTail } from "../background-output.js";
|
|
51
|
+
import { childModelOption, HANDBACK_TOOL, handbackMessage, isNativeSubagentControlTool, launchReply, linkedSessionMessages, mergeSubagentIdentity, responseModelEntry, resumedNativeSubagentId, rfdLabels, sendMessageResume, subagentIdentity, unexposedControlFallback, } from "../native-subagents.js";
|
|
52
|
+
import { subagentLineage } from "../subagent-history.js";
|
|
53
|
+
import { withRunningTerminal, withRunningToolCall } from "../tool-calls/background.js";
|
|
54
|
+
import { ClientCapabilities } from "../tool-calls/client-capabilities.js";
|
|
55
|
+
import { AcpToolCallRenderer } from "../tool-calls/renderer.js";
|
|
56
|
+
import { workflowCard, workflowSnapshot } from "../workflow-progress.js";
|
|
57
|
+
import { ChildConfigurations } from "./child-config.js";
|
|
58
|
+
import { SessionOutput } from "./stream.js";
|
|
59
|
+
import { SubagentReplay } from "./subagent-replay.js";
|
|
60
|
+
/** The tools whose structured result names the task that the call started. */
|
|
61
|
+
const TASK_TOOLS = new Set(["Monitor", "Workflow"]);
|
|
62
|
+
/** The most messages that wait for the announcement of one child. */
|
|
63
|
+
const MAX_PENDING_MESSAGES = 256;
|
|
64
|
+
/** The most children not announced yet whose hooks wait for them. */
|
|
65
|
+
const MAX_PENDING_HOOKS = 64;
|
|
66
|
+
const FINAL_STATUSES = new Set(["completed", "failed", "cancelled"]);
|
|
67
|
+
const V2_RENDERER = new AcpToolCallRenderer(ClientCapabilities.from(undefined, { v2: true }));
|
|
68
|
+
export class SessionTasks {
|
|
69
|
+
host;
|
|
70
|
+
rootOutput;
|
|
71
|
+
/** The subagents, by agent id. */
|
|
72
|
+
children = new Map();
|
|
73
|
+
/** The child of each Agent call that launched or resumed one. */
|
|
74
|
+
childByToolUse = new Map();
|
|
75
|
+
/** The Agent and Task calls, by tool use id. */
|
|
76
|
+
launches = new Map();
|
|
77
|
+
/** The messages of a launch whose child has not started, by launch id. */
|
|
78
|
+
pendingByLaunch = new Map();
|
|
79
|
+
/** The live subagent tasks, by agent id, announced or not. */
|
|
80
|
+
agents = new Map();
|
|
81
|
+
/** The open permission requests of each subagent, by agent id. */
|
|
82
|
+
agentRequests = new Map();
|
|
83
|
+
/** The subagents whose runs a cancel stops, by agent id, until their runs end. */
|
|
84
|
+
cancelledAgents = new Set();
|
|
85
|
+
/** The subagents that the root's last cancel stopped (see {@link foregroundCancelFailed}). */
|
|
86
|
+
foregroundCancelled = new Set();
|
|
87
|
+
/**
|
|
88
|
+
* Whether the root's cancel is in effect: from {@link cancelForeground}
|
|
89
|
+
* until {@link foregroundCancelEnded} or {@link foregroundCancelFailed}.
|
|
90
|
+
*/
|
|
91
|
+
rootCancelling = false;
|
|
92
|
+
/** Set when the root session closes: no request goes to the client after it. */
|
|
93
|
+
closed = false;
|
|
94
|
+
/** The session that made each SendMessage call: the sender of a resumed child's prompt. */
|
|
95
|
+
senderByToolUse = new Map();
|
|
96
|
+
/** The other tasks that `task_started` reported, until they end. */
|
|
97
|
+
started = new Map();
|
|
98
|
+
/** Claude Code's live background tasks, from its last `background_tasks_changed`. */
|
|
99
|
+
level = new Map();
|
|
100
|
+
/** The terminals of the commands that went to the background, by task id. */
|
|
101
|
+
terminals = new Map();
|
|
102
|
+
/**
|
|
103
|
+
* The tool calls whose tasks go on in the background, by task id. A call
|
|
104
|
+
* that the adapter started for its task (see {@link adoptTasks}) has the
|
|
105
|
+
* task's description as its `title` instead of a tool use.
|
|
106
|
+
*/
|
|
107
|
+
toolCalls = new Map();
|
|
108
|
+
/** The tool calls that returned: their tasks no longer hold their work. */
|
|
109
|
+
returned = new Set();
|
|
110
|
+
/** What a subagent's hooks reported before the child was announced, by agent id. */
|
|
111
|
+
startedHooks = new Map();
|
|
112
|
+
/** The children's configurations (see `child-config.ts`). */
|
|
113
|
+
configs;
|
|
114
|
+
/**
|
|
115
|
+
* The SendMessage calls, which the client is not shown until their final
|
|
116
|
+
* update, with their first report and the session that made them. A message
|
|
117
|
+
* that reaches an announced child replaces its call.
|
|
118
|
+
*/
|
|
119
|
+
hiddenSendMessages = new Map();
|
|
120
|
+
/**
|
|
121
|
+
* The SendMessage calls that a permission request showed before their tool
|
|
122
|
+
* use streamed: the client holds them, so they stay shown until their final
|
|
123
|
+
* update, as on v1 (its `eagerToolCallSessions`).
|
|
124
|
+
*/
|
|
125
|
+
shownSendMessages = new Set();
|
|
126
|
+
/**
|
|
127
|
+
* The SubagentHandback calls of announced children, which the client is not
|
|
128
|
+
* shown until their final update, with their first report, the report from
|
|
129
|
+
* their input, and the call that delegated the run.
|
|
130
|
+
*/
|
|
131
|
+
handbacks = new Map();
|
|
132
|
+
/** The restore of a subagent from the session's history, while it reads it (see {@link restore}). */
|
|
133
|
+
restoring;
|
|
134
|
+
constructor(host,
|
|
135
|
+
/** The root session's output, which owns its tool calls. */
|
|
136
|
+
rootOutput) {
|
|
137
|
+
this.host = host;
|
|
138
|
+
this.rootOutput = rootOutput;
|
|
139
|
+
rootOutput.route = (notification) => this.route(rootOutput, notification, undefined);
|
|
140
|
+
this.configs = new ChildConfigurations({
|
|
141
|
+
modes: () => host.modes(),
|
|
142
|
+
models: () => host.models(),
|
|
143
|
+
announced: (agentId) => this.hasChild(agentId),
|
|
144
|
+
});
|
|
145
|
+
// Every state of a session that reports its background work carries a list.
|
|
146
|
+
if (host.reportsBackground) {
|
|
147
|
+
host.background.changed({ sessionId: host.sessionId, items: [], state: undefined });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// --- Claude Code's messages ---------------------------------------------
|
|
151
|
+
/**
|
|
152
|
+
* Takes a message of the query that concerns the tasks. Returns whether it
|
|
153
|
+
* was a child's, which then goes to the child's stream only.
|
|
154
|
+
*/
|
|
155
|
+
handle(message) {
|
|
156
|
+
switch (message.type) {
|
|
157
|
+
case "system":
|
|
158
|
+
switch (message.subtype) {
|
|
159
|
+
case "task_started":
|
|
160
|
+
this.taskStarted(message);
|
|
161
|
+
return true;
|
|
162
|
+
case "task_updated":
|
|
163
|
+
this.taskUpdated(message);
|
|
164
|
+
return true;
|
|
165
|
+
case "task_notification":
|
|
166
|
+
this.taskNotification(message);
|
|
167
|
+
return true;
|
|
168
|
+
case "task_progress":
|
|
169
|
+
this.taskProgress(message);
|
|
170
|
+
return true;
|
|
171
|
+
case "background_tasks_changed":
|
|
172
|
+
this.levelChanged(message.tasks);
|
|
173
|
+
return true;
|
|
174
|
+
default:
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
case "stream_event":
|
|
178
|
+
case "assistant":
|
|
179
|
+
case "user":
|
|
180
|
+
case "tool_progress":
|
|
181
|
+
return this.childMessage(message);
|
|
182
|
+
default:
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The restore of a subagent that {@link handle} started, once: the session
|
|
188
|
+
* handles its next message after it, so the child's traffic finds it.
|
|
189
|
+
*/
|
|
190
|
+
restored() {
|
|
191
|
+
const restoring = this.restoring;
|
|
192
|
+
this.restoring = undefined;
|
|
193
|
+
return restoring;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Restores the agent that a SendMessage result of `output` resumed
|
|
197
|
+
* (`resumedAgentId`), when this process does not know it, as the v1 core
|
|
198
|
+
* does (`sendMessageResumed`): Claude Code can resume an agent without a
|
|
199
|
+
* `task_started`. The caller sends the result's updates after it, so the
|
|
200
|
+
* restored child takes the call's message. Undefined when nothing is
|
|
201
|
+
* restored: the agent is known, or no SendMessage call of the session
|
|
202
|
+
* carried the result.
|
|
203
|
+
*/
|
|
204
|
+
restoreResumed(output, message) {
|
|
205
|
+
const agentId = resumedNativeSubagentId(message.tool_use_result);
|
|
206
|
+
const content = message.message.content;
|
|
207
|
+
if (agentId === undefined || this.children.has(agentId) || !Array.isArray(content)) {
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
const resume = sendMessageResume(output.toolUses(), agentId, content.flatMap((block) => (block.type === "tool_result" ? [block.tool_use_id] : [])));
|
|
211
|
+
if (!resume || !this.senderByToolUse.has(resume.toolUseId))
|
|
212
|
+
return undefined;
|
|
213
|
+
return this.restore(agentId, resume.text, resume.toolUseId);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The tool results of the root session, or of a child (`output`): a
|
|
217
|
+
* background command's terminal and a background task's tool call keep
|
|
218
|
+
* running past them.
|
|
219
|
+
*/
|
|
220
|
+
toolResults(output, message) {
|
|
221
|
+
const content = message.message.content;
|
|
222
|
+
if (!Array.isArray(content))
|
|
223
|
+
return;
|
|
224
|
+
const results = content.filter((block) => block.type === "tool_result");
|
|
225
|
+
for (const { tool_use_id } of results)
|
|
226
|
+
this.returned.add(tool_use_id);
|
|
227
|
+
const toolUses = output.toolUses();
|
|
228
|
+
// Before the result's own updates: a SendMessage call whose message
|
|
229
|
+
// reached its child is that message.
|
|
230
|
+
this.sendMessageResumed(message, results, toolUses);
|
|
231
|
+
const command = backgroundBashTaskFromToolResult(content, message.tool_use_result, toolUses, (toolUseId) => [...this.started].find(([, task]) => task.toolUseId === toolUseId && task.taskType === "local_bash")?.[0]);
|
|
232
|
+
// A fast command can end before its result: then its terminal exits with it.
|
|
233
|
+
const runningTerminal = command && this.started.has(command.taskId) ? command.toolCallId : undefined;
|
|
234
|
+
if (command && runningTerminal) {
|
|
235
|
+
this.terminals.set(command.taskId, {
|
|
236
|
+
toolCallId: command.toolCallId,
|
|
237
|
+
output,
|
|
238
|
+
leveled: this.level.get(command.taskId)?.ambient === false,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
const runningToolCalls = new Set();
|
|
242
|
+
const succeeded = results.filter((block) => block.is_error !== true);
|
|
243
|
+
const structuredTaskId = succeeded.length === 1 &&
|
|
244
|
+
typeof message.tool_use_result === "object" &&
|
|
245
|
+
message.tool_use_result !== null &&
|
|
246
|
+
typeof message.tool_use_result.taskId === "string"
|
|
247
|
+
? message.tool_use_result.taskId
|
|
248
|
+
: undefined;
|
|
249
|
+
// A tool call's task is kept only for a session that lists it.
|
|
250
|
+
for (const { tool_use_id: toolCallId } of this.host.reportsBackground ? succeeded : []) {
|
|
251
|
+
const toolUse = toolUses[toolCallId];
|
|
252
|
+
if (!toolUse || toolUse.name === "Bash" || isNativeSubagentControlTool(toolUse.name)) {
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const taskId = (TASK_TOOLS.has(toolUse.name) ? structuredTaskId : undefined) ??
|
|
256
|
+
[...this.started].find(([, task]) => task.toolUseId === toolCallId)?.[0];
|
|
257
|
+
const task = taskId === undefined ? undefined : this.level.get(taskId);
|
|
258
|
+
if (!task || task.taskType === "local_bash" || task.taskType === "local_agent")
|
|
259
|
+
continue;
|
|
260
|
+
this.toolCalls.set(taskId, {
|
|
261
|
+
toolCallId,
|
|
262
|
+
output,
|
|
263
|
+
toolUse: { name: toolUse.name, input: toolUse.input },
|
|
264
|
+
paused: false,
|
|
265
|
+
});
|
|
266
|
+
runningToolCalls.add(toolCallId);
|
|
267
|
+
}
|
|
268
|
+
output.toolResults(message, (notification) => withRunningToolCall(withRunningTerminal(notification, runningTerminal), runningToolCalls));
|
|
269
|
+
// A workflow can report progress before its launch call returns: it
|
|
270
|
+
// goes on the call after the result's own updates.
|
|
271
|
+
for (const [taskId, toolCall] of this.toolCalls) {
|
|
272
|
+
if (!runningToolCalls.has(toolCall.toolCallId))
|
|
273
|
+
continue;
|
|
274
|
+
const card = workflowCard(this.level.get(taskId)?.progress);
|
|
275
|
+
if (card)
|
|
276
|
+
toolCall.output.taskToolCallProgress(toolCall.toolCallId, card);
|
|
277
|
+
}
|
|
278
|
+
// After the result's own updates: the output replaces their placeholder.
|
|
279
|
+
if (command && runningTerminal) {
|
|
280
|
+
this.followOutput(command.taskId, typeof command.outputFilePath === "string" ? command.outputFilePath : undefined);
|
|
281
|
+
}
|
|
282
|
+
this.publish();
|
|
283
|
+
}
|
|
284
|
+
// --- Subagent sessions ----------------------------------------------------
|
|
285
|
+
/** Reads the subagents that the history `messages` launched, for its replay. */
|
|
286
|
+
loadReplay(messages) {
|
|
287
|
+
return SubagentReplay.load(this.host, messages, {
|
|
288
|
+
tracks: (sessionId) => this.children.has(sessionId),
|
|
289
|
+
configuration: (sessionId) => this.hasChild(sessionId) ? this.configs.published(sessionId) : undefined,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/** Whether a subagent task runs, announced or not, in the foreground or the background. */
|
|
293
|
+
hasLiveSubagents() {
|
|
294
|
+
return this.agents.size > 0;
|
|
295
|
+
}
|
|
296
|
+
/** Whether `sessionId` is an announced child session of this root. */
|
|
297
|
+
hasChild(sessionId) {
|
|
298
|
+
return this.children.get(sessionId)?.announced === true;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* The session that a permission request of the agent `agentId` goes to:
|
|
302
|
+
* its child session once it is announced, else the root. A request can
|
|
303
|
+
* come before its subagent's `task_started`: it blocks the root's work once
|
|
304
|
+
* that shows the subagent runs in the foreground.
|
|
305
|
+
*/
|
|
306
|
+
async target(agentId, root) {
|
|
307
|
+
if (agentId === undefined)
|
|
308
|
+
return root;
|
|
309
|
+
const child = this.children.get(agentId);
|
|
310
|
+
const announced = child?.announced ? child : undefined;
|
|
311
|
+
return {
|
|
312
|
+
sessionId: announced?.sessionId ?? root.sessionId,
|
|
313
|
+
cwd: announced ? this.cwdOf(announced.sessionId) : root.cwd,
|
|
314
|
+
output: announced?.output ?? root.output,
|
|
315
|
+
...(child?.launchToolUseId !== undefined ? { parentToolUseId: child.launchToolUseId } : {}),
|
|
316
|
+
cancelling: () => this.cancelledAgents.has(agentId),
|
|
317
|
+
// The request counts on the session it goes to, also when the child is
|
|
318
|
+
// announced while the request is built.
|
|
319
|
+
requestPermission: (request, toolSignal) => this.agentRequest(agentId, announced, toolSignal, async (signal) => {
|
|
320
|
+
try {
|
|
321
|
+
return await this.hostRequest(request, signal);
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
if (signal.aborted)
|
|
325
|
+
return { outcome: { outcome: "cancelled" } };
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
}),
|
|
329
|
+
openRequest: (signal, send) => this.agentRequest(agentId, announced, signal, send),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Whether the root's foreground work, through the subagents that it waits
|
|
334
|
+
* on (those it does not run in the background), waits on the user: each of
|
|
335
|
+
* them is blocked. Undefined when it waits on no subagent. A subagent is
|
|
336
|
+
* blocked when each subagent that it waits on is, or, waiting on none, when
|
|
337
|
+
* a request of it is open. So one that still makes progress keeps the work
|
|
338
|
+
* `running`, as v2 asks.
|
|
339
|
+
*/
|
|
340
|
+
foregroundBlocked() {
|
|
341
|
+
return this.subagentsBlocked(undefined, new Set());
|
|
342
|
+
}
|
|
343
|
+
subagentsBlocked(parent, seen) {
|
|
344
|
+
const waited = [...this.agents].flatMap(([agentId, task]) => !task.background && task.parentTaskId === parent && !seen.has(agentId) ? [agentId] : []);
|
|
345
|
+
if (waited.length === 0)
|
|
346
|
+
return undefined;
|
|
347
|
+
for (const agentId of waited)
|
|
348
|
+
seen.add(agentId);
|
|
349
|
+
return waited.every((agentId) => this.subagentsBlocked(agentId, seen) ?? (this.agentRequests.get(agentId)?.size ?? 0) > 0);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* The root's foreground work is cancelled: so is the work of the subagents
|
|
353
|
+
* that it waits on. Their open requests are withdrawn. Claude Code's
|
|
354
|
+
* interrupt stops their runs, which then end `cancelled`. Until then, of
|
|
355
|
+
* their consolidated messages only the results of the tool calls that the
|
|
356
|
+
* client holds go out, as on the root (see `SessionOutput.cancelled`). A foreground subagent that Claude Code
|
|
357
|
+
* reports after the cancel, until {@link foregroundCancelEnded}, is
|
|
358
|
+
* stopped work too: Claude Code started it before the interrupt, and the
|
|
359
|
+
* session reads its `task_started` only after the cancel.
|
|
360
|
+
*/
|
|
361
|
+
cancelForeground() {
|
|
362
|
+
this.foregroundCancelled.clear();
|
|
363
|
+
this.rootCancelling = true;
|
|
364
|
+
for (const agentId of this.agents.keys())
|
|
365
|
+
this.cancelIfForeground(agentId);
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* The work that the root's cancel stopped ended: its result, Claude Code's
|
|
369
|
+
* idle, or the start of a later prompt. A subagent that comes after it is
|
|
370
|
+
* the later work's.
|
|
371
|
+
*/
|
|
372
|
+
foregroundCancelEnded() {
|
|
373
|
+
this.rootCancelling = false;
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* The interrupt of the root's cancel failed: the subagents that it stopped
|
|
377
|
+
* go on. Their requests were withdrawn, and their later ones are theirs
|
|
378
|
+
* again, not a stopped run's.
|
|
379
|
+
*/
|
|
380
|
+
foregroundCancelFailed() {
|
|
381
|
+
this.rootCancelling = false;
|
|
382
|
+
this.cancelFailed(this.foregroundCancelled);
|
|
383
|
+
this.foregroundCancelled.clear();
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* A cancel failed to stop the agents `agentIds` that it withdrew: their
|
|
387
|
+
* runs go on, and their later requests are theirs again. Each reports
|
|
388
|
+
* `running` again, which the withdrawn requests did not.
|
|
389
|
+
*/
|
|
390
|
+
cancelFailed(agentIds) {
|
|
391
|
+
for (const agentId of agentIds) {
|
|
392
|
+
this.cancelledAgents.delete(agentId);
|
|
393
|
+
const child = this.children.get(agentId);
|
|
394
|
+
if (child?.output)
|
|
395
|
+
child.output.cancelled = false;
|
|
396
|
+
if (child)
|
|
397
|
+
this.reportChild(child);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* The root session closes: every subagent's open request is withdrawn, and
|
|
402
|
+
* a later one never reaches the client.
|
|
403
|
+
*/
|
|
404
|
+
withdrawAll() {
|
|
405
|
+
this.closed = true;
|
|
406
|
+
for (const agentId of this.agentRequests.keys())
|
|
407
|
+
this.withdraw(agentId);
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* `session/cancel` of a child: stops its run, and the work of the subagents
|
|
411
|
+
* that it waits on. Its idle reports `cancelled` once Claude Code reports
|
|
412
|
+
* the task stopped. A child that does not work has nothing to stop.
|
|
413
|
+
*/
|
|
414
|
+
async cancelChild(sessionId) {
|
|
415
|
+
const child = this.children.get(sessionId);
|
|
416
|
+
if (!child?.announced || !child.working)
|
|
417
|
+
return;
|
|
418
|
+
// The agents that this cancel stops, and not an earlier one still.
|
|
419
|
+
const withdrawn = [];
|
|
420
|
+
for (const agentId of this.agents.keys()) {
|
|
421
|
+
if (!this.waitsOn(agentId, sessionId))
|
|
422
|
+
continue;
|
|
423
|
+
if (!this.cancelledAgents.has(agentId))
|
|
424
|
+
withdrawn.push(agentId);
|
|
425
|
+
this.withdraw(agentId);
|
|
426
|
+
}
|
|
427
|
+
try {
|
|
428
|
+
await this.host.stopTask(child.sessionId);
|
|
429
|
+
}
|
|
430
|
+
catch (error) {
|
|
431
|
+
// The run ended meanwhile, or Claude Code refused: it reports how it
|
|
432
|
+
// ends, and so do the subagents that it waits on.
|
|
433
|
+
this.cancelFailed(withdrawn);
|
|
434
|
+
this.host.logger.error(`Subagent ${sessionId}: stopping it failed`, error);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Claude Code denied a tool use without asking: on the session of the agent
|
|
439
|
+
* `agent_id` names, where its tool call is.
|
|
440
|
+
*/
|
|
441
|
+
permissionDenied(message) {
|
|
442
|
+
const child = message.agent_id !== undefined ? this.children.get(message.agent_id) : undefined;
|
|
443
|
+
if (child?.announced)
|
|
444
|
+
child.output.permissionDenied(message, child.launchToolUseId);
|
|
445
|
+
else
|
|
446
|
+
this.rootOutput.permissionDenied(message);
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* A permission request on the session of `output` shows the tool call
|
|
450
|
+
* `toolCallId` to the client. A SendMessage call whose tool use has not
|
|
451
|
+
* streamed yet then stays shown: its updates go out, and its message goes
|
|
452
|
+
* to the child only. One that already streamed stays hidden.
|
|
453
|
+
*/
|
|
454
|
+
requestShows(output, toolName, toolCallId) {
|
|
455
|
+
if (toolName === "SendMessage" && !output.holds(toolCallId)) {
|
|
456
|
+
this.shownSendMessages.add(toolCallId);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* A hook of the subagent `input.agent_id`, as the v1 core reads them
|
|
461
|
+
* (`subagentConfigurationHook`): its `cwd` is the child's working
|
|
462
|
+
* directory, such as its worktree, and its configuration goes to the
|
|
463
|
+
* child's session (see `child-config.ts`). What a hook reports before the
|
|
464
|
+
* child's announcement goes with it.
|
|
465
|
+
*/
|
|
466
|
+
subagentHook(input) {
|
|
467
|
+
const agentId = input.agent_id;
|
|
468
|
+
if (agentId === undefined)
|
|
469
|
+
return;
|
|
470
|
+
const child = this.children.get(agentId);
|
|
471
|
+
if (child?.announced) {
|
|
472
|
+
if (path.isAbsolute(input.cwd))
|
|
473
|
+
this.reportCwd(child, input.cwd);
|
|
474
|
+
}
|
|
475
|
+
else if (this.startedHooks.has(agentId) || this.startedHooks.size < MAX_PENDING_HOOKS) {
|
|
476
|
+
const started = this.startedHooks.get(agentId) ?? {};
|
|
477
|
+
if (path.isAbsolute(input.cwd))
|
|
478
|
+
started.cwd = input.cwd;
|
|
479
|
+
if (input.agent_type)
|
|
480
|
+
started.agentType = input.agent_type;
|
|
481
|
+
this.startedHooks.set(agentId, started);
|
|
482
|
+
}
|
|
483
|
+
if (this.configs.take(agentId, this.configs.hookOptions(input)) && child?.announced) {
|
|
484
|
+
this.publishConfiguration(child, undefined);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
// --- Background work ----------------------------------------------------------
|
|
488
|
+
/**
|
|
489
|
+
* Stops the listed terminal or tool call of `sessionId` (`terminal/cancel`
|
|
490
|
+
* and `tool_call/cancel`). It ends when Claude Code reports its task
|
|
491
|
+
* stopped. Returns false when the session does not list it, also when it
|
|
492
|
+
* ended while Claude Code tried to stop it.
|
|
493
|
+
*/
|
|
494
|
+
async cancelItem(sessionId, target) {
|
|
495
|
+
const taskId = this.listedTask(sessionId, target);
|
|
496
|
+
if (taskId === undefined)
|
|
497
|
+
return false;
|
|
498
|
+
try {
|
|
499
|
+
await this.host.stopTask(taskId);
|
|
500
|
+
}
|
|
501
|
+
catch (error) {
|
|
502
|
+
if (this.listedTask(sessionId, target) === undefined)
|
|
503
|
+
return false;
|
|
504
|
+
throw error;
|
|
505
|
+
}
|
|
506
|
+
return true;
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* The current state of the session's work, for a resume of the active
|
|
510
|
+
* session: each subagent that a session lists, or that works in its
|
|
511
|
+
* foreground, with its labels and state (also on its own stream), and the
|
|
512
|
+
* current update of each item that a session lists. Every item comes
|
|
513
|
+
* before the state that lists it, and a child's announcement before any
|
|
514
|
+
* update of its session, so a child whose list names items is announced
|
|
515
|
+
* first and gets its state after them.
|
|
516
|
+
*/
|
|
517
|
+
currentState() {
|
|
518
|
+
const updates = [];
|
|
519
|
+
const lists = this.lists();
|
|
520
|
+
const visit = (sessionId) => {
|
|
521
|
+
const listed = lists.get(sessionId) ?? [];
|
|
522
|
+
const children = this.parentsFirst().filter((child) => child.parentSessionId === sessionId &&
|
|
523
|
+
(child.working ||
|
|
524
|
+
listed.some((item) => item.type === "subagent" && item.sessionId === child.sessionId)));
|
|
525
|
+
for (const child of children) {
|
|
526
|
+
const state = stateObject(this.childState(child), undefined);
|
|
527
|
+
if ((lists.get(child.sessionId) ?? []).length === 0) {
|
|
528
|
+
updates.push(this.host.background.stamp({
|
|
529
|
+
sessionId: child.parentSessionId,
|
|
530
|
+
update: { ...this.announcement(child), state },
|
|
531
|
+
}));
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
updates.push({ sessionId: child.parentSessionId, update: this.announcement(child) });
|
|
535
|
+
visit(child.sessionId);
|
|
536
|
+
updates.push(this.host.background.stamp({
|
|
537
|
+
sessionId: child.parentSessionId,
|
|
538
|
+
update: { sessionUpdate: "subagent_update", sessionId: child.sessionId, state },
|
|
539
|
+
}));
|
|
540
|
+
}
|
|
541
|
+
updates.push(this.host.background.stamp({
|
|
542
|
+
sessionId: child.sessionId,
|
|
543
|
+
update: { sessionUpdate: "state_update", ...state },
|
|
544
|
+
}));
|
|
545
|
+
}
|
|
546
|
+
for (const item of listed) {
|
|
547
|
+
if (item.type !== "tool_call")
|
|
548
|
+
continue;
|
|
549
|
+
const listed = [...this.toolCalls].find(([, t]) => t.toolCallId === item.toolCallId);
|
|
550
|
+
if (!listed)
|
|
551
|
+
continue;
|
|
552
|
+
const [taskId, toolCall] = listed;
|
|
553
|
+
const update = toolCall.toolUse
|
|
554
|
+
? V2_RENDERER.toolCall({ id: toolCall.toolCallId, ...toolCall.toolUse }, { cwd: this.cwdOf(sessionId) })
|
|
555
|
+
: taskToolCall(toolCall.toolCallId, toolCall.title);
|
|
556
|
+
const status = toolCall.paused ? "paused" : "in_progress";
|
|
557
|
+
for (const v2Update of this.host.translator.updates(sessionId, {
|
|
558
|
+
...update,
|
|
559
|
+
...workflowCard(this.level.get(taskId)?.progress),
|
|
560
|
+
status,
|
|
561
|
+
})) {
|
|
562
|
+
updates.push({ sessionId, update: v2Update });
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
updates.push(...this.host.background.currentItems(sessionId));
|
|
566
|
+
};
|
|
567
|
+
visit(this.host.sessionId);
|
|
568
|
+
return updates;
|
|
569
|
+
}
|
|
570
|
+
/** The tool calls of `sessionId` whose tasks go on in the background: a cancel leaves them. */
|
|
571
|
+
backgroundCalls(sessionId) {
|
|
572
|
+
return new Set([...this.toolCalls.values()]
|
|
573
|
+
.filter((toolCall) => toolCall.output.sessionId === sessionId)
|
|
574
|
+
.map((toolCall) => toolCall.toolCallId));
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Claude Code's query ended: its tasks ended with its process. Terminals
|
|
578
|
+
* exit and background tool calls are cancelled; a child that worked ends
|
|
579
|
+
* `error`, as the root's work does.
|
|
580
|
+
*/
|
|
581
|
+
queryEnded(error) {
|
|
582
|
+
for (const [taskId, terminal] of this.terminals) {
|
|
583
|
+
terminal.tail?.stop();
|
|
584
|
+
if (error)
|
|
585
|
+
this.exitTerminal(taskId);
|
|
586
|
+
}
|
|
587
|
+
if (!error)
|
|
588
|
+
return;
|
|
589
|
+
for (const [taskId] of this.toolCalls)
|
|
590
|
+
this.endToolCall(taskId, "stopped");
|
|
591
|
+
for (const child of this.children.values()) {
|
|
592
|
+
if (child.announced && child.working)
|
|
593
|
+
this.endRun(child, { stopReason: "error", error });
|
|
594
|
+
}
|
|
595
|
+
this.level = new Map();
|
|
596
|
+
this.publish();
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Claude Code mounted a fresh conversation (`conversation_reset`). Its
|
|
600
|
+
* subagents end, deeper ones first, as on v1 (`finishAll`): each
|
|
601
|
+
* child that works goes `idle` with no stop reason, since nothing says how
|
|
602
|
+
* its run ended, after its unfinished tool calls end `failed`. Then every
|
|
603
|
+
* child is forgotten: a later event of one
|
|
604
|
+
* changes nothing, and a child not announced yet stays unexposed. Claude
|
|
605
|
+
* Code's tasks (the live subagents, background commands and other tasks)
|
|
606
|
+
* stay as its task events report them.
|
|
607
|
+
*/
|
|
608
|
+
conversationReset() {
|
|
609
|
+
for (const child of [...this.parentsFirst()].reverse()) {
|
|
610
|
+
if (child.working)
|
|
611
|
+
this.endRun(child, undefined);
|
|
612
|
+
}
|
|
613
|
+
this.publish();
|
|
614
|
+
for (const child of this.children.values())
|
|
615
|
+
this.configs.forget(child.sessionId);
|
|
616
|
+
this.children.clear();
|
|
617
|
+
this.childByToolUse.clear();
|
|
618
|
+
this.launches.clear();
|
|
619
|
+
this.pendingByLaunch.clear();
|
|
620
|
+
this.cancelledAgents.clear();
|
|
621
|
+
this.foregroundCancelled.clear();
|
|
622
|
+
this.senderByToolUse.clear();
|
|
623
|
+
this.startedHooks.clear();
|
|
624
|
+
this.hiddenSendMessages.clear();
|
|
625
|
+
this.shownSendMessages.clear();
|
|
626
|
+
this.handbacks.clear();
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Publishes the `background` list of each session that changed, deeper
|
|
630
|
+
* sessions first, so a child's own list is current before its parent's
|
|
631
|
+
* list names or drops it.
|
|
632
|
+
*/
|
|
633
|
+
publish() {
|
|
634
|
+
if (!this.host.reportsBackground)
|
|
635
|
+
return;
|
|
636
|
+
// A task that needs a tool call of its own gets it first, so the list can name it.
|
|
637
|
+
this.adoptTasks();
|
|
638
|
+
const lists = this.lists();
|
|
639
|
+
for (const child of [...this.parentsFirst()].reverse()) {
|
|
640
|
+
this.sendAll(this.host.background.changed({
|
|
641
|
+
sessionId: child.sessionId,
|
|
642
|
+
items: lists.get(child.sessionId) ?? [],
|
|
643
|
+
state: this.childState(child),
|
|
644
|
+
parentSessionId: child.parentSessionId,
|
|
645
|
+
}));
|
|
646
|
+
}
|
|
647
|
+
this.sendAll(this.host.background.changed({
|
|
648
|
+
sessionId: this.host.sessionId,
|
|
649
|
+
items: lists.get(this.host.sessionId) ?? [],
|
|
650
|
+
state: this.host.rootState(),
|
|
651
|
+
}));
|
|
652
|
+
}
|
|
653
|
+
// --- Task events ----------------------------------------------------------------
|
|
654
|
+
taskStarted(message) {
|
|
655
|
+
const isAgent = message.task_type === "local_agent" || message.subagent_type !== undefined;
|
|
656
|
+
if (!isAgent) {
|
|
657
|
+
this.started.set(message.task_id, {
|
|
658
|
+
...(message.tool_use_id !== undefined ? { toolUseId: message.tool_use_id } : {}),
|
|
659
|
+
...(message.parent_task_id !== undefined ? { parentTaskId: message.parent_task_id } : {}),
|
|
660
|
+
...(message.task_type !== undefined ? { taskType: message.task_type } : {}),
|
|
661
|
+
});
|
|
662
|
+
this.publish();
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
// A subagent that Claude Code does not run in the background blocks the
|
|
666
|
+
// work that waits on it, also before it is announced.
|
|
667
|
+
this.agents.set(message.task_id, {
|
|
668
|
+
parentTaskId: message.parent_task_id,
|
|
669
|
+
background: message.is_backgrounded === true,
|
|
670
|
+
});
|
|
671
|
+
const toolUseId = message.tool_use_id ?? undefined;
|
|
672
|
+
const prompt = nonBlank(message.prompt);
|
|
673
|
+
let child = this.children.get(message.task_id);
|
|
674
|
+
if (child) {
|
|
675
|
+
// A resume: the same child, again, under the call that resumed it.
|
|
676
|
+
if (toolUseId !== undefined) {
|
|
677
|
+
this.childByToolUse.set(toolUseId, child);
|
|
678
|
+
child.launchToolUseId = toolUseId;
|
|
679
|
+
}
|
|
680
|
+
this.startRun(child, prompt, toolUseId);
|
|
681
|
+
}
|
|
682
|
+
else if (toolUseId !== undefined && this.senderByToolUse.has(toolUseId)) {
|
|
683
|
+
// A SendMessage call resumed an agent that this process does not know,
|
|
684
|
+
// such as one from before a restart.
|
|
685
|
+
this.restoring = this.restore(message.task_id, prompt, toolUseId);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
else {
|
|
689
|
+
// A child's parent is the subagent that launched it. One Claude Code
|
|
690
|
+
// no longer tracks, such as one from before a restart, cannot be
|
|
691
|
+
// placed: the child stays unexposed, its traffic the root's.
|
|
692
|
+
if (message.parent_task_id !== undefined && !this.children.has(message.parent_task_id)) {
|
|
693
|
+
this.cancelIfForeground(message.task_id);
|
|
694
|
+
this.host.foregroundRequestsChanged();
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
child = this.newChild(message.task_id, toolUseId, {
|
|
698
|
+
...(nonBlank(message.description) ? { description: message.description } : {}),
|
|
699
|
+
...(prompt ? { prompt } : {}),
|
|
700
|
+
...(nonBlank(message.subagent_type) ? { subagentType: message.subagent_type } : {}),
|
|
701
|
+
});
|
|
702
|
+
if (toolUseId !== undefined) {
|
|
703
|
+
this.pendingByLaunch.delete(toolUseId);
|
|
704
|
+
this.childByToolUse.set(toolUseId, child);
|
|
705
|
+
// The launch call names the parent. Without one, it is the parent task.
|
|
706
|
+
const launch = this.launches.get(toolUseId);
|
|
707
|
+
if (launch)
|
|
708
|
+
this.announce(child, launch.output.sessionId);
|
|
709
|
+
}
|
|
710
|
+
else {
|
|
711
|
+
// No session update may carry a session id before its announcement.
|
|
712
|
+
const parent = message.parent_task_id ?? this.host.sessionId;
|
|
713
|
+
if (parent === this.host.sessionId || this.children.get(parent)?.announced) {
|
|
714
|
+
this.announce(child, parent);
|
|
715
|
+
}
|
|
716
|
+
else {
|
|
717
|
+
child.awaitedParent = parent;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
// After `startRun`, which clears the stop of the resumed child's last run.
|
|
722
|
+
this.cancelIfForeground(message.task_id);
|
|
723
|
+
this.host.foregroundRequestsChanged();
|
|
724
|
+
this.publish();
|
|
725
|
+
}
|
|
726
|
+
taskUpdated(message) {
|
|
727
|
+
const { task_id: taskId, patch } = message;
|
|
728
|
+
const child = this.children.get(taskId);
|
|
729
|
+
const agent = this.agents.get(taskId);
|
|
730
|
+
if (patch.is_backgrounded !== undefined && agent) {
|
|
731
|
+
agent.background = patch.is_backgrounded;
|
|
732
|
+
this.host.foregroundRequestsChanged();
|
|
733
|
+
this.publish();
|
|
734
|
+
}
|
|
735
|
+
switch (patch.status) {
|
|
736
|
+
case "completed":
|
|
737
|
+
case "failed":
|
|
738
|
+
this.taskEnded(taskId, patch.status, patch.error);
|
|
739
|
+
return;
|
|
740
|
+
case "killed":
|
|
741
|
+
this.taskEnded(taskId, "stopped");
|
|
742
|
+
return;
|
|
743
|
+
case "paused":
|
|
744
|
+
case "running":
|
|
745
|
+
case "pending": {
|
|
746
|
+
const paused = patch.status === "paused";
|
|
747
|
+
const toolCall = this.toolCalls.get(taskId);
|
|
748
|
+
if (toolCall && toolCall.paused !== paused) {
|
|
749
|
+
toolCall.paused = paused;
|
|
750
|
+
toolCall.output.toolCallStatus(toolCall.toolCallId, paused ? "paused" : "in_progress");
|
|
751
|
+
}
|
|
752
|
+
// Claude Code can resume a subagent that ended without a new `task_started`.
|
|
753
|
+
if (patch.status === "running" && child && !child.working) {
|
|
754
|
+
this.agents.set(taskId, { parentTaskId: agent?.parentTaskId, background: true });
|
|
755
|
+
this.startRun(child, undefined, undefined);
|
|
756
|
+
}
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
default:
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
taskNotification(message) {
|
|
764
|
+
const child = this.children.get(message.task_id);
|
|
765
|
+
// The end of an earlier delegation to a resumed child ends nothing: the
|
|
766
|
+
// child and its task belong to the new run.
|
|
767
|
+
const toolUseId = message.tool_use_id ?? undefined;
|
|
768
|
+
if (child &&
|
|
769
|
+
toolUseId !== undefined &&
|
|
770
|
+
toolUseId !== child.launchToolUseId &&
|
|
771
|
+
this.childByToolUse.get(toolUseId) === child) {
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
this.taskEnded(message.task_id, message.status);
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* A task's progress report. A workflow's goes on its tool call, as its
|
|
778
|
+
* title and body (`workflowCard`), without changing its status. A report
|
|
779
|
+
* that comes before the call returns waits for the result (see
|
|
780
|
+
* {@link toolResults}), and a report without `workflow_progress` keeps the
|
|
781
|
+
* last phase and agent list. A report that changes nothing on the card
|
|
782
|
+
* sends nothing.
|
|
783
|
+
*/
|
|
784
|
+
taskProgress(message) {
|
|
785
|
+
const task = this.level.get(message.task_id);
|
|
786
|
+
if (!task || task.taskType !== "local_workflow")
|
|
787
|
+
return;
|
|
788
|
+
// The SDK does not type `workflow_progress`; see workflow-progress.ts.
|
|
789
|
+
const workflow = workflowSnapshot(message.workflow_progress);
|
|
790
|
+
const previous = workflowCard(task.progress);
|
|
791
|
+
task.progress = {
|
|
792
|
+
...task.progress,
|
|
793
|
+
...taskProgressFields(message),
|
|
794
|
+
...(workflow ? { workflow } : {}),
|
|
795
|
+
};
|
|
796
|
+
const card = workflowCard(task.progress);
|
|
797
|
+
if (!card || JSON.stringify(previous) === JSON.stringify(card))
|
|
798
|
+
return;
|
|
799
|
+
const toolCall = this.toolCalls.get(message.task_id);
|
|
800
|
+
toolCall?.output.taskToolCallProgress(toolCall.toolCallId, card);
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* The task `taskId` ended. Claude Code can report one end twice (a
|
|
804
|
+
* terminal `task_updated` and a `task_notification`), so a second is a
|
|
805
|
+
* no-op, unless it gives the error text of a failure that the first lacked.
|
|
806
|
+
*/
|
|
807
|
+
taskEnded(taskId, status, error) {
|
|
808
|
+
const child = this.children.get(taskId);
|
|
809
|
+
if (this.agents.delete(taskId))
|
|
810
|
+
this.host.foregroundRequestsChanged();
|
|
811
|
+
if (child && !child.announced) {
|
|
812
|
+
this.withdrawChild(child);
|
|
813
|
+
}
|
|
814
|
+
else if (child) {
|
|
815
|
+
this.endRun(child, status === "completed"
|
|
816
|
+
? { stopReason: "end_turn" }
|
|
817
|
+
: status === "stopped"
|
|
818
|
+
? { stopReason: "cancelled" }
|
|
819
|
+
: {
|
|
820
|
+
stopReason: "error",
|
|
821
|
+
...(error
|
|
822
|
+
? { error: { code: RequestError.internalError().code, message: error } }
|
|
823
|
+
: {}),
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
this.started.delete(taskId);
|
|
827
|
+
const terminal = this.terminals.get(taskId);
|
|
828
|
+
if (terminal && !terminal.ending) {
|
|
829
|
+
terminal.ending = true;
|
|
830
|
+
// The rest of the output goes out before the exit, and the list drops
|
|
831
|
+
// the terminal only after its exit.
|
|
832
|
+
void (terminal.tail?.finish() ?? Promise.resolve()).then(() => {
|
|
833
|
+
this.exitTerminal(taskId);
|
|
834
|
+
this.publish();
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
if (this.toolCalls.has(taskId))
|
|
838
|
+
this.endToolCall(taskId, status);
|
|
839
|
+
this.publish();
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Claude Code's live background task set changed. Terminals and tool calls
|
|
843
|
+
* whose tasks it no longer holds ended, without saying how.
|
|
844
|
+
*/
|
|
845
|
+
levelChanged(tasks) {
|
|
846
|
+
this.level = new Map(tasks.map((task) => [
|
|
847
|
+
task.task_id,
|
|
848
|
+
{
|
|
849
|
+
ambient: task.ambient === true,
|
|
850
|
+
taskType: task.task_type,
|
|
851
|
+
description: task.description,
|
|
852
|
+
...(task.parent_task_id !== undefined ? { parentTaskId: task.parent_task_id } : {}),
|
|
853
|
+
progress: this.level.get(task.task_id)?.progress,
|
|
854
|
+
},
|
|
855
|
+
]));
|
|
856
|
+
for (const [taskId, terminal] of this.terminals) {
|
|
857
|
+
if (this.level.get(taskId)?.ambient === false)
|
|
858
|
+
terminal.leveled = true;
|
|
859
|
+
}
|
|
860
|
+
for (const taskId of [...this.terminals.keys(), ...this.toolCalls.keys()]) {
|
|
861
|
+
if (!this.level.has(taskId))
|
|
862
|
+
this.taskEnded(taskId, "completed");
|
|
863
|
+
}
|
|
864
|
+
this.publish();
|
|
865
|
+
}
|
|
866
|
+
// --- Children ---------------------------------------------------------------------
|
|
867
|
+
/** A new child, not announced, which runs; the messages of its launch that came wait for it. */
|
|
868
|
+
newChild(sessionId, launchToolUseId, task) {
|
|
869
|
+
const child = {
|
|
870
|
+
sessionId,
|
|
871
|
+
parentSessionId: this.host.sessionId,
|
|
872
|
+
launchToolUseId,
|
|
873
|
+
task,
|
|
874
|
+
announced: false,
|
|
875
|
+
awaitedParent: undefined,
|
|
876
|
+
pending: launchToolUseId !== undefined ? (this.pendingByLaunch.get(launchToolUseId) ?? []) : [],
|
|
877
|
+
title: undefined,
|
|
878
|
+
description: undefined,
|
|
879
|
+
working: true,
|
|
880
|
+
reportedState: undefined,
|
|
881
|
+
outcome: undefined,
|
|
882
|
+
openRequests: 0,
|
|
883
|
+
cwd: undefined,
|
|
884
|
+
output: undefined,
|
|
885
|
+
promptIds: new Set(),
|
|
886
|
+
stopped: new Set(),
|
|
887
|
+
endedRuns: new Set(),
|
|
888
|
+
handedBack: new Set(),
|
|
889
|
+
};
|
|
890
|
+
this.children.set(sessionId, child);
|
|
891
|
+
return child;
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Restores the agent `agentId`, which the SendMessage call `toolUseId`
|
|
895
|
+
* resumed with `prompt`, as the v1 core does (`NativeSubagentRuntime.restore`):
|
|
896
|
+
* the process does not know it, because it ran before the session was
|
|
897
|
+
* resumed. The session's subagent history (`subagentLineage`) gives the
|
|
898
|
+
* call that launched it and its ancestors. Claude Code sends the resumed
|
|
899
|
+
* run's messages under that launch call's id. Before the agent's traffic,
|
|
900
|
+
* the RFD requires its ancestors, parent before child, so each one that is
|
|
901
|
+
* not announced is, with no state, since nothing says that it runs. Then
|
|
902
|
+
* the agent, running, and the SendMessage call's message to it. The RFD
|
|
903
|
+
* forbids guessing a parent, so an agent that the history cannot place
|
|
904
|
+
* stays unexposed, its traffic the root's.
|
|
905
|
+
*/
|
|
906
|
+
async restore(agentId, prompt, toolUseId) {
|
|
907
|
+
const lineage = await subagentLineage(this.host.sessionId, agentId, this.host.logger).catch((error) => {
|
|
908
|
+
this.host.logger.error(`Subagent ${agentId}: reading its history failed`, error);
|
|
909
|
+
return [];
|
|
910
|
+
});
|
|
911
|
+
// The session handles no message while the history is read (see `restored`).
|
|
912
|
+
if (this.closed || this.children.has(agentId) || lineage.at(-1)?.agentId !== agentId) {
|
|
913
|
+
this.host.foregroundRequestsChanged();
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
for (const entry of lineage) {
|
|
917
|
+
if (this.children.get(entry.agentId)?.announced)
|
|
918
|
+
continue;
|
|
919
|
+
const child = this.newChild(entry.agentId, entry.launchId, {
|
|
920
|
+
...(entry.name ? { name: entry.name } : {}),
|
|
921
|
+
...(entry.description ? { description: entry.description } : {}),
|
|
922
|
+
...(entry.agentType ? { subagentType: entry.agentType } : {}),
|
|
923
|
+
});
|
|
924
|
+
this.childByToolUse.set(entry.launchId, child);
|
|
925
|
+
// A hook of the resumed agent may have reported a newer `cwd`.
|
|
926
|
+
if (entry.cwd && this.startedHooks.get(entry.agentId)?.cwd === undefined) {
|
|
927
|
+
this.startedHooks.set(entry.agentId, {
|
|
928
|
+
...this.startedHooks.get(entry.agentId),
|
|
929
|
+
cwd: entry.cwd,
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
const parent = entry.parentAgentId ?? this.host.sessionId;
|
|
933
|
+
if (entry.agentId === agentId) {
|
|
934
|
+
this.announce(child, parent);
|
|
935
|
+
}
|
|
936
|
+
else {
|
|
937
|
+
child.working = false;
|
|
938
|
+
this.open(child, parent);
|
|
939
|
+
this.host.send({ sessionId: parent, update: this.announcement(child, false) });
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
const child = this.children.get(agentId);
|
|
943
|
+
this.childByToolUse.set(toolUseId, child);
|
|
944
|
+
child.launchToolUseId = toolUseId;
|
|
945
|
+
this.startRun(child, prompt, toolUseId);
|
|
946
|
+
this.host.foregroundRequestsChanged();
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* A message of a subagent, by its `parent_tool_use_id`: it goes to the
|
|
950
|
+
* child's stream, or waits for the child's announcement. A message of an
|
|
951
|
+
* agent that no known call launched is the root's.
|
|
952
|
+
*/
|
|
953
|
+
childMessage(message) {
|
|
954
|
+
const launchId = message.parent_tool_use_id;
|
|
955
|
+
if (launchId === null)
|
|
956
|
+
return false;
|
|
957
|
+
const child = this.childByToolUse.get(launchId);
|
|
958
|
+
if (child?.announced) {
|
|
959
|
+
this.deliver(child, message);
|
|
960
|
+
return true;
|
|
961
|
+
}
|
|
962
|
+
if (!child && !this.launches.has(launchId))
|
|
963
|
+
return false;
|
|
964
|
+
const pending = child?.pending ?? this.pendingByLaunch.get(launchId) ?? [];
|
|
965
|
+
if (!child)
|
|
966
|
+
this.pendingByLaunch.set(launchId, pending);
|
|
967
|
+
if (pending.length < MAX_PENDING_MESSAGES)
|
|
968
|
+
pending.push(message);
|
|
969
|
+
else
|
|
970
|
+
this.host.logger.error(`Subagent of ${launchId}: dropping a message before its start`);
|
|
971
|
+
return true;
|
|
972
|
+
}
|
|
973
|
+
/** Sends a message of the announced `child` to its stream. */
|
|
974
|
+
deliver(child, message) {
|
|
975
|
+
const output = child.output;
|
|
976
|
+
switch (message.type) {
|
|
977
|
+
case "stream_event":
|
|
978
|
+
if (message.event.type === "message_start") {
|
|
979
|
+
this.reportModel(child, message.event.message.model);
|
|
980
|
+
}
|
|
981
|
+
output.streamEvent(message);
|
|
982
|
+
return;
|
|
983
|
+
case "assistant":
|
|
984
|
+
this.reportModel(child, message.message.model);
|
|
985
|
+
output.assistant(message);
|
|
986
|
+
return;
|
|
987
|
+
case "tool_progress":
|
|
988
|
+
output.toolProgress(message);
|
|
989
|
+
return;
|
|
990
|
+
case "user": {
|
|
991
|
+
// Its prompts are the delegations, which go out as session messages.
|
|
992
|
+
// Its other text is Claude Code's, such as "[Request interrupted by
|
|
993
|
+
// user]", which the child's session does not show.
|
|
994
|
+
const content = message.message.content;
|
|
995
|
+
if (Array.isArray(content) && content.some((block) => block.type === "tool_result")) {
|
|
996
|
+
// The session handles its next message after the restore (see `restored`).
|
|
997
|
+
const restoring = this.restoreResumed(output, message);
|
|
998
|
+
if (restoring)
|
|
999
|
+
this.restoring = restoring.then(() => this.toolResults(output, message));
|
|
1000
|
+
else
|
|
1001
|
+
this.toolResults(output, message);
|
|
1002
|
+
}
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
default:
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Announces `child` on `parentSessionId`, running, with its parent's
|
|
1011
|
+
* labels for it, then sends its prompt as the parent's message to it, and
|
|
1012
|
+
* the messages that came before.
|
|
1013
|
+
*/
|
|
1014
|
+
announce(child, parentSessionId) {
|
|
1015
|
+
const identity = this.open(child, parentSessionId);
|
|
1016
|
+
child.reportedState = "running";
|
|
1017
|
+
const state = stateObject("running", undefined);
|
|
1018
|
+
this.host.send({ sessionId: parentSessionId, update: { ...this.announcement(child), state } });
|
|
1019
|
+
this.host.send({
|
|
1020
|
+
sessionId: child.sessionId,
|
|
1021
|
+
update: { sessionUpdate: "state_update", ...state },
|
|
1022
|
+
});
|
|
1023
|
+
const prompt = child.task.prompt ?? identity?.prompt;
|
|
1024
|
+
if (prompt)
|
|
1025
|
+
this.sendPrompt(child, prompt, child.launchToolUseId, parentSessionId, true);
|
|
1026
|
+
// What its hooks reported before, after the prompt.
|
|
1027
|
+
this.publishConfiguration(child, undefined);
|
|
1028
|
+
const pending = child.pending;
|
|
1029
|
+
child.pending = [];
|
|
1030
|
+
for (const message of pending)
|
|
1031
|
+
this.deliver(child, message);
|
|
1032
|
+
for (const waiting of [...this.children.values()]) {
|
|
1033
|
+
if (!waiting.announced && waiting.awaitedParent === child.sessionId) {
|
|
1034
|
+
waiting.awaitedParent = undefined;
|
|
1035
|
+
this.announce(waiting, child.sessionId);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Makes `child` a session of `parentSessionId`, with its parent's labels
|
|
1041
|
+
* for it, its `cwd` and its output. Returns the identity of its launch.
|
|
1042
|
+
*/
|
|
1043
|
+
open(child, parentSessionId) {
|
|
1044
|
+
const launch = child.launchToolUseId !== undefined ? this.launches.get(child.launchToolUseId) : undefined;
|
|
1045
|
+
const identity = launch?.identity;
|
|
1046
|
+
const hook = this.startedHooks.get(child.sessionId);
|
|
1047
|
+
this.startedHooks.delete(child.sessionId);
|
|
1048
|
+
const labels = rfdLabels(identity?.name ?? child.task.name, identity?.subagentType ?? child.task.subagentType ?? hook?.agentType, identity?.description ?? child.task.description);
|
|
1049
|
+
child.parentSessionId = parentSessionId;
|
|
1050
|
+
child.title = labels.title;
|
|
1051
|
+
child.description = labels.description;
|
|
1052
|
+
const parentCwd = this.cwdOf(parentSessionId);
|
|
1053
|
+
child.cwd = hook?.cwd && !sameDirectory(hook.cwd, parentCwd) ? hook.cwd : undefined;
|
|
1054
|
+
const output = new SessionOutput(child.sessionId, child.cwd ?? parentCwd, this.host.translator, (update) => this.host.send({ sessionId: child.sessionId, update }), this.host.logger, true);
|
|
1055
|
+
output.route = (notification) => this.route(output, notification, child);
|
|
1056
|
+
child.output = output;
|
|
1057
|
+
child.announced = true;
|
|
1058
|
+
// Before the messages that waited for the announcement go out.
|
|
1059
|
+
this.cancelIfForeground(child.sessionId);
|
|
1060
|
+
return identity;
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* A message delegated to `child`, with the id of the call that sent it. A
|
|
1064
|
+
* launch's prompt replaces its call (`linked`): it goes out as the
|
|
1065
|
+
* sender's outgoing message and the child's incoming one.
|
|
1066
|
+
*/
|
|
1067
|
+
sendPrompt(child, text, toolUseId, sender, linked) {
|
|
1068
|
+
const messageId = toolUseId ?? `${child.sessionId}:prompt:${child.promptIds.size + 1}`;
|
|
1069
|
+
if (child.promptIds.has(messageId))
|
|
1070
|
+
return;
|
|
1071
|
+
child.promptIds.add(messageId);
|
|
1072
|
+
if (linked && toolUseId !== undefined && sender !== undefined) {
|
|
1073
|
+
const [outgoing, incoming] = linkedSessionMessages(toolUseId, sender, child.sessionId, text);
|
|
1074
|
+
this.outputOf(sender)?.emitV1([outgoing]);
|
|
1075
|
+
child.output.emitV1([incoming]);
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
child.output.emitV1([
|
|
1079
|
+
{
|
|
1080
|
+
sessionId: child.sessionId,
|
|
1081
|
+
update: {
|
|
1082
|
+
sessionUpdate: "session_message",
|
|
1083
|
+
messageId,
|
|
1084
|
+
...(sender !== undefined ? { senderSessionId: sender } : {}),
|
|
1085
|
+
recipientSessionId: child.sessionId,
|
|
1086
|
+
content: [{ type: "text", text }],
|
|
1087
|
+
},
|
|
1088
|
+
},
|
|
1089
|
+
]);
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Rewrites an update of `output`, the output of the root or of `child`: an
|
|
1093
|
+
* update of an Agent or Task call goes out as {@link launchUpdate} says,
|
|
1094
|
+
* and Claude Code's late result of a call that the child's stop ended
|
|
1095
|
+
* goes nowhere.
|
|
1096
|
+
*/
|
|
1097
|
+
route(output, notification, child) {
|
|
1098
|
+
const { update } = notification;
|
|
1099
|
+
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
|
|
1100
|
+
return [notification];
|
|
1101
|
+
}
|
|
1102
|
+
if (child?.stopped.has(update.toolCallId))
|
|
1103
|
+
return [];
|
|
1104
|
+
const toolName = update._meta?.claudeCode?.toolName;
|
|
1105
|
+
if (toolName === "SendMessage")
|
|
1106
|
+
this.senderByToolUse.set(update.toolCallId, output.sessionId);
|
|
1107
|
+
const message = this.sendMessageUpdate(output, notification, toolName) ??
|
|
1108
|
+
(child ? this.handbackUpdate(child, notification, toolName) : undefined);
|
|
1109
|
+
if (message)
|
|
1110
|
+
return message;
|
|
1111
|
+
let launch = this.launches.get(update.toolCallId);
|
|
1112
|
+
if (!launch) {
|
|
1113
|
+
if (!isNativeSubagentControlTool(toolName))
|
|
1114
|
+
return [notification];
|
|
1115
|
+
launch = {
|
|
1116
|
+
toolUseId: update.toolCallId,
|
|
1117
|
+
output,
|
|
1118
|
+
identity: undefined,
|
|
1119
|
+
background: false,
|
|
1120
|
+
initial: undefined,
|
|
1121
|
+
ended: false,
|
|
1122
|
+
};
|
|
1123
|
+
this.launches.set(launch.toolUseId, launch);
|
|
1124
|
+
}
|
|
1125
|
+
return this.launchUpdate(launch, notification);
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* An update of an Agent or Task call. Its child, if it started, is
|
|
1129
|
+
* announced at the call's first update. The call goes out only once it
|
|
1130
|
+
* ends without an announced child, except a background launch that
|
|
1131
|
+
* completed: its child starts after it. A foreground child's answer, the
|
|
1132
|
+
* completed result, is its reply to the parent.
|
|
1133
|
+
*/
|
|
1134
|
+
launchUpdate(launch, notification) {
|
|
1135
|
+
const update = notification.update;
|
|
1136
|
+
if (update.sessionUpdate === "tool_call")
|
|
1137
|
+
launch.initial ??= notification;
|
|
1138
|
+
const identity = subagentIdentity(update.rawInput);
|
|
1139
|
+
if (identity)
|
|
1140
|
+
launch.identity = mergeSubagentIdentity(launch.identity, identity);
|
|
1141
|
+
if (update.rawInput?.run_in_background === true) {
|
|
1142
|
+
launch.background = true;
|
|
1143
|
+
}
|
|
1144
|
+
const child = this.childByToolUse.get(launch.toolUseId);
|
|
1145
|
+
if (child && !child.announced)
|
|
1146
|
+
this.announce(child, launch.output.sessionId);
|
|
1147
|
+
if (!FINAL_STATUSES.has(update.status) || launch.ended)
|
|
1148
|
+
return [];
|
|
1149
|
+
launch.ended = true;
|
|
1150
|
+
if (child?.announced) {
|
|
1151
|
+
// A run that handed back its report has none in its result.
|
|
1152
|
+
if (update.status !== "completed" ||
|
|
1153
|
+
launch.background ||
|
|
1154
|
+
child.handedBack.has(launch.toolUseId)) {
|
|
1155
|
+
return [];
|
|
1156
|
+
}
|
|
1157
|
+
const reply = launchReply(launch.toolUseId, child.sessionId, child.parentSessionId, update);
|
|
1158
|
+
return reply ? [reply] : [];
|
|
1159
|
+
}
|
|
1160
|
+
// No child came, or it ended unexposed: its messages are dropped with it.
|
|
1161
|
+
this.pendingByLaunch.delete(launch.toolUseId);
|
|
1162
|
+
if (launch.background && update.status === "completed")
|
|
1163
|
+
return [];
|
|
1164
|
+
return [unexposedControlFallback(launch.initial, notification, launch.output.sessionId)];
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* An update of a SendMessage call, which its message replaces once it
|
|
1168
|
+
* reaches an announced child (see {@link startRun}): the sender's outgoing
|
|
1169
|
+
* view and the child's incoming one. Claude Code reports that delivery
|
|
1170
|
+
* before the call's final update. A call whose message reached no announced
|
|
1171
|
+
* child, such as one to the parent, is shown after all, with its final
|
|
1172
|
+
* status. Undefined for any other update.
|
|
1173
|
+
*/
|
|
1174
|
+
sendMessageUpdate(output, notification, toolName) {
|
|
1175
|
+
const update = notification.update;
|
|
1176
|
+
// A call that its permission request showed (see `requestShows`).
|
|
1177
|
+
if (this.shownSendMessages.has(update.toolCallId)) {
|
|
1178
|
+
if (FINAL_STATUSES.has(update.status))
|
|
1179
|
+
this.shownSendMessages.delete(update.toolCallId);
|
|
1180
|
+
return [notification];
|
|
1181
|
+
}
|
|
1182
|
+
let call = this.hiddenSendMessages.get(update.toolCallId);
|
|
1183
|
+
if (!call) {
|
|
1184
|
+
if (update.sessionUpdate !== "tool_call" || toolName !== "SendMessage")
|
|
1185
|
+
return undefined;
|
|
1186
|
+
call = { initial: notification, sender: output.sessionId, delivered: false };
|
|
1187
|
+
this.hiddenSendMessages.set(update.toolCallId, call);
|
|
1188
|
+
}
|
|
1189
|
+
if (!FINAL_STATUSES.has(update.status))
|
|
1190
|
+
return [];
|
|
1191
|
+
this.hiddenSendMessages.delete(update.toolCallId);
|
|
1192
|
+
if (call.delivered)
|
|
1193
|
+
return [];
|
|
1194
|
+
return [unexposedControlFallback(call.initial, notification, call.sender)];
|
|
1195
|
+
}
|
|
1196
|
+
/**
|
|
1197
|
+
* An update of a SubagentHandback call of the announced `child`, which its
|
|
1198
|
+
* report replaces: the child's message to its parent, the outgoing view on
|
|
1199
|
+
* the child and the incoming one on the parent. Its run's result is then no
|
|
1200
|
+
* reply. A call that failed delivered nothing, so the child is shown the
|
|
1201
|
+
* call after all. Undefined for any other update.
|
|
1202
|
+
*/
|
|
1203
|
+
handbackUpdate(child, notification, toolName) {
|
|
1204
|
+
const update = notification.update;
|
|
1205
|
+
let handback = this.handbacks.get(update.toolCallId);
|
|
1206
|
+
if (!handback) {
|
|
1207
|
+
if (toolName !== HANDBACK_TOOL)
|
|
1208
|
+
return undefined;
|
|
1209
|
+
const parentToolUseId = update._meta?.claudeCode?.parentToolUseId;
|
|
1210
|
+
const delegationId = parentToolUseId ?? child.launchToolUseId;
|
|
1211
|
+
handback = {
|
|
1212
|
+
initial: notification,
|
|
1213
|
+
...(delegationId !== undefined ? { delegationId } : {}),
|
|
1214
|
+
};
|
|
1215
|
+
this.handbacks.set(update.toolCallId, handback);
|
|
1216
|
+
}
|
|
1217
|
+
handback.message = handbackMessage(update.rawInput) ?? handback.message;
|
|
1218
|
+
if (!FINAL_STATUSES.has(update.status))
|
|
1219
|
+
return [];
|
|
1220
|
+
this.handbacks.delete(update.toolCallId);
|
|
1221
|
+
if (update.status !== "completed" || !handback.message) {
|
|
1222
|
+
return [unexposedControlFallback(handback.initial, notification, child.sessionId)];
|
|
1223
|
+
}
|
|
1224
|
+
if (handback.delegationId !== undefined)
|
|
1225
|
+
child.handedBack.add(handback.delegationId);
|
|
1226
|
+
const [outgoing, incoming] = linkedSessionMessages(update.toolCallId, child.sessionId, child.parentSessionId, handback.message);
|
|
1227
|
+
// Sent here, in order: an output routes each update once the ones before it went out.
|
|
1228
|
+
child.output.emitV1([outgoing]);
|
|
1229
|
+
this.outputOf(child.parentSessionId)?.emitV1([incoming]);
|
|
1230
|
+
return [];
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* A SendMessage result that reports the agent it resumed (`resumedAgentId`):
|
|
1234
|
+
* the call is the child's delegation, which it takes unless the run of that
|
|
1235
|
+
* call ended already, as on v1 (`sendMessageResumed`). Claude Code
|
|
1236
|
+
* can resume a child without a new `task_started`.
|
|
1237
|
+
*/
|
|
1238
|
+
sendMessageResumed(message, results, toolUses) {
|
|
1239
|
+
const agentId = resumedNativeSubagentId(message.tool_use_result);
|
|
1240
|
+
const child = agentId !== undefined ? this.children.get(agentId) : undefined;
|
|
1241
|
+
if (!child?.announced)
|
|
1242
|
+
return;
|
|
1243
|
+
const resume = sendMessageResume(toolUses, child.sessionId, results.map((block) => block.tool_use_id));
|
|
1244
|
+
if (resume && child.endedRuns.has(resume.toolUseId))
|
|
1245
|
+
return;
|
|
1246
|
+
if (!this.agents.has(child.sessionId)) {
|
|
1247
|
+
this.agents.set(child.sessionId, { parentTaskId: undefined, background: true });
|
|
1248
|
+
}
|
|
1249
|
+
if (resume) {
|
|
1250
|
+
this.childByToolUse.set(resume.toolUseId, child);
|
|
1251
|
+
child.launchToolUseId = resume.toolUseId;
|
|
1252
|
+
}
|
|
1253
|
+
this.startRun(child, resume?.text, resume?.toolUseId);
|
|
1254
|
+
}
|
|
1255
|
+
/** A child that ended before its announcement stays unexposed, and is forgotten. */
|
|
1256
|
+
withdrawChild(child) {
|
|
1257
|
+
this.children.delete(child.sessionId);
|
|
1258
|
+
this.configs.forget(child.sessionId);
|
|
1259
|
+
this.startedHooks.delete(child.sessionId);
|
|
1260
|
+
for (const [toolUseId, owner] of this.childByToolUse) {
|
|
1261
|
+
if (owner === child)
|
|
1262
|
+
this.childByToolUse.delete(toolUseId);
|
|
1263
|
+
}
|
|
1264
|
+
this.cancelledAgents.delete(child.sessionId);
|
|
1265
|
+
}
|
|
1266
|
+
/** A new run of the announced `child`, with the prompt that the call `toolUseId` sent it. */
|
|
1267
|
+
startRun(child, prompt, toolUseId) {
|
|
1268
|
+
if (!child.announced)
|
|
1269
|
+
return;
|
|
1270
|
+
if (!child.working) {
|
|
1271
|
+
child.working = true;
|
|
1272
|
+
child.outcome = undefined;
|
|
1273
|
+
this.cancelledAgents.delete(child.sessionId);
|
|
1274
|
+
this.reportChild(child);
|
|
1275
|
+
}
|
|
1276
|
+
if (prompt && toolUseId !== undefined) {
|
|
1277
|
+
// The message of a SendMessage call that the client is not shown replaces it.
|
|
1278
|
+
const call = this.hiddenSendMessages.get(toolUseId);
|
|
1279
|
+
this.sendPrompt(child, prompt, toolUseId, call?.sender ?? this.senderByToolUse.get(toolUseId), call !== undefined);
|
|
1280
|
+
if (call)
|
|
1281
|
+
call.delivered = true;
|
|
1282
|
+
}
|
|
1283
|
+
this.publish();
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* A run of `child` ended: its unfinished tool calls get their final status,
|
|
1287
|
+
* except its background work, then its idle goes out, as v2 asks. A stopped
|
|
1288
|
+
* run's end `cancelled`, and a failed run's or an unexplained end's
|
|
1289
|
+
* (`undefined`, an idle with no stop reason) `failed`. At a completed end, a
|
|
1290
|
+
* tool call that Claude dropped before it ran ends `cancelled`, as on the
|
|
1291
|
+
* root (see `SessionOutput.closeUnfinished`).
|
|
1292
|
+
*/
|
|
1293
|
+
endRun(child, outcome) {
|
|
1294
|
+
if (!child.working) {
|
|
1295
|
+
// A later report of the same failure can give its error text.
|
|
1296
|
+
if (outcome?.stopReason === "error" &&
|
|
1297
|
+
outcome.error &&
|
|
1298
|
+
child.outcome?.stopReason === "error" &&
|
|
1299
|
+
!child.outcome.error) {
|
|
1300
|
+
child.outcome = outcome;
|
|
1301
|
+
this.sendChildState(child, "idle");
|
|
1302
|
+
}
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
const keep = this.backgroundWork(child.sessionId);
|
|
1306
|
+
if (outcome?.stopReason === "end_turn") {
|
|
1307
|
+
child.output.closeUnfinished(false, keep);
|
|
1308
|
+
}
|
|
1309
|
+
else {
|
|
1310
|
+
const status = outcome?.stopReason === "cancelled" ? "cancelled" : "failed";
|
|
1311
|
+
const ended = child.output.finishUnfinished(status, keep, { exitTerminals: true });
|
|
1312
|
+
for (const toolCallId of ended)
|
|
1313
|
+
child.stopped.add(toolCallId);
|
|
1314
|
+
}
|
|
1315
|
+
child.working = false;
|
|
1316
|
+
child.outcome = outcome;
|
|
1317
|
+
child.output.cancelled = false;
|
|
1318
|
+
if (child.launchToolUseId !== undefined)
|
|
1319
|
+
child.endedRuns.add(child.launchToolUseId);
|
|
1320
|
+
this.reportChild(child);
|
|
1321
|
+
this.cancelledAgents.delete(child.sessionId);
|
|
1322
|
+
}
|
|
1323
|
+
/** The tool calls and terminals of `sessionId` that go on in the background. */
|
|
1324
|
+
backgroundWork(sessionId) {
|
|
1325
|
+
const work = this.backgroundCalls(sessionId);
|
|
1326
|
+
for (const terminal of this.terminals.values()) {
|
|
1327
|
+
if (terminal.output.sessionId === sessionId)
|
|
1328
|
+
work.add(terminal.toolCallId);
|
|
1329
|
+
}
|
|
1330
|
+
return work;
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Rewrites a replayed update of `sessionId`'s background work as the live
|
|
1334
|
+
* tool result was (see `toolResult`): a running command's result keeps its
|
|
1335
|
+
* terminal running, and a running task's tool call stays `in_progress`.
|
|
1336
|
+
*/
|
|
1337
|
+
replayedBackground(sessionId) {
|
|
1338
|
+
const terminals = [...this.terminals.values()]
|
|
1339
|
+
.filter((terminal) => terminal.output.sessionId === sessionId)
|
|
1340
|
+
.map((terminal) => terminal.toolCallId);
|
|
1341
|
+
const toolCalls = this.backgroundCalls(sessionId);
|
|
1342
|
+
return (notification) => withRunningToolCall(terminals.reduce(withRunningTerminal, notification), toolCalls);
|
|
1343
|
+
}
|
|
1344
|
+
childState(child) {
|
|
1345
|
+
if (!child.working)
|
|
1346
|
+
return "idle";
|
|
1347
|
+
return child.openRequests > 0 ? "requires_action" : "running";
|
|
1348
|
+
}
|
|
1349
|
+
/** Sends the child's state on its stream and in its parent's mirror, when it changed. */
|
|
1350
|
+
reportChild(child) {
|
|
1351
|
+
if (!child.announced)
|
|
1352
|
+
return;
|
|
1353
|
+
const state = this.childState(child);
|
|
1354
|
+
if (state === child.reportedState)
|
|
1355
|
+
return;
|
|
1356
|
+
// A cancel withdrew the open requests: the run is stopping, and its idle follows.
|
|
1357
|
+
if (child.reportedState === "requires_action" &&
|
|
1358
|
+
state === "running" &&
|
|
1359
|
+
this.cancelledAgents.has(child.sessionId)) {
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
this.sendChildState(child, state);
|
|
1363
|
+
}
|
|
1364
|
+
sendChildState(child, state) {
|
|
1365
|
+
child.reportedState = state;
|
|
1366
|
+
const snapshot = stateObject(state, state === "idle" ? child.outcome : undefined);
|
|
1367
|
+
this.host.send({
|
|
1368
|
+
sessionId: child.parentSessionId,
|
|
1369
|
+
update: { sessionUpdate: "subagent_update", sessionId: child.sessionId, state: snapshot },
|
|
1370
|
+
});
|
|
1371
|
+
this.host.send({
|
|
1372
|
+
sessionId: child.sessionId,
|
|
1373
|
+
update: { sessionUpdate: "state_update", ...snapshot },
|
|
1374
|
+
});
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* Runs `send` as an open request of the agent `agentId` (see
|
|
1378
|
+
* {@link RequestTarget.openRequest}). While it is open, `announced`, the
|
|
1379
|
+
* child session it goes to, is `requires_action`, and the work that waits
|
|
1380
|
+
* on the agent is too. After the root closed, or while a cancel stops the
|
|
1381
|
+
* agent's run, `send` runs with an aborted signal and the request does not
|
|
1382
|
+
* count as open.
|
|
1383
|
+
*/
|
|
1384
|
+
async agentRequest(agentId, announced, toolSignal, send) {
|
|
1385
|
+
if (this.closed || this.cancelledAgents.has(agentId))
|
|
1386
|
+
return send(AbortSignal.abort());
|
|
1387
|
+
const abort = new AbortController();
|
|
1388
|
+
const signal = AbortSignal.any([toolSignal, abort.signal]);
|
|
1389
|
+
const requests = this.agentRequests.get(agentId) ?? new Set();
|
|
1390
|
+
this.agentRequests.set(agentId, requests);
|
|
1391
|
+
requests.add(abort);
|
|
1392
|
+
if (announced) {
|
|
1393
|
+
announced.openRequests++;
|
|
1394
|
+
this.reportChild(announced);
|
|
1395
|
+
}
|
|
1396
|
+
this.host.foregroundRequestsChanged();
|
|
1397
|
+
try {
|
|
1398
|
+
return await send(signal);
|
|
1399
|
+
}
|
|
1400
|
+
finally {
|
|
1401
|
+
requests.delete(abort);
|
|
1402
|
+
if (requests.size === 0)
|
|
1403
|
+
this.agentRequests.delete(agentId);
|
|
1404
|
+
this.host.foregroundRequestsChanged();
|
|
1405
|
+
if (announced) {
|
|
1406
|
+
announced.openRequests--;
|
|
1407
|
+
this.reportChild(announced);
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
/** Set by the session: sends a permission request to the client. */
|
|
1412
|
+
hostRequest;
|
|
1413
|
+
/**
|
|
1414
|
+
* While the root's cancel is in effect, the agent `agentId`, when the root
|
|
1415
|
+
* waits on it, is stopped with the root's work (see {@link cancelForeground}).
|
|
1416
|
+
*/
|
|
1417
|
+
cancelIfForeground(agentId) {
|
|
1418
|
+
if (!this.rootCancelling || !this.waitsOn(agentId, undefined))
|
|
1419
|
+
return;
|
|
1420
|
+
this.withdraw(agentId);
|
|
1421
|
+
this.foregroundCancelled.add(agentId);
|
|
1422
|
+
const output = this.children.get(agentId)?.output;
|
|
1423
|
+
if (output)
|
|
1424
|
+
output.cancelled = true;
|
|
1425
|
+
}
|
|
1426
|
+
/** Withdraws the open requests of the agent `agentId`, whose run a cancel stops. */
|
|
1427
|
+
withdraw(agentId) {
|
|
1428
|
+
this.cancelledAgents.add(agentId);
|
|
1429
|
+
for (const abort of this.agentRequests.get(agentId) ?? [])
|
|
1430
|
+
abort.abort();
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Whether the work of `sessionId` (the root when undefined) waits on the
|
|
1434
|
+
* agent `agentId`: the agent is that session's, or each agent from it up to
|
|
1435
|
+
* that session runs in the foreground of its parent.
|
|
1436
|
+
*/
|
|
1437
|
+
waitsOn(agentId, sessionId) {
|
|
1438
|
+
const seen = new Set();
|
|
1439
|
+
for (let id = agentId; id !== undefined && !seen.has(id);) {
|
|
1440
|
+
if (id === sessionId)
|
|
1441
|
+
return true;
|
|
1442
|
+
seen.add(id);
|
|
1443
|
+
const task = this.agents.get(id);
|
|
1444
|
+
if (!task || task.background)
|
|
1445
|
+
return false;
|
|
1446
|
+
id = task.parentTaskId;
|
|
1447
|
+
}
|
|
1448
|
+
return sessionId === undefined;
|
|
1449
|
+
}
|
|
1450
|
+
/**
|
|
1451
|
+
* Reports the model of a child response as the entry of the root's `model`
|
|
1452
|
+
* option that matches it, else as the id, in the child's configuration.
|
|
1453
|
+
* The child gets no model before its first response, and the client gets
|
|
1454
|
+
* its configuration again only when it changes.
|
|
1455
|
+
*/
|
|
1456
|
+
reportModel(child, model) {
|
|
1457
|
+
const entry = responseModelEntry(model, this.host.models());
|
|
1458
|
+
if (!entry || !this.configs.take(child.sessionId, [childModelOption(entry)]))
|
|
1459
|
+
return;
|
|
1460
|
+
this.publishConfiguration(child, child.launchToolUseId !== undefined
|
|
1461
|
+
? { claudeCode: { parentToolUseId: child.launchToolUseId } }
|
|
1462
|
+
: undefined);
|
|
1463
|
+
}
|
|
1464
|
+
/** Sends the configuration of the announced `child`, when the client does not hold it. */
|
|
1465
|
+
publishConfiguration(child, meta) {
|
|
1466
|
+
const configOptions = this.configs.unsent(child.sessionId);
|
|
1467
|
+
if (!configOptions)
|
|
1468
|
+
return;
|
|
1469
|
+
child.output.emitV1([
|
|
1470
|
+
{
|
|
1471
|
+
sessionId: child.sessionId,
|
|
1472
|
+
update: {
|
|
1473
|
+
sessionUpdate: "config_option_update",
|
|
1474
|
+
configOptions,
|
|
1475
|
+
...(meta ? { _meta: meta } : {}),
|
|
1476
|
+
},
|
|
1477
|
+
},
|
|
1478
|
+
]);
|
|
1479
|
+
}
|
|
1480
|
+
reportCwd(child, cwd) {
|
|
1481
|
+
const parentCwd = this.cwdOf(child.parentSessionId);
|
|
1482
|
+
const next = sameDirectory(cwd, parentCwd) ? undefined : cwd;
|
|
1483
|
+
if (next === child.cwd)
|
|
1484
|
+
return;
|
|
1485
|
+
child.cwd = next;
|
|
1486
|
+
this.host.send({
|
|
1487
|
+
sessionId: child.parentSessionId,
|
|
1488
|
+
update: { sessionUpdate: "subagent_update", sessionId: child.sessionId, cwd: next ?? null },
|
|
1489
|
+
});
|
|
1490
|
+
}
|
|
1491
|
+
/** The working directory of the root or of an announced child. */
|
|
1492
|
+
cwdOf(sessionId) {
|
|
1493
|
+
const child = this.children.get(sessionId);
|
|
1494
|
+
if (!child?.announced)
|
|
1495
|
+
return this.host.cwd;
|
|
1496
|
+
return child.cwd ?? this.cwdOf(child.parentSessionId);
|
|
1497
|
+
}
|
|
1498
|
+
outputOf(sessionId) {
|
|
1499
|
+
if (sessionId === this.host.sessionId)
|
|
1500
|
+
return this.rootOutput;
|
|
1501
|
+
return this.children.get(sessionId)?.output;
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* The announcement of `child`, with its `cancel` capability unless
|
|
1505
|
+
* `cancellable` is false: a restored ancestor, which nothing says runs.
|
|
1506
|
+
*/
|
|
1507
|
+
announcement(child, cancellable = true) {
|
|
1508
|
+
return {
|
|
1509
|
+
sessionUpdate: "subagent_update",
|
|
1510
|
+
sessionId: child.sessionId,
|
|
1511
|
+
...(child.title !== undefined ? { title: child.title } : {}),
|
|
1512
|
+
...(child.description !== undefined ? { description: child.description } : {}),
|
|
1513
|
+
...(child.cwd !== undefined ? { cwd: child.cwd } : {}),
|
|
1514
|
+
// `session/cancel` of the child stops its run (`stopTask`).
|
|
1515
|
+
...(cancellable ? { capabilities: { cancel: {} } } : {}),
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
/** The announced children, each after its parent. */
|
|
1519
|
+
parentsFirst() {
|
|
1520
|
+
const ordered = [];
|
|
1521
|
+
const visit = (sessionId) => {
|
|
1522
|
+
for (const child of this.children.values()) {
|
|
1523
|
+
if (!child.announced || child.parentSessionId !== sessionId)
|
|
1524
|
+
continue;
|
|
1525
|
+
ordered.push(child);
|
|
1526
|
+
visit(child.sessionId);
|
|
1527
|
+
}
|
|
1528
|
+
};
|
|
1529
|
+
visit(this.host.sessionId);
|
|
1530
|
+
return ordered;
|
|
1531
|
+
}
|
|
1532
|
+
// --- Lists ------------------------------------------------------------------------
|
|
1533
|
+
/**
|
|
1534
|
+
* The `background` list of each session, from Claude Code's live background
|
|
1535
|
+
* tasks: its background terminals, tool calls and other tasks, and its
|
|
1536
|
+
* children that work in the background or have background work of their
|
|
1537
|
+
* own. Claude Code marks its housekeeping `ambient`, which is left out,
|
|
1538
|
+
* except a task that a tool call started. A task that a tool call started
|
|
1539
|
+
* is part of that call until the call returns, and is not listed.
|
|
1540
|
+
*/
|
|
1541
|
+
lists() {
|
|
1542
|
+
const lists = new Map([[this.host.sessionId, []]]);
|
|
1543
|
+
const children = this.parentsFirst();
|
|
1544
|
+
for (const child of children)
|
|
1545
|
+
lists.set(child.sessionId, []);
|
|
1546
|
+
for (const [taskId, task] of this.level) {
|
|
1547
|
+
const toolCall = this.toolCalls.get(taskId);
|
|
1548
|
+
if (toolCall) {
|
|
1549
|
+
lists
|
|
1550
|
+
.get(toolCall.output.sessionId)
|
|
1551
|
+
?.push({ type: "tool_call", toolCallId: toolCall.toolCallId });
|
|
1552
|
+
continue;
|
|
1553
|
+
}
|
|
1554
|
+
if (task.ambient)
|
|
1555
|
+
continue;
|
|
1556
|
+
const terminal = this.terminals.get(taskId);
|
|
1557
|
+
if (terminal) {
|
|
1558
|
+
lists
|
|
1559
|
+
.get(terminal.output.sessionId)
|
|
1560
|
+
?.push({ type: "terminal", terminalId: terminal.toolCallId });
|
|
1561
|
+
continue;
|
|
1562
|
+
}
|
|
1563
|
+
// Any other task is listed by the tool call that `adoptTasks` starts
|
|
1564
|
+
// for it, or is not background work. A subagent is listed below, as
|
|
1565
|
+
// its session.
|
|
1566
|
+
}
|
|
1567
|
+
// A terminal whose task left the level is listed until its exit, which
|
|
1568
|
+
// waits for the rest of its output.
|
|
1569
|
+
for (const [taskId, terminal] of this.terminals) {
|
|
1570
|
+
if (terminal.ending && terminal.leveled && !this.level.has(taskId)) {
|
|
1571
|
+
lists
|
|
1572
|
+
.get(terminal.output.sessionId)
|
|
1573
|
+
?.push({ type: "terminal", terminalId: terminal.toolCallId });
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
// Deeper children first: a child's own list is whole before its parent's reads it.
|
|
1577
|
+
for (const child of [...children].reverse()) {
|
|
1578
|
+
const task = this.level.get(child.sessionId);
|
|
1579
|
+
const inBackground = child.working && task !== undefined && !task.ambient;
|
|
1580
|
+
if (inBackground || (lists.get(child.sessionId)?.length ?? 0) > 0) {
|
|
1581
|
+
lists.get(child.parentSessionId)?.push({ type: "subagent", sessionId: child.sessionId });
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
return lists;
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* Starts a tool call for each live task that no terminal or tool call
|
|
1588
|
+
* stands for yet: v2 lists background work only by an entity the client
|
|
1589
|
+
* knows. Such a task is one that no tool call started, such as one a hook
|
|
1590
|
+
* started, or one whose tool call returned, with its final status, before
|
|
1591
|
+
* the task started. The call (`task_<taskId>`) has the task's description
|
|
1592
|
+
* as its title, is `in_progress`, and ends with the task. A task of an
|
|
1593
|
+
* announced subagent gets its call on the subagent's session. Ambient
|
|
1594
|
+
* tasks are housekeeping and get no call. {@link publish} calls it before
|
|
1595
|
+
* each list it publishes, so the call comes before the first list that
|
|
1596
|
+
* names it, as v2 requires.
|
|
1597
|
+
*/
|
|
1598
|
+
adoptTasks() {
|
|
1599
|
+
for (const [taskId, task] of this.level) {
|
|
1600
|
+
if (task.ambient || this.toolCalls.has(taskId) || this.terminals.has(taskId))
|
|
1601
|
+
continue;
|
|
1602
|
+
// A command without a terminal yet is one that foreground work waits on.
|
|
1603
|
+
// A subagent is listed as its session.
|
|
1604
|
+
if (task.taskType === "local_bash" || task.taskType === "local_agent")
|
|
1605
|
+
continue;
|
|
1606
|
+
// A task joins the level before its `task_started`, and before the tool
|
|
1607
|
+
// call that starts it returns. Until both, the task is unknown or part
|
|
1608
|
+
// of that tool call.
|
|
1609
|
+
const started = this.started.get(taskId);
|
|
1610
|
+
if (!started || (started.toolUseId && !this.returned.has(started.toolUseId)))
|
|
1611
|
+
continue;
|
|
1612
|
+
const parent = task.parentTaskId ? this.children.get(task.parentTaskId) : undefined;
|
|
1613
|
+
const output = (parent?.announced ? parent.output : undefined) ?? this.rootOutput;
|
|
1614
|
+
const toolCallId = `task_${taskId}`;
|
|
1615
|
+
this.toolCalls.set(taskId, { toolCallId, output, title: task.description, paused: false });
|
|
1616
|
+
output.taskToolCall(taskToolCall(toolCallId, task.description));
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
/** The task of the terminal or tool call `target` that `sessionId` lists. */
|
|
1620
|
+
listedTask(sessionId, target) {
|
|
1621
|
+
if (!this.host.reportsBackground)
|
|
1622
|
+
return undefined;
|
|
1623
|
+
const listed = this.lists().get(sessionId) ?? [];
|
|
1624
|
+
return "terminalId" in target
|
|
1625
|
+
? listed.some((item) => item.type === "terminal" && item.terminalId === target.terminalId)
|
|
1626
|
+
? [...this.terminals].find(([, t]) => t.toolCallId === target.terminalId)?.[0]
|
|
1627
|
+
: undefined
|
|
1628
|
+
: listed.some((item) => item.type === "tool_call" && item.toolCallId === target.toolCallId)
|
|
1629
|
+
? [...this.toolCalls].find(([, t]) => t.toolCallId === target.toolCallId)?.[0]
|
|
1630
|
+
: undefined;
|
|
1631
|
+
}
|
|
1632
|
+
followOutput(taskId, outputFilePath) {
|
|
1633
|
+
const terminal = this.terminals.get(taskId);
|
|
1634
|
+
if (!terminal || !outputFilePath || !this.host.reportsBackground)
|
|
1635
|
+
return;
|
|
1636
|
+
terminal.tail = new BackgroundOutputTail(outputFilePath, async (output) => terminal.output.emitV1([
|
|
1637
|
+
terminalOutput(terminal.output.sessionId, terminal.toolCallId, output),
|
|
1638
|
+
]));
|
|
1639
|
+
}
|
|
1640
|
+
exitTerminal(taskId) {
|
|
1641
|
+
const terminal = this.terminals.get(taskId);
|
|
1642
|
+
if (!terminal)
|
|
1643
|
+
return;
|
|
1644
|
+
this.terminals.delete(taskId);
|
|
1645
|
+
terminal.output.emitV1([
|
|
1646
|
+
{
|
|
1647
|
+
sessionId: terminal.output.sessionId,
|
|
1648
|
+
update: {
|
|
1649
|
+
sessionUpdate: "tool_call_update",
|
|
1650
|
+
toolCallId: terminal.toolCallId,
|
|
1651
|
+
_meta: {
|
|
1652
|
+
terminal_exit: { terminal_id: terminal.toolCallId, exit_code: null, signal: null },
|
|
1653
|
+
},
|
|
1654
|
+
},
|
|
1655
|
+
},
|
|
1656
|
+
]);
|
|
1657
|
+
}
|
|
1658
|
+
endToolCall(taskId, status) {
|
|
1659
|
+
const toolCall = this.toolCalls.get(taskId);
|
|
1660
|
+
if (!toolCall)
|
|
1661
|
+
return;
|
|
1662
|
+
this.toolCalls.delete(taskId);
|
|
1663
|
+
toolCall.output.toolCallStatus(toolCall.toolCallId, status === "stopped" ? "cancelled" : status);
|
|
1664
|
+
}
|
|
1665
|
+
sendAll(notifications) {
|
|
1666
|
+
for (const notification of notifications)
|
|
1667
|
+
this.host.send(notification);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
/**
|
|
1671
|
+
* The `tool_call` that the adapter starts for a task (see
|
|
1672
|
+
* `SessionTasks.adoptTasks`). Claude Code's tool use ids start with `toolu_`,
|
|
1673
|
+
* so `task_<taskId>` names no other call.
|
|
1674
|
+
*/
|
|
1675
|
+
function taskToolCall(toolCallId, title) {
|
|
1676
|
+
return {
|
|
1677
|
+
sessionUpdate: "tool_call",
|
|
1678
|
+
toolCallId,
|
|
1679
|
+
title: title || "Background task",
|
|
1680
|
+
kind: "other",
|
|
1681
|
+
status: "in_progress",
|
|
1682
|
+
};
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* Whether two paths name one directory, also through a symlink: a hook's
|
|
1686
|
+
* `cwd` is the real path, such as `/private/tmp/project` for `/tmp/project`.
|
|
1687
|
+
*/
|
|
1688
|
+
export function sameDirectory(left, right) {
|
|
1689
|
+
const real = (directory) => {
|
|
1690
|
+
try {
|
|
1691
|
+
return fs.realpathSync.native(directory);
|
|
1692
|
+
}
|
|
1693
|
+
catch {
|
|
1694
|
+
return path.resolve(directory);
|
|
1695
|
+
}
|
|
1696
|
+
};
|
|
1697
|
+
return path.resolve(left) === path.resolve(right) || real(left) === real(right);
|
|
1698
|
+
}
|
|
1699
|
+
/** A child's state as a `StateUpdate`: an idle with how its last run ended. */
|
|
1700
|
+
function stateObject(state, outcome) {
|
|
1701
|
+
switch (state) {
|
|
1702
|
+
case "running":
|
|
1703
|
+
return { state: "running" };
|
|
1704
|
+
case "requires_action":
|
|
1705
|
+
return { state: "requires_action" };
|
|
1706
|
+
default:
|
|
1707
|
+
return { state: "idle", ...(outcome ?? {}) };
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
function nonBlank(value) {
|
|
1711
|
+
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
|
|
1712
|
+
}
|
|
1713
|
+
/** The v1 update that gives a background command's terminal its output. */
|
|
1714
|
+
function terminalOutput(sessionId, terminalId, output) {
|
|
1715
|
+
const data = { terminal_id: terminalId, data: output.text };
|
|
1716
|
+
return {
|
|
1717
|
+
sessionId,
|
|
1718
|
+
update: {
|
|
1719
|
+
sessionUpdate: "tool_call_update",
|
|
1720
|
+
toolCallId: terminalId,
|
|
1721
|
+
_meta: output.replaces ? { terminal_output: data } : { terminal_output_delta: data },
|
|
1722
|
+
},
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
/** The error of a request on a child session: the client can only watch a child. */
|
|
1726
|
+
export function restrictedChild(sessionId, method) {
|
|
1727
|
+
return RequestError.invalidParams({ sessionId }, `${sessionId} is a subagent session: the client cannot ${method} it. Its parent session runs it.`);
|
|
1728
|
+
}
|