@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/session.js
CHANGED
|
@@ -1,152 +1,1234 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* `ClaudeAcpAgent`: v2 requests become the v1 requests that the agent serves,
|
|
4
|
-
* and its v1 responses become v2 responses.
|
|
5
|
-
*/
|
|
6
|
-
import { RequestError, } from "@agentclientprotocol/sdk/unstable";
|
|
7
|
-
import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
|
|
8
|
-
import { V2_SESSION_CAPABILITIES } from "./initialize.js";
|
|
9
|
-
import { v1ContentBlock } from "./prompt.js";
|
|
10
|
-
export function v1NewSessionRequest(params) {
|
|
11
|
-
const { mcpServers, systemPrompt, ...request } = params;
|
|
12
|
-
// v1 requires the list; v2 treats an omitted list as an empty one.
|
|
13
|
-
return {
|
|
14
|
-
...request,
|
|
15
|
-
mcpServers: v1McpServers(mcpServers) ?? [],
|
|
16
|
-
...v1SystemPromptField(systemPrompt),
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* The v1 request that a v2 `session/resume` means.
|
|
2
|
+
* One ACP v2 session, served straight from its Claude Code query.
|
|
21
3
|
*
|
|
22
|
-
* v2
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
4
|
+
* ACP v2 and Claude Code describe a session the same way: prompts go into a
|
|
5
|
+
* queue, Claude Code works through them, and the session reports whether it
|
|
6
|
+
* is working. So this session keeps little of its own:
|
|
7
|
+
*
|
|
8
|
+
* - A prompt is pushed to Claude Code at once, with a uuid. Its response is
|
|
9
|
+
* the prompt's insertion: the `command_lifecycle` frame `started` for that
|
|
10
|
+
* uuid, or the prompt's echo, whichever comes first. `cancelled`,
|
|
11
|
+
* `discarded` or `refused` fails the prompt.
|
|
12
|
+
* - The foreground work is Claude Code's turn: it starts with a prompt's
|
|
13
|
+
* `started` frame or echo, or with the main conversation's output (a
|
|
14
|
+
* cycle that Claude Code starts on its own, such as after a background
|
|
15
|
+
* task ends), and ends with the turn's `result`, whose stop reason, usage
|
|
16
|
+
* and quota the idle carries (see `outcome.ts`). Claude Code's own
|
|
17
|
+
* `session_state_changed` stays `running` while background subagents work,
|
|
18
|
+
* which v2 lists as background work instead (`background`), so its `idle`
|
|
19
|
+
* only ends a turn that ended without a result.
|
|
20
|
+
* - `requires_action` is this session's own: a turn is open, and a
|
|
21
|
+
* permission request or elicitation of this session is open, or, while
|
|
22
|
+
* the turn waits on subagents, each of them waits on one.
|
|
23
|
+
* - Subagents are child sessions, and background work is listed on every
|
|
24
|
+
* state (see {@link SessionTasks}).
|
|
25
|
+
* - `session/cancel` answers the prompts that are not inserted yet with
|
|
26
|
+
* -32800, and sends Claude Code's interrupt with `cancelQueued`, which ends
|
|
27
|
+
* them in Claude Code too. A run of one that Claude Code had taken in
|
|
28
|
+
* already is dropped (see {@link StoppedWork}). With
|
|
29
|
+
* `perTaskStopAffordance`, the interrupt spares background tasks.
|
|
30
|
+
*
|
|
31
|
+
* Output goes out as it comes, whatever prompt it belongs to (see
|
|
32
|
+
* {@link SessionOutput}).
|
|
27
33
|
*/
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
34
|
+
import { randomUUID } from "node:crypto";
|
|
35
|
+
import { RequestError, } from "@agentclientprotocol/sdk/unstable";
|
|
36
|
+
import { AUTONOMOUS_RESULT_ORIGINS, promptToClaude } from "../acp-agent.js";
|
|
37
|
+
import { v1PromptRequest } from "./prompt.js";
|
|
38
|
+
import { V2Background, stateUpdate as currentStateUpdate } from "./background.js";
|
|
39
|
+
import { MODEL_CONFIG_ID } from "../session-model.js";
|
|
40
|
+
import { modelRefusalFallback, noticeUpdate } from "../session-notices.js";
|
|
41
|
+
import { planModeUpdate } from "../exit-plan.js";
|
|
42
|
+
import { resetPlanUpdates } from "../plans.js";
|
|
43
|
+
import { agentFileChangeReportMeta } from "../file-change-audit.js";
|
|
44
|
+
import { ClearContext } from "./clear-context.js";
|
|
45
|
+
import { TurnFileChanges } from "./file-changes.js";
|
|
46
|
+
import { SessionCommands } from "./commands.js";
|
|
47
|
+
import { idleOutcome, isPlaceholderResult, ResultUsage, TurnReport, } from "./outcome.js";
|
|
48
|
+
import { StoppedWork } from "./stopped-work.js";
|
|
49
|
+
import { SessionReports } from "./reports.js";
|
|
50
|
+
import { SessionElicitations } from "./elicitation.js";
|
|
51
|
+
import { SessionOutput } from "./stream.js";
|
|
52
|
+
import { SessionRemoteControl } from "./remote-control.js";
|
|
53
|
+
import { SessionTasks } from "./tasks.js";
|
|
54
|
+
export class V2Session {
|
|
55
|
+
sessionId;
|
|
56
|
+
cwd;
|
|
57
|
+
additionalDirectories;
|
|
58
|
+
connection;
|
|
59
|
+
input;
|
|
60
|
+
/** The prompts not inserted yet, by uuid. */
|
|
61
|
+
pending = new Map();
|
|
62
|
+
/** Whether a turn of Claude Code is open: the session's foreground work. */
|
|
63
|
+
foreground = false;
|
|
64
|
+
/** The prompt whose `started` frame came last in the open turn. */
|
|
65
|
+
turnCommand;
|
|
66
|
+
/** The state the client was told last. */
|
|
67
|
+
reportedState = "idle";
|
|
68
|
+
/** The open permission requests and elicitations of the session. */
|
|
69
|
+
requests = new Set();
|
|
70
|
+
/** Whether `session/cancel` stops the open turn: its idle reports `cancelled`. */
|
|
71
|
+
cancelledWork = false;
|
|
72
|
+
/** What a cancel stopped before the client saw it, and the reach of its interrupt. */
|
|
73
|
+
stopped = new StoppedWork();
|
|
74
|
+
/** The interrupt of the last `session/cancel`, while it runs. */
|
|
75
|
+
interrupting;
|
|
76
|
+
/** Pushes prompts in the order they came (see {@link prompt}). */
|
|
77
|
+
pushes = Promise.resolve();
|
|
78
|
+
/** Pushes the adapter's own prompts of the open turn in order (see {@link pushOwnPrompt}). */
|
|
79
|
+
ownPushes = Promise.resolve();
|
|
80
|
+
/** The result that ended the open turn, with what the turn spent. */
|
|
81
|
+
lastEnd;
|
|
82
|
+
usage = new ResultUsage(false);
|
|
83
|
+
/**
|
|
84
|
+
* Whether Claude Code's `idle` for the last result is still to come. It can
|
|
85
|
+
* come after the next cycle's first output, and does not end that cycle.
|
|
86
|
+
*/
|
|
87
|
+
idleOwed = false;
|
|
88
|
+
/** Whether Claude Code sends `command_lifecycle` frames (`msg_lifecycle_v1`). */
|
|
89
|
+
lifecycleFrames = false;
|
|
90
|
+
/** What the open turn's assistant messages reported about its end (see {@link TurnReport}). */
|
|
91
|
+
turnReport = new TurnReport();
|
|
92
|
+
/** Set by `session/close`, or when the query ends: nothing more goes out. */
|
|
93
|
+
closed = false;
|
|
94
|
+
closing;
|
|
95
|
+
/** Set by {@link start}. */
|
|
96
|
+
query;
|
|
97
|
+
output;
|
|
98
|
+
/** Usage, quota, notices, compactions and the title (see {@link SessionReports}). */
|
|
99
|
+
reports;
|
|
100
|
+
/** Resolves the adapter's own `/compact` once a turn ends (see {@link compact}). */
|
|
101
|
+
ownCommandDone;
|
|
102
|
+
/** The `background` lists of the session and its children, stamped on each state. */
|
|
103
|
+
background;
|
|
104
|
+
tasks;
|
|
105
|
+
elicitations;
|
|
106
|
+
/** AIR's file-change reports, when the client declared them (see `file-changes.ts`). */
|
|
107
|
+
fileChanges;
|
|
108
|
+
config;
|
|
109
|
+
commands;
|
|
110
|
+
/** ExitPlanMode's "clear context" option (see {@link ClearContext}). */
|
|
111
|
+
clearContext;
|
|
112
|
+
/** The `/mcp` prompts not inserted yet, by uuid, and the open turn's (see `SessionCommands`). */
|
|
113
|
+
localCommands = new Map();
|
|
114
|
+
turnLocalCommand;
|
|
115
|
+
/** The JSON of the query's MCP servers. */
|
|
116
|
+
mcpServers = "";
|
|
117
|
+
/** The adapter's `/remote-control`, and messages typed in other clients. */
|
|
118
|
+
remoteControl;
|
|
119
|
+
/** Who waits for {@link turnBoundary}, with whether it waits for a restart. */
|
|
120
|
+
boundaryWaiters = [];
|
|
121
|
+
constructor(sessionId, cwd,
|
|
122
|
+
/** The session's additional directories, as its query got them. */
|
|
123
|
+
additionalDirectories, connection, input,
|
|
124
|
+
/** Whether Claude Code's interrupt spares background tasks (see {@link SessionTasks}). */
|
|
125
|
+
reportsBackground = true,
|
|
126
|
+
/**
|
|
127
|
+
* The query's additional directories: the request's and those of the
|
|
128
|
+
* client's `_meta.claudeCode.options`. A file-change report lists paths
|
|
129
|
+
* in them and in `cwd`.
|
|
130
|
+
*/
|
|
131
|
+
workspaceDirectories = additionalDirectories) {
|
|
132
|
+
this.sessionId = sessionId;
|
|
133
|
+
this.cwd = cwd;
|
|
134
|
+
this.additionalDirectories = additionalDirectories;
|
|
135
|
+
this.connection = connection;
|
|
136
|
+
this.input = input;
|
|
137
|
+
this.output = new SessionOutput(sessionId, cwd, connection.translator, (update) => this.send(update), connection.logger);
|
|
138
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
139
|
+
const session = this;
|
|
140
|
+
const titled = {
|
|
141
|
+
get query() {
|
|
142
|
+
return session.query;
|
|
143
|
+
},
|
|
144
|
+
get queryClosed() {
|
|
145
|
+
return session.closed;
|
|
146
|
+
},
|
|
147
|
+
get cancelled() {
|
|
148
|
+
return session.cancelledWork;
|
|
149
|
+
},
|
|
150
|
+
cwd,
|
|
35
151
|
};
|
|
152
|
+
this.reports = new SessionReports({
|
|
153
|
+
sessionId,
|
|
154
|
+
logger: connection.logger,
|
|
155
|
+
airClient: connection.air.client,
|
|
156
|
+
emit: (notifications) => this.output.emitV1(notifications),
|
|
157
|
+
isBusy: () => this.foreground || this.pending.size > 0 || this.requests.size > 0,
|
|
158
|
+
compact: () => this.compact(),
|
|
159
|
+
titledSession: () => (this.query && !this.closed ? titled : undefined),
|
|
160
|
+
});
|
|
161
|
+
this.output.onAgentText = (content) => this.reports.agentText(content);
|
|
162
|
+
this.fileChanges = TurnFileChanges.create(connection.air.fileChangeReport, {
|
|
163
|
+
cwd,
|
|
164
|
+
additionalDirectories: [...workspaceDirectories],
|
|
165
|
+
publish: async (report) => this.send({
|
|
166
|
+
sessionUpdate: "session_info_update",
|
|
167
|
+
_meta: agentFileChangeReportMeta(report),
|
|
168
|
+
}),
|
|
169
|
+
logError: (message) => connection.logger.error(`Session ${sessionId}: ${message}`),
|
|
170
|
+
});
|
|
171
|
+
this.clearContext = new ClearContext({
|
|
172
|
+
push: (text, uuid) => this.pushOwnPrompt(text, uuid),
|
|
173
|
+
enterMode: (mode) => this.config.enterMode(mode),
|
|
174
|
+
publish: (plan) => {
|
|
175
|
+
this.send({
|
|
176
|
+
sessionUpdate: "config_option_update",
|
|
177
|
+
configOptions: this.config.options(),
|
|
178
|
+
});
|
|
179
|
+
// Otherwise the client shows the old context's usage until the fresh one reports its own.
|
|
180
|
+
this.reports.emptyContext();
|
|
181
|
+
// The approved plan becomes the session's plan. Its ExitPlanMode
|
|
182
|
+
// ended as a rejection, so the stream did not show it.
|
|
183
|
+
this.output.emitV1([{ sessionId, update: planModeUpdate(plan) }]);
|
|
184
|
+
},
|
|
185
|
+
logError: (message, error) => connection.logger.error(`Session ${sessionId}: ${message}`, error),
|
|
186
|
+
}, () => this.output.toolUses(), randomUUID);
|
|
187
|
+
this.background = new V2Background(connection.translator.terminals);
|
|
188
|
+
this.tasks = new SessionTasks({
|
|
189
|
+
sessionId,
|
|
190
|
+
cwd,
|
|
191
|
+
logger: connection.logger,
|
|
192
|
+
translator: connection.translator,
|
|
193
|
+
background: this.background,
|
|
194
|
+
reportsBackground,
|
|
195
|
+
send: (notification) => this.sendNotification(notification),
|
|
196
|
+
rootState: () => this.foregroundState(),
|
|
197
|
+
// A cancel withdraws the requests of the subagents that the work waits on.
|
|
198
|
+
foregroundRequestsChanged: () => this.reportState(this.cancelledWork),
|
|
199
|
+
models: () => this.config.subagentModels(),
|
|
200
|
+
modes: () => this.config.availableModes(),
|
|
201
|
+
stopTask: async (taskId) => {
|
|
202
|
+
await this.query?.stopTask(taskId);
|
|
203
|
+
},
|
|
204
|
+
}, this.output);
|
|
205
|
+
this.tasks.hostRequest = (request, signal) => unlessWithdrawn(signal, () => connection.requestPermission(request, signal));
|
|
206
|
+
this.elicitations = new SessionElicitations({
|
|
207
|
+
sessionId,
|
|
208
|
+
logger: connection.logger,
|
|
209
|
+
support: connection.elicitation,
|
|
210
|
+
airClient: connection.air.client,
|
|
211
|
+
createElicitation: (request, signal) => unlessWithdrawn(signal, () => connection.createElicitation(request, signal)),
|
|
212
|
+
completeElicitation: (params) => connection.completeElicitation(params),
|
|
213
|
+
target: (agentId) => this.target(agentId),
|
|
214
|
+
query: () => this.query,
|
|
215
|
+
});
|
|
216
|
+
this.remoteControl = new SessionRemoteControl({
|
|
217
|
+
logger: connection.logger,
|
|
218
|
+
query: () => this.query,
|
|
219
|
+
terminalCommands: () => this.commands.terminal(),
|
|
220
|
+
idle: () => this.turnBoundary(false),
|
|
221
|
+
begin: (uuid) => {
|
|
222
|
+
this.inserted(uuid);
|
|
223
|
+
this.openTurn(undefined);
|
|
224
|
+
},
|
|
225
|
+
end: (text, messageId) => {
|
|
226
|
+
this.output.agentMessage(text, messageId);
|
|
227
|
+
this.closeTurn();
|
|
228
|
+
},
|
|
229
|
+
});
|
|
36
230
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Starts reading the query. Called once, after its initialization.
|
|
233
|
+
* `mcpServers` are the servers the query started with.
|
|
234
|
+
*/
|
|
235
|
+
start(query, config, mcpServers, resumed = false) {
|
|
236
|
+
this.query = query;
|
|
237
|
+
this.config = config;
|
|
238
|
+
this.usage = new ResultUsage(resumed);
|
|
239
|
+
this.mcpServers = JSON.stringify(mcpServers);
|
|
240
|
+
this.commands = new SessionCommands(query);
|
|
241
|
+
void this.consume(query);
|
|
40
242
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
|
|
243
|
+
/** Sends the session's commands in an update, read again from Claude Code. */
|
|
244
|
+
async sendCommands() {
|
|
245
|
+
const availableCommands = await this.commands.list();
|
|
246
|
+
this.send({ sessionUpdate: "available_commands_update", availableCommands });
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* What `session/resume` sends before its response: the listed children
|
|
250
|
+
* with their current states, the current update of each listed item, then
|
|
251
|
+
* the session's state, with its list. A snapshot is no new completion, so
|
|
252
|
+
* its idle has no stop reason.
|
|
253
|
+
*/
|
|
254
|
+
resumeSnapshot() {
|
|
255
|
+
return [
|
|
256
|
+
...this.tasks.currentState(),
|
|
257
|
+
this.background.stamp({
|
|
258
|
+
sessionId: this.sessionId,
|
|
259
|
+
update: currentStateUpdate(this.foregroundState()),
|
|
260
|
+
}),
|
|
261
|
+
];
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Replaces the session's MCP servers, as a resume of the active session
|
|
265
|
+
* asks. The same servers stay as they are, connected.
|
|
266
|
+
*/
|
|
267
|
+
async setMcpServers(servers) {
|
|
268
|
+
const key = JSON.stringify(servers);
|
|
269
|
+
if (key === this.mcpServers)
|
|
270
|
+
return;
|
|
271
|
+
await this.query?.setMcpServers(servers);
|
|
272
|
+
this.reports.mcpServersChanged(Object.keys(servers));
|
|
273
|
+
this.mcpServers = key;
|
|
274
|
+
}
|
|
275
|
+
// --- Requests ---------------------------------------------------------
|
|
276
|
+
/**
|
|
277
|
+
* Pushes the prompt to Claude Code. Answers once Claude Code inserted it
|
|
278
|
+
* (see the module doc), right after the prompt's `user_message`.
|
|
279
|
+
*
|
|
280
|
+
* A prompt waits for the interrupt of an earlier `session/cancel` before it
|
|
281
|
+
* goes to Claude Code: the interrupt's `cancelQueued` must not end a prompt
|
|
282
|
+
* that came after the cancel.
|
|
283
|
+
*
|
|
284
|
+
* `guard`, the subscription guard's check (see `subscription-guard.ts`),
|
|
285
|
+
* runs in the prompt's turn among the session's prompts, so they keep their
|
|
286
|
+
* order, and a cancel or close answers a prompt that waits for it with
|
|
287
|
+
* -32800 as any prompt not inserted yet. Its refusal answers the prompt.
|
|
288
|
+
* The adapter's `/remote-control` is not guarded.
|
|
289
|
+
*/
|
|
290
|
+
prompt(params, guard) {
|
|
291
|
+
if (this.closed) {
|
|
292
|
+
return Promise.reject(RequestError.sessionNotFound(this.sessionId));
|
|
293
|
+
}
|
|
294
|
+
// Throws invalid params for content that Claude cannot take.
|
|
295
|
+
const request = v1PromptRequest(params);
|
|
296
|
+
const remoteControl = this.remoteControl.mayRun(request.prompt);
|
|
297
|
+
const guarded = guard && !remoteControl ? guard : undefined;
|
|
298
|
+
// A prompt that the guard refuses titles nothing and sends no notice.
|
|
299
|
+
const sent = () => {
|
|
300
|
+
this.reports.promptSent(request.prompt);
|
|
301
|
+
// The notice of a mode fallback at the session's start, which sends it at once.
|
|
302
|
+
void this.config.promptSent();
|
|
303
|
+
};
|
|
304
|
+
if (!guarded)
|
|
305
|
+
sent();
|
|
306
|
+
const uuid = randomUUID();
|
|
307
|
+
const message = { ...promptToClaude(request), uuid };
|
|
308
|
+
// Only a prompt that goes to Claude Code gets a file-change report, as on
|
|
309
|
+
// v1: the adapter's `/remote-control` registers it once it passes the
|
|
310
|
+
// prompt on (below).
|
|
311
|
+
if (!remoteControl)
|
|
312
|
+
this.fileChanges?.requested(uuid, params._meta);
|
|
313
|
+
const localCommand = this.commands.localCommand(request.prompt);
|
|
314
|
+
if (localCommand)
|
|
315
|
+
this.localCommands.set(uuid, localCommand);
|
|
316
|
+
return new Promise((resolve, reject) => {
|
|
317
|
+
const pending = { prompt: params.prompt, pushed: false, resolve, reject };
|
|
318
|
+
this.pending.set(uuid, pending);
|
|
319
|
+
// A cancel or close answered it before it went out.
|
|
320
|
+
const answered = () => this.pending.get(uuid) !== pending || this.closed;
|
|
321
|
+
this.pushes = this.pushes
|
|
322
|
+
.then(() => this.interrupting)
|
|
323
|
+
.then(async () => {
|
|
324
|
+
if (answered())
|
|
325
|
+
return;
|
|
326
|
+
if (guarded) {
|
|
327
|
+
try {
|
|
328
|
+
// Set by `start`, which runs before the agent lists the session.
|
|
329
|
+
await guarded(this.query);
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
this.failPrompt(uuid, error);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (answered())
|
|
336
|
+
return;
|
|
337
|
+
sent();
|
|
338
|
+
}
|
|
339
|
+
// The prompts after the adapter's `/remote-control` wait for it.
|
|
340
|
+
if (remoteControl) {
|
|
341
|
+
try {
|
|
342
|
+
if (await this.remoteControl.run(request.prompt, uuid, () => !answered()))
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
this.failPrompt(uuid, error);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (answered())
|
|
350
|
+
return;
|
|
351
|
+
this.fileChanges?.requested(uuid, params._meta);
|
|
352
|
+
}
|
|
353
|
+
pending.pushed = true;
|
|
354
|
+
this.remoteControl.pushed(uuid);
|
|
355
|
+
this.input.push(message);
|
|
356
|
+
this.reports.promptQueued(request.prompt);
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Whether no turn is open and no prompt waits in Claude Code's queue. With
|
|
362
|
+
* `restart`, for a restart of the query (see `restarts.ts`), also no
|
|
363
|
+
* prompt of the session waits to go to Claude Code, which the restart would
|
|
364
|
+
* answer with -32800, and no subagent runs. Without it, for the adapter's
|
|
365
|
+
* `/remote-control`, whose own prompt waits for the boundary.
|
|
366
|
+
*/
|
|
367
|
+
atTurnBoundary(restart) {
|
|
368
|
+
return (!this.closed &&
|
|
369
|
+
!this.foreground &&
|
|
370
|
+
![...this.pending.values()].some((prompt) => restart || prompt.pushed) &&
|
|
371
|
+
!(restart && this.tasks.hasLiveSubagents()));
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Resolves `true` at the next turn boundary (see {@link atTurnBoundary}),
|
|
375
|
+
* at once if the session is at one, and `false` once the session closed.
|
|
376
|
+
*/
|
|
377
|
+
turnBoundary(restart) {
|
|
378
|
+
if (this.closed)
|
|
379
|
+
return Promise.resolve(false);
|
|
380
|
+
if (this.atTurnBoundary(restart))
|
|
381
|
+
return Promise.resolve(true);
|
|
382
|
+
return new Promise((resolve) => this.boundaryWaiters.push({ restart, resolve }));
|
|
383
|
+
}
|
|
384
|
+
checkBoundary() {
|
|
385
|
+
for (const waiter of [...this.boundaryWaiters]) {
|
|
386
|
+
if (!this.closed && !this.atTurnBoundary(waiter.restart))
|
|
387
|
+
continue;
|
|
388
|
+
this.boundaryWaiters.splice(this.boundaryWaiters.indexOf(waiter), 1);
|
|
389
|
+
waiter.resolve(!this.closed);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* The adapter's idle compaction: `/compact`, as Claude Code's own turn. It
|
|
394
|
+
* is no prompt of the client's, so it gets no `user_message`, and the client
|
|
395
|
+
* sees its turn as `running`, then `idle`. Resolves when a turn ends after
|
|
396
|
+
* it: the idle compaction runs it only while the session is idle, so the
|
|
397
|
+
* next turn to end is its own.
|
|
398
|
+
*/
|
|
399
|
+
compact() {
|
|
400
|
+
return new Promise((resolve) => {
|
|
401
|
+
this.ownCommandDone?.();
|
|
402
|
+
this.ownCommandDone = resolve;
|
|
403
|
+
const message = {
|
|
404
|
+
...promptToClaude({
|
|
405
|
+
sessionId: this.sessionId,
|
|
406
|
+
prompt: [{ type: "text", text: "/compact" }],
|
|
407
|
+
}),
|
|
408
|
+
uuid: randomUUID(),
|
|
409
|
+
};
|
|
410
|
+
this.pushes = this.pushes
|
|
411
|
+
.then(() => this.interrupting)
|
|
412
|
+
.then(() => {
|
|
413
|
+
if (this.closed) {
|
|
414
|
+
resolve();
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
this.remoteControl.pushed(message.uuid);
|
|
418
|
+
this.input.push(message);
|
|
419
|
+
});
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Sends Claude Code the adapter's own prompt `text`, after the interrupt of
|
|
424
|
+
* an earlier `session/cancel`, as {@link prompt} does. It is no prompt of
|
|
425
|
+
* the client's: it gets no `user_message`, also when its echo carries the
|
|
426
|
+
* human `origin` that `promptToClaude` stamps.
|
|
427
|
+
*
|
|
428
|
+
* These prompts continue the open turn (`clear-context.ts`), so they do not
|
|
429
|
+
* wait on {@link pushes}: a `/remote-control` there waits for the turn to
|
|
430
|
+
* end, which needs them. The client's prompts keep their order among
|
|
431
|
+
* themselves on `pushes`.
|
|
432
|
+
*/
|
|
433
|
+
pushOwnPrompt(text, uuid) {
|
|
434
|
+
const message = {
|
|
435
|
+
...promptToClaude({ sessionId: this.sessionId, prompt: [{ type: "text", text }] }),
|
|
436
|
+
uuid,
|
|
437
|
+
};
|
|
438
|
+
this.ownPushes = this.ownPushes
|
|
439
|
+
.then(() => this.interrupting)
|
|
440
|
+
.then(() => {
|
|
441
|
+
if (this.closed)
|
|
442
|
+
return;
|
|
443
|
+
this.remoteControl.pushed(uuid);
|
|
444
|
+
this.input.push(message);
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Stops the foreground work, and answers the prompts not inserted yet with
|
|
449
|
+
* -32800. The work's idle reports `cancelled`. Background work goes on.
|
|
450
|
+
*
|
|
451
|
+
* The interrupt goes out also while the session is idle:
|
|
452
|
+
* Claude Code may run a cycle that this session has not read yet.
|
|
453
|
+
*/
|
|
454
|
+
async cancel() {
|
|
455
|
+
if (this.closed || !this.query)
|
|
456
|
+
return;
|
|
457
|
+
this.reports.disarmIdleCompaction("cancel");
|
|
458
|
+
this.stopForeground();
|
|
459
|
+
// `cancelQueued` is untyped in the SDK (`Query.interrupt` takes it since
|
|
460
|
+
// the CLI's `interrupt_cancel_queued_v1`): Claude Code then drops the
|
|
461
|
+
// queued prompts, which this session answered already.
|
|
462
|
+
const interrupt = this.query.interrupt;
|
|
463
|
+
const done = interrupt.call(this.query, { cancelQueued: true }).then(() => undefined, (error) => {
|
|
464
|
+
// `session/cancel` is a notification: no one can be answered. Nothing
|
|
465
|
+
// stopped, so the work's idle reports how it really ends.
|
|
466
|
+
this.connection.logger.error(`Session ${this.sessionId}: the interrupt failed`, error);
|
|
467
|
+
this.cancelledWork = false;
|
|
468
|
+
this.output.cancelled = false;
|
|
469
|
+
this.stopped.interruptFailed();
|
|
470
|
+
this.tasks.foregroundCancelFailed();
|
|
471
|
+
// The withdrawn requests reported no `running`: the work goes on.
|
|
472
|
+
this.reportState();
|
|
473
|
+
});
|
|
474
|
+
this.interrupting = done;
|
|
475
|
+
await done;
|
|
476
|
+
if (this.interrupting === done)
|
|
477
|
+
this.interrupting = undefined;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* What a cancel or close stops at once: the prompts not inserted yet, the
|
|
481
|
+
* open turn, and the work of the subagents that it waits on. The open
|
|
482
|
+
* permission requests stay open: Claude Code's interrupt withdraws them,
|
|
483
|
+
* and the end of the stopped work withdraws what is left (see
|
|
484
|
+
* {@link closeTurn}).
|
|
485
|
+
*/
|
|
486
|
+
stopForeground() {
|
|
487
|
+
const pushed = [];
|
|
488
|
+
for (const [uuid, prompt] of [...this.pending]) {
|
|
489
|
+
if (prompt.pushed)
|
|
490
|
+
pushed.push(uuid);
|
|
491
|
+
this.failPrompt(uuid, RequestError.requestCancelled());
|
|
492
|
+
}
|
|
493
|
+
// A turn that waits for its plan's prompt in a fresh context: the
|
|
494
|
+
// adapter's prompts are stopped work too, and no frame of the turn's own
|
|
495
|
+
// prompt is left to end it.
|
|
496
|
+
const heldTurn = this.clearContext.holdsTurn();
|
|
497
|
+
pushed.push(...this.clearContext.stop());
|
|
498
|
+
this.stopped.cancelled(pushed, this.foreground);
|
|
499
|
+
if (this.foreground) {
|
|
500
|
+
this.cancelledWork = true;
|
|
501
|
+
this.output.cancelled = true;
|
|
502
|
+
}
|
|
503
|
+
for (const request of this.requests)
|
|
504
|
+
request.coveredByCancel = true;
|
|
505
|
+
this.turnLocalCommand?.abort.abort();
|
|
506
|
+
// The subagents that the work waits on stop with it. Background ones go on.
|
|
507
|
+
this.tasks.cancelForeground();
|
|
508
|
+
if (heldTurn)
|
|
509
|
+
this.closeTurn();
|
|
510
|
+
}
|
|
511
|
+
async setConfigOption(params) {
|
|
512
|
+
await this.config.set(params);
|
|
513
|
+
if (params.configId === MODEL_CONFIG_ID)
|
|
514
|
+
this.modelChangedReports();
|
|
515
|
+
const options = this.config.options();
|
|
516
|
+
// v2 sends every config change as an update too, for the session's other clients.
|
|
517
|
+
this.send({ sessionUpdate: "config_option_update", configOptions: options });
|
|
104
518
|
return options;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Cancels as `session/cancel` does, ends the open turn with its cancelled
|
|
522
|
+
* idle, then ends the query, which stops the background work too. Nothing
|
|
523
|
+
* of the session goes out after it resolves. It does not wait for Claude
|
|
524
|
+
* Code to end the work: the query's end stops it, and the
|
|
525
|
+
* tool calls that the work leaves open end `cancelled` before its idle.
|
|
526
|
+
*/
|
|
527
|
+
close() {
|
|
528
|
+
this.closing ??= (async () => {
|
|
529
|
+
if (!this.closed)
|
|
530
|
+
this.stopForeground();
|
|
531
|
+
// v2 asks to withdraw every request of the session before the close
|
|
532
|
+
// response, also its background subagents' and the MCP OAuth runs'.
|
|
533
|
+
this.tasks.withdrawAll();
|
|
534
|
+
this.elicitations.close();
|
|
535
|
+
for (const request of this.requests) {
|
|
536
|
+
request.coveredByCancel = true;
|
|
537
|
+
request.abort.abort();
|
|
538
|
+
}
|
|
539
|
+
this.closeTurn();
|
|
540
|
+
this.failPending(RequestError.requestCancelled());
|
|
541
|
+
this.closed = true;
|
|
542
|
+
this.checkBoundary();
|
|
543
|
+
this.endReports();
|
|
544
|
+
this.input.end();
|
|
545
|
+
this.query?.close();
|
|
546
|
+
})();
|
|
547
|
+
return this.closing;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Ends the session's query, which a new one replaced (see `restarts.ts`).
|
|
551
|
+
* The session is idle then. Its background work ends with the query: its
|
|
552
|
+
* terminals exit and its listed tool calls end before the list drops them,
|
|
553
|
+
* as when a query ends. Then it closes as {@link close} does.
|
|
554
|
+
*/
|
|
555
|
+
retire() {
|
|
556
|
+
if (!this.closed && !this.closing) {
|
|
557
|
+
this.tasks.queryEnded({
|
|
558
|
+
code: RequestError.internalError().code,
|
|
559
|
+
message: "The session's query restarted",
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
return this.close();
|
|
563
|
+
}
|
|
564
|
+
// --- Permission requests -----------------------------------------------
|
|
565
|
+
get airClient() {
|
|
566
|
+
return this.connection.air.client;
|
|
567
|
+
}
|
|
568
|
+
availableModes() {
|
|
569
|
+
return this.config.availableModeIds();
|
|
570
|
+
}
|
|
571
|
+
cancelling() {
|
|
572
|
+
return this.cancelledWork;
|
|
573
|
+
}
|
|
574
|
+
dropsToolUse(toolUseId, agentId, signal) {
|
|
575
|
+
return this.stopped.dropsToolUse(toolUseId, agentId, signal);
|
|
576
|
+
}
|
|
577
|
+
/** The session of a permission request: this one, or a subagent's (see `canUseTool`). */
|
|
578
|
+
target(agentId) {
|
|
579
|
+
return this.tasks.target(agentId, this);
|
|
580
|
+
}
|
|
581
|
+
requestPermission(request, toolSignal) {
|
|
582
|
+
return this.openRequest(toolSignal, async (signal) => {
|
|
583
|
+
try {
|
|
584
|
+
// The subject is an upsert of the tool call: the client may see the
|
|
585
|
+
// request before the tool use streams.
|
|
586
|
+
return await unlessWithdrawn(signal, () => this.connection.requestPermission(request, signal));
|
|
587
|
+
}
|
|
588
|
+
catch (error) {
|
|
589
|
+
if (signal.aborted)
|
|
590
|
+
return { outcome: { outcome: "cancelled" } };
|
|
591
|
+
throw error;
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
/** Runs `send` as an open request of this session (see {@link RequestTarget.openRequest}). */
|
|
596
|
+
async openRequest(toolSignal, send) {
|
|
597
|
+
const open = { abort: new AbortController(), coveredByCancel: false };
|
|
598
|
+
// After `session/close` nothing of the session goes out: the request is
|
|
599
|
+
// withdrawn before it is sent.
|
|
600
|
+
if (this.closed)
|
|
601
|
+
open.abort.abort();
|
|
602
|
+
const signal = AbortSignal.any([toolSignal, open.abort.signal]);
|
|
603
|
+
this.requests.add(open);
|
|
604
|
+
this.reportState();
|
|
605
|
+
try {
|
|
606
|
+
return await send(signal);
|
|
607
|
+
}
|
|
608
|
+
finally {
|
|
609
|
+
this.requests.delete(open);
|
|
610
|
+
// A request withdrawn after a cancel (Claude Code's interrupt aborts
|
|
611
|
+
// `toolSignal`) ends work that is stopping: its idle follows, so no
|
|
612
|
+
// `running` comes first. One that the user answers, or that Claude Code
|
|
613
|
+
// withdraws without a cancel (a hook answered it), lets the work go on.
|
|
614
|
+
this.reportState(open.coveredByCancel && signal.aborted);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
modeChanged(mode) {
|
|
618
|
+
if (this.config.modeChanged(mode)) {
|
|
619
|
+
this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
prePlanMode() {
|
|
623
|
+
return this.config.prePlanMode();
|
|
624
|
+
}
|
|
625
|
+
/** A fresh context continues the open turn: only the root's plan in a turn offers it. */
|
|
626
|
+
contextReset(agentId) {
|
|
627
|
+
return {
|
|
628
|
+
offered: agentId === undefined && this.foreground,
|
|
629
|
+
usedPercent: this.reports.contextUsedPercent(),
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
exitPlanInterrupting(toolUseId, reset) {
|
|
633
|
+
// The fresh context starts in the mode that the answer's mode runs as on
|
|
634
|
+
// the model, such as `acceptEdits` for `auto` on a model without Auto,
|
|
635
|
+
// with no fallback notice.
|
|
636
|
+
this.clearContext.interrupting(toolUseId, reset && { ...reset, mode: this.config.effectiveMode(reset.mode) });
|
|
637
|
+
}
|
|
638
|
+
permissionAllowed(result) {
|
|
639
|
+
return this.config.permissionAllowed(result);
|
|
640
|
+
}
|
|
641
|
+
requestShows(target, toolName, toolCallId) {
|
|
642
|
+
this.tasks.requestShows(target.output, toolName, toolCallId);
|
|
643
|
+
}
|
|
644
|
+
toolCallSubject(sessionId, toolCall) {
|
|
645
|
+
return this.connection.translator.toolCallMeta.subject(sessionId, toolCall);
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Claude Code switched the model without the adapter: a typed `/model`
|
|
649
|
+
* (see `modelSwitchHook`), or a refusal fallback.
|
|
650
|
+
*/
|
|
651
|
+
modelSwitched(model) {
|
|
652
|
+
this.config.modelSwitched(model).then((changed) => {
|
|
653
|
+
if (!changed)
|
|
654
|
+
return;
|
|
655
|
+
this.modelChangedReports();
|
|
656
|
+
this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
|
|
657
|
+
}, (error) => {
|
|
658
|
+
this.connection.logger.error(`Session ${this.sessionId}: failed to follow a model switch`, error);
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
/** The reports follow the model: its context window, and the idle compaction. */
|
|
662
|
+
modelChangedReports() {
|
|
663
|
+
const { id, info } = this.config.currentModel();
|
|
664
|
+
this.reports.modelChanged(id, info);
|
|
665
|
+
}
|
|
666
|
+
/** Claude Code reported a Fast mode state, on `system`/init or a result. */
|
|
667
|
+
fastModeReported(message) {
|
|
668
|
+
if (this.config.fastModeReported(message.fast_mode_state, message.fast_mode_disabled_reason)) {
|
|
669
|
+
this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Claude Code mounted a fresh conversation (such as for `/clear`), whose
|
|
674
|
+
* Task* ids and task store are independent of the previous transcript. The
|
|
675
|
+
* old conversation's plans are removed (`plan_removed` of the checklist and
|
|
676
|
+
* of the approved ExitPlanMode plan) before a follow-up prompt can
|
|
677
|
+
* republish stale tasks, and the title and the idle compaction start over.
|
|
678
|
+
* The fresh context of an approved plan removes no plan: that plan becomes
|
|
679
|
+
* the session's plan in it.
|
|
680
|
+
*/
|
|
681
|
+
conversationReset() {
|
|
682
|
+
// First, the subagents of the dropped conversation end.
|
|
683
|
+
this.tasks.conversationReset();
|
|
684
|
+
this.output.taskState.clear();
|
|
685
|
+
if (!this.clearContext.holdsTurn()) {
|
|
686
|
+
// Every v2 client has plan operations. v2 publishes an approved plan
|
|
687
|
+
// under the plain `plan-mode` id, also to AIR (see `planModeUpdate`).
|
|
688
|
+
const updates = resetPlanUpdates(true, false);
|
|
689
|
+
this.output.emitV1(updates.map((update) => ({ sessionId: this.sessionId, update })));
|
|
690
|
+
}
|
|
691
|
+
this.reports.conversationReset();
|
|
692
|
+
// A fresh context for an approved plan: the plan goes out in it.
|
|
693
|
+
this.clearContext.conversationReset();
|
|
694
|
+
}
|
|
695
|
+
// --- The query's messages ----------------------------------------------
|
|
696
|
+
async consume(query) {
|
|
697
|
+
try {
|
|
698
|
+
for await (const message of query) {
|
|
699
|
+
if (this.closed)
|
|
700
|
+
break;
|
|
701
|
+
try {
|
|
702
|
+
await this.handle(message);
|
|
703
|
+
}
|
|
704
|
+
catch (error) {
|
|
705
|
+
this.connection.logger.error(`Session ${this.sessionId}: failed to handle a ${message.type} message`, error);
|
|
706
|
+
}
|
|
707
|
+
this.checkBoundary();
|
|
708
|
+
}
|
|
709
|
+
this.ended(undefined);
|
|
710
|
+
}
|
|
711
|
+
catch (error) {
|
|
712
|
+
this.ended(error);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Claude Code's tool results. A SendMessage result can restore the agent
|
|
717
|
+
* that it resumed from the history: the results go out after the restore
|
|
718
|
+
* (see `SessionTasks.restoreResumed`).
|
|
719
|
+
*/
|
|
720
|
+
toolResultMessage(message) {
|
|
721
|
+
const restoring = this.tasks.restoreResumed(this.output, message);
|
|
722
|
+
if (restoring)
|
|
723
|
+
return restoring.then(() => this.toolResults(message));
|
|
724
|
+
this.toolResults(message);
|
|
725
|
+
}
|
|
726
|
+
toolResults(message) {
|
|
727
|
+
if (message.parent_tool_use_id !== null) {
|
|
728
|
+
this.tasks.toolResults(this.output, message);
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
// The rewrite applies to the updates of this message only.
|
|
732
|
+
this.output.rewrite = this.clearContext.toolResults(message);
|
|
733
|
+
try {
|
|
734
|
+
this.tasks.toolResults(this.output, message);
|
|
735
|
+
}
|
|
736
|
+
finally {
|
|
737
|
+
this.output.rewrite = undefined;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Handles one message. Only a `/mcp` turn's result, a result whose turn
|
|
742
|
+
* reads file-change reports, and a subagent's restore from the history are
|
|
743
|
+
* awaited (see {@link result}, {@link endTurn} and `SessionTasks.restored`).
|
|
744
|
+
*/
|
|
745
|
+
handle(message) {
|
|
746
|
+
if (message.type === "command_lifecycle") {
|
|
747
|
+
this.lifecycle(message);
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
// Before the tasks take a subagent's messages: its file edits are the turn's.
|
|
751
|
+
this.fileChanges?.message(message);
|
|
752
|
+
// Task events, and a subagent's messages, which go to its session.
|
|
753
|
+
// A subagent that a task restores from the history is read before the next message.
|
|
754
|
+
if (this.tasks.handle(message))
|
|
755
|
+
return this.tasks.restored();
|
|
756
|
+
switch (message.type) {
|
|
757
|
+
case "conversation_reset":
|
|
758
|
+
this.conversationReset();
|
|
759
|
+
return;
|
|
760
|
+
case "stream_event":
|
|
761
|
+
if (this.stopped.drops(message))
|
|
762
|
+
return;
|
|
763
|
+
if (message.parent_tool_use_id === null) {
|
|
764
|
+
this.outputStarts();
|
|
765
|
+
this.reports.streamEvent(message);
|
|
766
|
+
}
|
|
767
|
+
this.output.streamEvent(message);
|
|
768
|
+
return;
|
|
769
|
+
case "assistant":
|
|
770
|
+
if (message.parent_tool_use_id === null)
|
|
771
|
+
this.usage.assistant(message.message.model);
|
|
772
|
+
if (this.stopped.drops(message))
|
|
773
|
+
return;
|
|
774
|
+
if (message.parent_tool_use_id === null) {
|
|
775
|
+
// Claude Code's sign-in message is not shown (see `TurnReport`).
|
|
776
|
+
if (this.turnReport.assistant(message))
|
|
777
|
+
return;
|
|
778
|
+
this.outputStarts();
|
|
779
|
+
this.reports.assistant(message);
|
|
780
|
+
}
|
|
781
|
+
this.output.assistant(message);
|
|
782
|
+
return;
|
|
783
|
+
case "user":
|
|
784
|
+
// With `replay-user-messages`, Claude Code echoes each prompt it takes
|
|
785
|
+
// in. A prompt Claude Code reported `started` for is inserted already.
|
|
786
|
+
if ("isReplay" in message && message.isReplay) {
|
|
787
|
+
if (message.uuid && message.parent_tool_use_id === null) {
|
|
788
|
+
// A message typed in another client of the session.
|
|
789
|
+
const remote = this.remoteControl.remoteMessage(message);
|
|
790
|
+
if (remote !== undefined)
|
|
791
|
+
this.output.userMessage(remote, message.uuid);
|
|
792
|
+
this.promptStarted(message.uuid);
|
|
793
|
+
}
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
if (this.stopped.drops(message))
|
|
797
|
+
return;
|
|
798
|
+
return this.toolResultMessage(message);
|
|
799
|
+
case "result":
|
|
800
|
+
return this.result(message);
|
|
801
|
+
case "system":
|
|
802
|
+
switch (message.subtype) {
|
|
803
|
+
case "init":
|
|
804
|
+
if (message.capabilities?.includes("msg_lifecycle_v1"))
|
|
805
|
+
this.lifecycleFrames = true;
|
|
806
|
+
this.elicitations.init(message.capabilities);
|
|
807
|
+
// A fresh init (such as after a reinitialize) can carry another Fast mode state.
|
|
808
|
+
this.fastModeReported(message);
|
|
809
|
+
this.reports.handle(message);
|
|
810
|
+
// Its terminal-bound commands leave the list.
|
|
811
|
+
if (this.commands.init(message))
|
|
812
|
+
this.resendCommands();
|
|
813
|
+
return;
|
|
814
|
+
case "status":
|
|
815
|
+
// Each model request starts with one, which lists the prompts it serves.
|
|
816
|
+
if (message.status === "requesting") {
|
|
817
|
+
const prompts = message.user_message_uuids;
|
|
818
|
+
this.stopped.requesting(Array.isArray(prompts) ? prompts : []);
|
|
819
|
+
}
|
|
820
|
+
this.report(message);
|
|
821
|
+
return;
|
|
822
|
+
case "local_command_output":
|
|
823
|
+
// The output of a local command, such as `/cost`.
|
|
824
|
+
if (this.stopped.drops(message))
|
|
825
|
+
return;
|
|
826
|
+
this.output.agentMessage(message.content, message.uuid);
|
|
827
|
+
return;
|
|
828
|
+
case "commands_changed":
|
|
829
|
+
this.send(this.commands.changed(message.commands));
|
|
830
|
+
return;
|
|
831
|
+
case "elicitation_complete":
|
|
832
|
+
this.elicitations.completed(message.elicitation_id);
|
|
833
|
+
return;
|
|
834
|
+
case "model_refusal_fallback": {
|
|
835
|
+
// Claude Code retried a refused turn on the fallback model.
|
|
836
|
+
const fallback = modelRefusalFallback(message);
|
|
837
|
+
this.output.emitV1([
|
|
838
|
+
{ sessionId: this.sessionId, update: noticeUpdate(fallback.notice) },
|
|
839
|
+
]);
|
|
840
|
+
if (fallback.persistent)
|
|
841
|
+
this.modelSwitched(message.fallback_model);
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
case "model_refusal_no_fallback":
|
|
845
|
+
this.turnReport.refusalWithoutFallback(message);
|
|
846
|
+
return;
|
|
847
|
+
case "permission_denied":
|
|
848
|
+
// A rule, the classifier or the mode denied a tool use before it ran.
|
|
849
|
+
this.tasks.permissionDenied(message);
|
|
850
|
+
return;
|
|
851
|
+
case "session_state_changed":
|
|
852
|
+
if (message.state === "idle") {
|
|
853
|
+
this.claudeCodeIdle();
|
|
854
|
+
this.reports.idle();
|
|
855
|
+
}
|
|
856
|
+
return;
|
|
857
|
+
default:
|
|
858
|
+
this.report(message);
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
default:
|
|
862
|
+
this.report(message);
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* The messages that report on the session rather than carry Claude's
|
|
868
|
+
* output (see {@link SessionReports}).
|
|
869
|
+
*/
|
|
870
|
+
report(message) {
|
|
871
|
+
if (message.type === "tool_progress") {
|
|
872
|
+
this.output.toolProgress(message);
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
if (message.type === "system" && message.subtype === "memory_recall") {
|
|
876
|
+
this.output.memoryRecall(message);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
// A compaction runs in a turn: it opens the turn if nothing reported it yet.
|
|
880
|
+
if (message.type === "system" &&
|
|
881
|
+
message.subtype === "status" &&
|
|
882
|
+
message.status === "compacting") {
|
|
883
|
+
this.openTurn(undefined);
|
|
884
|
+
}
|
|
885
|
+
this.reports.handle(message);
|
|
886
|
+
}
|
|
887
|
+
lifecycle(frame) {
|
|
888
|
+
this.lifecycleFrames = true;
|
|
889
|
+
const uuid = frame.command_uuid;
|
|
890
|
+
switch (frame.state) {
|
|
891
|
+
case "started":
|
|
892
|
+
this.promptStarted(uuid);
|
|
893
|
+
return;
|
|
894
|
+
case "cancelled":
|
|
895
|
+
if (this.failPrompt(uuid, RequestError.requestCancelled()))
|
|
896
|
+
return;
|
|
897
|
+
this.stopped.promptEnded(uuid, true);
|
|
898
|
+
// The prompt had started: the interrupt stopped its turn.
|
|
899
|
+
if (uuid === this.turnCommand)
|
|
900
|
+
this.closeTurn();
|
|
901
|
+
return;
|
|
902
|
+
case "discarded":
|
|
903
|
+
case "refused":
|
|
904
|
+
this.failPrompt(uuid, RequestError.internalError({ lifecycle: frame.state }, `Claude Code ${frame.state} the prompt before it ran`));
|
|
905
|
+
return;
|
|
906
|
+
case "completed":
|
|
907
|
+
// Comes after the turn's result. A turn that ended without one ends here.
|
|
908
|
+
this.stopped.promptEnded(uuid);
|
|
909
|
+
if (uuid === this.turnCommand)
|
|
910
|
+
this.closeTurn();
|
|
911
|
+
return;
|
|
912
|
+
default:
|
|
913
|
+
// `queued`: the prompt waits in Claude Code's queue.
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Claude Code took in the prompt `uuid`: its `started` frame or its echo.
|
|
919
|
+
* The prompt's `user_message` comes before the turn's `running`. v2 allows
|
|
920
|
+
* either order. A prompt that a cancel abandoned starts
|
|
921
|
+
* nothing (see {@link StoppedWork}).
|
|
922
|
+
*/
|
|
923
|
+
promptStarted(uuid) {
|
|
924
|
+
if (this.stopped.promptStarted(uuid, this.foreground))
|
|
925
|
+
return;
|
|
926
|
+
// Claude Code takes its prompts in order: the work that a cancel stopped
|
|
927
|
+
// has ended, also when the cancel came while it ran nothing.
|
|
928
|
+
this.tasks.foregroundCancelEnded();
|
|
929
|
+
if (this.clearContext.promptStarted(uuid))
|
|
930
|
+
this.fileChanges?.contextCleared(uuid);
|
|
931
|
+
this.inserted(uuid);
|
|
932
|
+
this.openTurn(uuid);
|
|
933
|
+
}
|
|
934
|
+
inserted(uuid) {
|
|
935
|
+
const prompt = this.pending.get(uuid);
|
|
936
|
+
if (!prompt)
|
|
937
|
+
return;
|
|
938
|
+
this.pending.delete(uuid);
|
|
939
|
+
this.fileChanges?.promptStarted(uuid);
|
|
940
|
+
this.send({ sessionUpdate: "user_message", messageId: uuid, content: prompt.prompt });
|
|
941
|
+
prompt.resolve({ messageId: uuid });
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Output of the main conversation while no turn is open starts a cycle
|
|
945
|
+
* that Claude Code started on its own. Without lifecycle frames, a pushed
|
|
946
|
+
* prompt's output can come before its echo, so output while one waits is
|
|
947
|
+
* that prompt's, and its echo opens the turn.
|
|
948
|
+
*/
|
|
949
|
+
outputStarts() {
|
|
950
|
+
if (this.foreground)
|
|
951
|
+
return;
|
|
952
|
+
if (!this.lifecycleFrames && [...this.pending.values()].some((prompt) => prompt.pushed)) {
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
this.openTurn(undefined);
|
|
956
|
+
}
|
|
957
|
+
result(message) {
|
|
958
|
+
// Every result moves the usage reading on, also one that ends nothing.
|
|
959
|
+
const end = this.usage.record(message);
|
|
960
|
+
if (isPlaceholderResult(message))
|
|
961
|
+
return;
|
|
962
|
+
this.idleOwed = true;
|
|
963
|
+
const { dropped, interrupted } = this.stopped.result(message);
|
|
964
|
+
// Also a dropped result: the cancel's interrupt reached no further.
|
|
965
|
+
this.tasks.foregroundCancelEnded();
|
|
966
|
+
if (dropped) {
|
|
967
|
+
this.turnReport.reset();
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
// The interrupt stopped work that Claude Code had started before the cancel arrived.
|
|
971
|
+
if (interrupted)
|
|
972
|
+
this.cancelledWork = true;
|
|
973
|
+
// A result with no open turn: a turn that sent nothing before it.
|
|
974
|
+
this.openTurn(undefined);
|
|
975
|
+
// A cycle that Claude Code started on its own leaves its Fast mode state
|
|
976
|
+
// to the next result of a prompt.
|
|
977
|
+
if (!(message.origin && AUTONOMOUS_RESULT_ORIGINS.has(message.origin.kind))) {
|
|
978
|
+
this.fastModeReported(message);
|
|
979
|
+
}
|
|
980
|
+
this.reports.result(message);
|
|
981
|
+
// The turn goes on in a fresh context (see `ClearContext`).
|
|
982
|
+
if (this.clearContext.holdsResult(message, end)) {
|
|
983
|
+
this.turnReport.reset();
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
this.lastEnd = this.clearContext.turnEnd(end);
|
|
987
|
+
const local = this.turnLocalCommand;
|
|
988
|
+
if (message.stop_reason === "refusal") {
|
|
989
|
+
// The refused message shows nothing: its explanation answers.
|
|
990
|
+
const explanation = this.turnReport.refusalExplanation;
|
|
991
|
+
if (explanation)
|
|
992
|
+
this.output.agentMessage(explanation, message.uuid);
|
|
993
|
+
}
|
|
994
|
+
else if (message.subtype === "success" &&
|
|
995
|
+
!message.is_error &&
|
|
996
|
+
message.result &&
|
|
997
|
+
!this.output.hasAgentText() &&
|
|
998
|
+
!this.reports.repeats(message.result)) {
|
|
999
|
+
// A local command (such as `/context`) answers with its result alone:
|
|
1000
|
+
// no model text streamed for it. A result that only repeats a notice or
|
|
1001
|
+
// a compaction of the turn is not shown again.
|
|
1002
|
+
if (local && this.query) {
|
|
1003
|
+
// The adapter's `/mcp` text replaces Claude Code's. `consume` waits
|
|
1004
|
+
// for it, so it goes out before the turn's idle.
|
|
1005
|
+
return this.commands
|
|
1006
|
+
.replace(this.query, local.command, message.result, local.abort.signal, (error) => this.connection.logger.error(`Session ${this.sessionId}: ${error}`))
|
|
1007
|
+
.then((text) => {
|
|
1008
|
+
this.output.agentMessage(text, message.uuid);
|
|
1009
|
+
return this.endTurn();
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
this.output.agentMessage(message.result, message.uuid);
|
|
1013
|
+
}
|
|
1014
|
+
return this.endTurn();
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Ends the open turn at its result. The file-change reports that its
|
|
1018
|
+
* prompts asked for go out first (see `file-changes.ts`). `consume` waits
|
|
1019
|
+
* for them, so the idle follows them.
|
|
1020
|
+
*/
|
|
1021
|
+
endTurn() {
|
|
1022
|
+
if (!this.foreground || this.clearContext.holdsTurn())
|
|
1023
|
+
return;
|
|
1024
|
+
const { stopReason } = idleOutcome(this.lastEnd, this.cancelledWork, this.turnReport);
|
|
1025
|
+
const reporting = this.fileChanges?.turnEnding(stopReason, this.query);
|
|
1026
|
+
if (!reporting)
|
|
1027
|
+
return this.closeTurn();
|
|
1028
|
+
return reporting.then(() => this.closeTurn());
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Claude Code's `idle`. The one that follows a result is that result's, and
|
|
1032
|
+
* can come after the next cycle's first output. Any other ends the open
|
|
1033
|
+
* turn, such as one that an interrupt stopped before it ran.
|
|
1034
|
+
*/
|
|
1035
|
+
claudeCodeIdle() {
|
|
1036
|
+
if (this.idleOwed) {
|
|
1037
|
+
this.idleOwed = false;
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
this.stopped.idle();
|
|
1041
|
+
this.tasks.foregroundCancelEnded();
|
|
1042
|
+
this.closeTurn();
|
|
1043
|
+
}
|
|
1044
|
+
/** Sends the commands again, without failing the message that changed them. */
|
|
1045
|
+
resendCommands() {
|
|
1046
|
+
this.sendCommands().catch((error) => {
|
|
1047
|
+
this.connection.logger.error(`Session ${this.sessionId}: failed to send its commands`, error);
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
/** The query ended, with `error` when it failed. The session cannot go on. */
|
|
1051
|
+
ended(error) {
|
|
1052
|
+
this.endReports();
|
|
1053
|
+
if (this.closing || this.closed) {
|
|
1054
|
+
this.tasks.queryEnded(undefined);
|
|
1055
|
+
this.failPending(RequestError.requestCancelled());
|
|
1056
|
+
this.closed = true;
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
const failure = RequestError.internalError(error instanceof Error ? { cause: error.message } : undefined, "Claude Code stopped. Resume the session to continue.");
|
|
1060
|
+
this.failPending(failure);
|
|
1061
|
+
this.connection.logger.error(`Session ${this.sessionId}: the query ended`, error);
|
|
1062
|
+
this.tasks.queryEnded({ code: failure.code, message: failure.message });
|
|
1063
|
+
if (this.foreground) {
|
|
1064
|
+
// Cancelled work that ended with the query was still cancelled.
|
|
1065
|
+
if (this.cancelledWork)
|
|
1066
|
+
this.output.closeUnfinished(true);
|
|
1067
|
+
else
|
|
1068
|
+
this.output.finishUnfinished("failed");
|
|
1069
|
+
this.fileChanges?.turnClosed(this.cancelledWork);
|
|
1070
|
+
// As `closeTurn`: a compaction still `in_progress` ends before the idle.
|
|
1071
|
+
this.reports.turnEnded();
|
|
1072
|
+
this.foreground = false;
|
|
1073
|
+
this.reportedState = "idle";
|
|
1074
|
+
this.send({
|
|
1075
|
+
sessionUpdate: "state_update",
|
|
1076
|
+
state: "idle",
|
|
1077
|
+
...(this.cancelledWork
|
|
1078
|
+
? idleOutcome(undefined, true, undefined, this.turnCommand !== undefined)
|
|
1079
|
+
: {
|
|
1080
|
+
stopReason: "error",
|
|
1081
|
+
error: { code: failure.code, message: failure.message },
|
|
1082
|
+
}),
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
this.closed = true;
|
|
1086
|
+
this.checkBoundary();
|
|
1087
|
+
this.connection.ended(this);
|
|
1088
|
+
}
|
|
1089
|
+
/** The session ends: its idle compaction is off, and its own `/compact` settles. */
|
|
1090
|
+
endReports() {
|
|
1091
|
+
this.reports.dispose();
|
|
1092
|
+
this.ownCommandDone?.();
|
|
1093
|
+
this.ownCommandDone = undefined;
|
|
1094
|
+
}
|
|
1095
|
+
// --- State ---------------------------------------------------------------
|
|
1096
|
+
/**
|
|
1097
|
+
* Opens a turn, if none is open. `command` is the prompt that started it,
|
|
1098
|
+
* if one did.
|
|
1099
|
+
*/
|
|
1100
|
+
openTurn(command) {
|
|
1101
|
+
if (command !== undefined) {
|
|
1102
|
+
this.turnCommand = command;
|
|
1103
|
+
const local = this.localCommands.get(command);
|
|
1104
|
+
this.localCommands.delete(command);
|
|
1105
|
+
if (local)
|
|
1106
|
+
this.turnLocalCommand = { command: local, abort: new AbortController() };
|
|
1107
|
+
}
|
|
1108
|
+
if (this.foreground)
|
|
1109
|
+
return;
|
|
1110
|
+
this.foreground = true;
|
|
1111
|
+
this.lastEnd = undefined;
|
|
1112
|
+
this.output.resetAgentText();
|
|
1113
|
+
this.reports.turnStarted();
|
|
1114
|
+
this.reportState();
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Ends the open turn: its idle goes out with the turn's outcome. A turn
|
|
1118
|
+
* that waits for its plan's prompt in a fresh context goes on: its end is
|
|
1119
|
+
* that prompt's.
|
|
1120
|
+
*/
|
|
1121
|
+
closeTurn() {
|
|
1122
|
+
if (!this.foreground || this.clearContext.holdsTurn())
|
|
1123
|
+
return;
|
|
1124
|
+
// v2 asks for a final status of the turn's tool calls before its idle. A
|
|
1125
|
+
// tool call whose task goes on in the background is not part of the work.
|
|
1126
|
+
const cancelled = idleOutcome(this.lastEnd, this.cancelledWork).stopReason === "cancelled";
|
|
1127
|
+
this.output.closeUnfinished(cancelled, this.tasks.backgroundCalls(this.sessionId));
|
|
1128
|
+
if (cancelled) {
|
|
1129
|
+
// v2 asks to stop waiting for the stopped work's requests. Claude Code's
|
|
1130
|
+
// interrupt withdraws them, and this withdraws what it left open.
|
|
1131
|
+
for (const request of this.requests) {
|
|
1132
|
+
if (request.coveredByCancel)
|
|
1133
|
+
request.abort.abort();
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
this.reports.turnEnded();
|
|
1137
|
+
this.elicitations.turnEnded();
|
|
1138
|
+
this.fileChanges?.turnClosed(cancelled);
|
|
1139
|
+
this.foreground = false;
|
|
1140
|
+
this.reportState();
|
|
1141
|
+
this.cancelledWork = false;
|
|
1142
|
+
this.output.cancelled = false;
|
|
1143
|
+
this.lastEnd = undefined;
|
|
1144
|
+
this.turnCommand = undefined;
|
|
1145
|
+
this.turnReport.reset();
|
|
1146
|
+
const ownCommandDone = this.ownCommandDone;
|
|
1147
|
+
this.ownCommandDone = undefined;
|
|
1148
|
+
ownCommandDone?.();
|
|
1149
|
+
this.turnLocalCommand = undefined;
|
|
1150
|
+
this.checkBoundary();
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* While the turn waits on subagents, it is blocked when each of them is
|
|
1154
|
+
* (see `SessionTasks.foregroundBlocked`). Otherwise by the session's own
|
|
1155
|
+
* open requests.
|
|
1156
|
+
*/
|
|
1157
|
+
foregroundState() {
|
|
1158
|
+
if (!this.foreground)
|
|
1159
|
+
return "idle";
|
|
1160
|
+
const blocked = this.tasks.foregroundBlocked() ?? this.requests.size > 0;
|
|
1161
|
+
return blocked ? "requires_action" : "running";
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Reports the foreground state when it changed. `withdrawnByCancel`: the
|
|
1165
|
+
* change is the end of a request that a cancel withdrew, so the work is
|
|
1166
|
+
* stopping and its idle follows: no `running` goes out for it.
|
|
1167
|
+
*/
|
|
1168
|
+
reportState(withdrawnByCancel = false) {
|
|
1169
|
+
if (this.closed)
|
|
1170
|
+
return;
|
|
1171
|
+
const state = this.foregroundState();
|
|
1172
|
+
if (state === this.reportedState)
|
|
1173
|
+
return;
|
|
1174
|
+
// The client keeps `requires_action`: the next report sends `running`
|
|
1175
|
+
// if the work goes on after all, such as when the interrupt fails.
|
|
1176
|
+
if (withdrawnByCancel && state === "running")
|
|
1177
|
+
return;
|
|
1178
|
+
this.reportedState = state;
|
|
1179
|
+
const update = this.stateUpdate(state);
|
|
1180
|
+
this.send(update);
|
|
1181
|
+
const error = update.error;
|
|
1182
|
+
if (state === "idle" && error?.code === RequestError.authRequired().code) {
|
|
1183
|
+
this.connection.signedOut(this.sessionId);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
stateUpdate(state) {
|
|
1187
|
+
switch (state) {
|
|
1188
|
+
case "running":
|
|
1189
|
+
return { sessionUpdate: "state_update", state };
|
|
1190
|
+
case "requires_action":
|
|
1191
|
+
return { sessionUpdate: "state_update", state };
|
|
1192
|
+
default:
|
|
1193
|
+
return {
|
|
1194
|
+
sessionUpdate: "state_update",
|
|
1195
|
+
state,
|
|
1196
|
+
...idleOutcome(this.lastEnd, this.cancelledWork, this.turnReport, this.turnCommand !== undefined),
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
send(update) {
|
|
1201
|
+
this.sendNotification({ sessionId: this.sessionId, update });
|
|
1202
|
+
}
|
|
1203
|
+
/** Sends an update of the session or of a child, with its `background` list. */
|
|
1204
|
+
sendNotification(notification) {
|
|
1205
|
+
if (this.closed)
|
|
1206
|
+
return;
|
|
1207
|
+
this.connection.send(this.background.stamp(notification));
|
|
1208
|
+
}
|
|
1209
|
+
/** Fails the prompt `uuid` if it is not answered yet. Returns whether it was pending. */
|
|
1210
|
+
failPrompt(uuid, error) {
|
|
1211
|
+
const prompt = this.pending.get(uuid);
|
|
1212
|
+
if (!prompt)
|
|
1213
|
+
return false;
|
|
1214
|
+
this.pending.delete(uuid);
|
|
1215
|
+
this.localCommands.delete(uuid);
|
|
1216
|
+
this.fileChanges?.promptFailed(uuid, error);
|
|
1217
|
+
prompt.reject(error);
|
|
1218
|
+
this.checkBoundary();
|
|
1219
|
+
return true;
|
|
1220
|
+
}
|
|
1221
|
+
failPending(error) {
|
|
1222
|
+
for (const uuid of [...this.pending.keys()])
|
|
1223
|
+
this.failPrompt(uuid, error);
|
|
1224
|
+
}
|
|
137
1225
|
}
|
|
138
1226
|
/**
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
* is dropped. {@link v1McpServers} has already rejected every other transport.
|
|
1227
|
+
* Sends a request to the client unless `signal` aborted already. The ACP SDK
|
|
1228
|
+
* would send it anyway, then withdraw it with `$/cancel_request`.
|
|
142
1229
|
*/
|
|
143
|
-
function
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
}
|
|
148
|
-
if (v2.McpServer.isHttp(server)) {
|
|
149
|
-
return { ...server, headers: server.headers ?? [] };
|
|
150
|
-
}
|
|
151
|
-
throw new Error(`Unreachable: MCP server of type ${server.type} passed the transport check`);
|
|
1230
|
+
function unlessWithdrawn(signal, send) {
|
|
1231
|
+
if (signal.aborted)
|
|
1232
|
+
return Promise.reject(new Error("The request was withdrawn"));
|
|
1233
|
+
return send();
|
|
152
1234
|
}
|