opencode-acp-client 0.0.0-stage → 0.1.0

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.
Files changed (55) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +220 -2
  3. package/README.zh.md +199 -0
  4. package/dist/acp/capabilities.d.ts +168 -0
  5. package/dist/acp/capabilities.js +240 -0
  6. package/dist/acp/capabilities.js.map +1 -0
  7. package/dist/acp/client.d.ts +241 -0
  8. package/dist/acp/client.js +767 -0
  9. package/dist/acp/client.js.map +1 -0
  10. package/dist/acp/types.d.ts +228 -0
  11. package/dist/acp/types.js +23 -0
  12. package/dist/acp/types.js.map +1 -0
  13. package/dist/acp-replay.d.ts +60 -0
  14. package/dist/acp-replay.js +188 -0
  15. package/dist/acp-replay.js.map +1 -0
  16. package/dist/contract.d.ts +435 -0
  17. package/dist/contract.js +126 -0
  18. package/dist/contract.js.map +1 -0
  19. package/dist/daemons.d.ts +39 -0
  20. package/dist/daemons.js +112 -0
  21. package/dist/daemons.js.map +1 -0
  22. package/dist/index.d.ts +268 -0
  23. package/dist/index.js +1882 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/opencode-bin.d.ts +73 -0
  26. package/dist/opencode-bin.js +109 -0
  27. package/dist/opencode-bin.js.map +1 -0
  28. package/dist/project.d.ts +81 -0
  29. package/dist/project.js +230 -0
  30. package/dist/project.js.map +1 -0
  31. package/dist/server.d.ts +743 -0
  32. package/dist/server.js +5029 -0
  33. package/dist/server.js.map +1 -0
  34. package/dist/session-map.d.ts +89 -0
  35. package/dist/session-map.js +305 -0
  36. package/dist/session-map.js.map +1 -0
  37. package/dist/sessions-command.d.ts +70 -0
  38. package/dist/sessions-command.js +188 -0
  39. package/dist/sessions-command.js.map +1 -0
  40. package/dist/sse.d.ts +40 -0
  41. package/dist/sse.js +147 -0
  42. package/dist/sse.js.map +1 -0
  43. package/dist/state.d.ts +161 -0
  44. package/dist/state.js +135 -0
  45. package/dist/state.js.map +1 -0
  46. package/dist/subagent-sessions.d.ts +71 -0
  47. package/dist/subagent-sessions.js +107 -0
  48. package/dist/subagent-sessions.js.map +1 -0
  49. package/dist/translate/events.d.ts +231 -0
  50. package/dist/translate/events.js +1244 -0
  51. package/dist/translate/events.js.map +1 -0
  52. package/dist/upgrade.d.ts +56 -0
  53. package/dist/upgrade.js +162 -0
  54. package/dist/upgrade.js.map +1 -0
  55. package/package.json +66 -4
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Capability negotiation and graceful degradation.
3
+ *
4
+ * The whole point of this file: **ACP agents are not interchangeable.** Some
5
+ * implement a rich superset; others (notably the backend's built-in ACP) implement the
6
+ * bare minimum and silently fail — or worse, hang — if you call something they
7
+ * never advertised.
8
+ *
9
+ * So every optional interaction goes through here first, and anything we must
10
+ * decline is declined *explicitly* (a JSON-RPC error or a cancelled outcome)
11
+ * rather than left unanswered. An unanswered request is a hang; a declined one
12
+ * is recoverable.
13
+ */
14
+ import type { InitializeResponse } from './types.js';
15
+ /** What we learned from `initialize`, normalised to booleans we can trust. */
16
+ export interface EffectiveCapabilities {
17
+ /** Agent can replay history for an existing session id. Often false. */
18
+ loadSession: boolean;
19
+ /**
20
+ * Agent supports `session/list`. ACP says a client MUST NOT call it without
21
+ * this gate, so it is a hard boolean rather than "best effort".
22
+ */
23
+ listSessions: boolean;
24
+ /**
25
+ * Agent supports `session/resume` — reconnect to an existing session *without*
26
+ * replaying history. Also a MUST NOT gate: ACP says clients must not call
27
+ * `session/resume` unless `sessionCapabilities.resume` is present.
28
+ *
29
+ * This is the capability that decides what a restored tab looks like on an
30
+ * agent that has no `session/load` (the backend's plain ACP profile is one):
31
+ * resume keeps the agent's context, but no transcript arrives, so the screen
32
+ * starts empty by design rather than by failure.
33
+ */
34
+ resumeSessions: boolean;
35
+ /** Agent accepts image content blocks in a prompt. */
36
+ images: boolean;
37
+ /** Agent accepts audio content blocks in a prompt. */
38
+ audio: boolean;
39
+ /** Agent accepts embedded resources (file contents) in a prompt. */
40
+ embeddedContext: boolean;
41
+ /** The agent offers `opencode/child-session-updates`. */
42
+ childSessionUpdates: boolean;
43
+ /** Whether the agent told us anything at all. */
44
+ reported: boolean;
45
+ /**
46
+ * What to call this agent in the UI. Put together by `displayName()` below: the
47
+ * agent's own `agentInfo.title` (ACP: "intended for UI… human-readable"), else its
48
+ * `agentInfo.name`, else `unknown` — `BridgeServer` then falls back to the launch
49
+ * command, which is always true and reproducible.
50
+ */
51
+ agentName: string;
52
+ /** `agentInfo.name`: the programmatic id, kept for logs and diagnostics. */
53
+ agentId?: string;
54
+ }
55
+ /**
56
+ * The profile of an agent that has not answered `initialize` yet (or answered
57
+ * uselessly). Exported because there must be exactly ONE such literal: a second
58
+ * hand-written copy in `AcpClient` went stale the moment a field was added.
59
+ */
60
+ export declare const NO_CAPABILITIES: EffectiveCapabilities;
61
+ /**
62
+ * Normalise an `initialize` result. Anything missing is *false*, never
63
+ * "probably fine": opting into an unimplemented feature is how you get a hang.
64
+ */
65
+ export declare function effectiveCapabilities(result: InitializeResponse | undefined): EffectiveCapabilities;
66
+ /**
67
+ * The name to show for an agent, per ACP's `Implementation` fields.
68
+ *
69
+ * `title` is "intended for UI and end-user contexts — optimized to be human-readable,
70
+ * easily understood. If not provided, the name should be used for display", while
71
+ * `name` is for "programmatic or logical use". We used to read `name` only, so an agent
72
+ * that titled itself nicely still appeared as its id.
73
+ */
74
+ export declare function displayName(info: {
75
+ name?: unknown;
76
+ title?: unknown;
77
+ } | undefined): string;
78
+ /** One thing the caller wanted to do, and whether the agent allows it. */
79
+ export interface CapabilityDecision {
80
+ allowed: boolean;
81
+ /** Human-readable reason, used in the HTTP error and the logs. */
82
+ reason: string;
83
+ }
84
+ export declare function canLoadSession(caps: EffectiveCapabilities): CapabilityDecision;
85
+ /**
86
+ * ACP: "Clients **MUST NOT** attempt to call `session/list`" without
87
+ * `sessionCapabilities.list`. Callers that can degrade (a title lookup, a
88
+ * `--session latest` probe) treat a refusal as "no sessions known".
89
+ */
90
+ export declare function canListSessions(caps: EffectiveCapabilities): CapabilityDecision;
91
+ /**
92
+ * ACP: "Before attempting to resume a session, Clients **MUST** verify that the
93
+ * Agent supports this capability by checking the `sessionCapabilities.resume`
94
+ * field in the `initialize` response … If `sessionCapabilities.resume` is not
95
+ * present, the Agent does not support resuming sessions and Clients **MUST NOT**
96
+ * attempt to call `session/resume`."
97
+ *
98
+ * We called it unconditionally once. The backend happened to advertise `resume`,
99
+ * so nothing broke; an agent that advertises neither `resume` nor `loadSession`
100
+ * answered method-not-found, and the rejection escaped into the session-startup
101
+ * path with no session and no visible reason.
102
+ */
103
+ export declare function canResumeSession(caps: EffectiveCapabilities): CapabilityDecision;
104
+ /**
105
+ * Prompt content blocks an agent may reject. We drop unsupported blocks rather
106
+ * than forwarding them, because several agents either error out or (worse)
107
+ * accept and then stall when they hit a block type they cannot render.
108
+ */
109
+ export declare function filterPromptBlocks(blocks: Array<{
110
+ type: string;
111
+ [k: string]: unknown;
112
+ }>, caps: EffectiveCapabilities): {
113
+ kept: Array<{
114
+ type: string;
115
+ [k: string]: unknown;
116
+ }>;
117
+ dropped: string[];
118
+ };
119
+ /**
120
+ * Exactly what we announce as `clientCapabilities` in `initialize`.
121
+ *
122
+ * Kept here so the announcement and the code that honours it are read together.
123
+ * The rule is strict, and it is the reason this is a constant
124
+ * rather than an inline literal: **a capability is a promise the agent may act
125
+ * on.** Announcing one we cannot service means the agent will call it and we
126
+ * will answer with an error (or worse, hang it), so nothing goes in here without
127
+ * a path behind it.
128
+ *
129
+ * | announced | path |
130
+ * |---|---|
131
+ * | `elicitation.form` | `AcpClient.onRequest('elicitation/create')` → `BridgeServer.awaitElicitation` → GET/POST `/api/session/:id/form` (the TUI's own form UI) |
132
+ *
133
+ * Deliberately **absent**, each for a concrete reason:
134
+ * - `elicitation.url` — there is no browser surface to open, and the spec forbids
135
+ * falling back to form mode for the sensitive flows url mode exists for.
136
+ * - `fs.readTextFile` / `fs.writeTextFile` / `terminal` — not implemented; the
137
+ * agent should use its own tools (see `clientCallbackSupport`).
138
+ * - `session.notices` / `session.compaction` — opencode v2 has no surface for
139
+ * them, so announcing would only produce `notice` / `compaction_*` updates
140
+ * that nothing renders.
141
+ * - `session.configOptions.boolean` — the spec only lets an agent emit a
142
+ * `type: "boolean"` option once the client advertises it, and the TUI's picker
143
+ * renders `select` options only (`/api/model` → the model panel); there is no
144
+ * boolean control in it. Announcing would either promise a control that does
145
+ * not exist or force a rewrite of the agent's boolean into a two-choice select.
146
+ * An agent that needs older clients omits the option or offers a `select`
147
+ * fallback (the spec says so itself), so leaving it out costs nothing.
148
+ */
149
+ export declare const CLIENT_CAPABILITIES: {
150
+ readonly elicitation: {
151
+ readonly form: {};
152
+ };
153
+ readonly _meta: {
154
+ readonly terminal_output: true;
155
+ readonly 'opencode/child-session-updates': true;
156
+ };
157
+ };
158
+ /**
159
+ * Whether we are willing to service an agent→client callback.
160
+ *
161
+ * We advertise neither `fs` nor `terminal`, so a well-behaved agent will not call
162
+ * them. A non-conforming one might anyway; we answer with an explicit error so it
163
+ * can fall back instead of waiting forever.
164
+ */
165
+ export declare function clientCallbackSupport(method: string): {
166
+ supported: boolean;
167
+ reason: string;
168
+ };
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Capability negotiation and graceful degradation.
3
+ *
4
+ * The whole point of this file: **ACP agents are not interchangeable.** Some
5
+ * implement a rich superset; others (notably the backend's built-in ACP) implement the
6
+ * bare minimum and silently fail — or worse, hang — if you call something they
7
+ * never advertised.
8
+ *
9
+ * So every optional interaction goes through here first, and anything we must
10
+ * decline is declined *explicitly* (a JSON-RPC error or a cancelled outcome)
11
+ * rather than left unanswered. An unanswered request is a hang; a declined one
12
+ * is recoverable.
13
+ */
14
+ /**
15
+ * The profile of an agent that has not answered `initialize` yet (or answered
16
+ * uselessly). Exported because there must be exactly ONE such literal: a second
17
+ * hand-written copy in `AcpClient` went stale the moment a field was added.
18
+ */
19
+ export const NO_CAPABILITIES = {
20
+ loadSession: false,
21
+ listSessions: false,
22
+ resumeSessions: false,
23
+ images: false,
24
+ audio: false,
25
+ embeddedContext: false,
26
+ reported: false,
27
+ childSessionUpdates: false,
28
+ agentName: 'unknown',
29
+ };
30
+ /**
31
+ * Normalise an `initialize` result. Anything missing is *false*, never
32
+ * "probably fine": opting into an unimplemented feature is how you get a hang.
33
+ */
34
+ export function effectiveCapabilities(result) {
35
+ if (!result || typeof result !== 'object') {
36
+ // Some agents return nothing useful. Treat as the minimal profile.
37
+ return { ...NO_CAPABILITIES };
38
+ }
39
+ const caps = result.agentCapabilities ?? {};
40
+ const prompt = caps.promptCapabilities ?? {};
41
+ // ACP: present and non-null means supported; omitted or null means not.
42
+ const sessionCaps = caps.sessionCapabilities ?? {};
43
+ const agentMeta = caps._meta ?? {};
44
+ return {
45
+ loadSession: caps.loadSession === true,
46
+ listSessions: sessionCaps.list !== undefined && sessionCaps.list !== null,
47
+ resumeSessions: sessionCaps.resume !== undefined && sessionCaps.resume !== null,
48
+ images: prompt.image === true,
49
+ audio: prompt.audio === true,
50
+ embeddedContext: prompt.embeddedContext === true,
51
+ reported: result.agentCapabilities !== undefined,
52
+ childSessionUpdates: agentMeta['opencode/child-session-updates'] === true,
53
+ agentName: displayName(result.agentInfo),
54
+ ...(result.agentInfo?.name ? { agentId: result.agentInfo.name } : {}),
55
+ };
56
+ }
57
+ /**
58
+ * The name to show for an agent, per ACP's `Implementation` fields.
59
+ *
60
+ * `title` is "intended for UI and end-user contexts — optimized to be human-readable,
61
+ * easily understood. If not provided, the name should be used for display", while
62
+ * `name` is for "programmatic or logical use". We used to read `name` only, so an agent
63
+ * that titled itself nicely still appeared as its id.
64
+ */
65
+ export function displayName(info) {
66
+ const title = typeof info?.title === 'string' ? info.title.trim() : '';
67
+ if (title)
68
+ return title;
69
+ const name = typeof info?.name === 'string' ? info.name.trim() : '';
70
+ return name || 'unknown';
71
+ }
72
+ export function canLoadSession(caps) {
73
+ return caps.loadSession
74
+ ? { allowed: true, reason: 'agent advertises loadSession' }
75
+ : {
76
+ allowed: false,
77
+ reason: 'agent does not advertise session/load; history cannot be replayed. ' +
78
+ 'The bridge will start a fresh agent session instead of failing the request.',
79
+ };
80
+ }
81
+ /**
82
+ * ACP: "Clients **MUST NOT** attempt to call `session/list`" without
83
+ * `sessionCapabilities.list`. Callers that can degrade (a title lookup, a
84
+ * `--session latest` probe) treat a refusal as "no sessions known".
85
+ */
86
+ export function canListSessions(caps) {
87
+ return caps.listSessions
88
+ ? { allowed: true, reason: 'agent advertises sessionCapabilities.list' }
89
+ : {
90
+ allowed: false,
91
+ reason: 'agent does not advertise sessionCapabilities.list; session/list must not be called',
92
+ };
93
+ }
94
+ /**
95
+ * ACP: "Before attempting to resume a session, Clients **MUST** verify that the
96
+ * Agent supports this capability by checking the `sessionCapabilities.resume`
97
+ * field in the `initialize` response … If `sessionCapabilities.resume` is not
98
+ * present, the Agent does not support resuming sessions and Clients **MUST NOT**
99
+ * attempt to call `session/resume`."
100
+ *
101
+ * We called it unconditionally once. The backend happened to advertise `resume`,
102
+ * so nothing broke; an agent that advertises neither `resume` nor `loadSession`
103
+ * answered method-not-found, and the rejection escaped into the session-startup
104
+ * path with no session and no visible reason.
105
+ */
106
+ export function canResumeSession(caps) {
107
+ return caps.resumeSessions
108
+ ? { allowed: true, reason: 'agent advertises sessionCapabilities.resume' }
109
+ : {
110
+ allowed: false,
111
+ reason: 'agent does not advertise sessionCapabilities.resume; session/resume must not be called',
112
+ };
113
+ }
114
+ /**
115
+ * Prompt content blocks an agent may reject. We drop unsupported blocks rather
116
+ * than forwarding them, because several agents either error out or (worse)
117
+ * accept and then stall when they hit a block type they cannot render.
118
+ */
119
+ export function filterPromptBlocks(blocks, caps) {
120
+ const dropped = [];
121
+ const kept = blocks.filter((b) => {
122
+ switch (b.type) {
123
+ case 'image':
124
+ if (!caps.images) {
125
+ dropped.push('image');
126
+ return false;
127
+ }
128
+ return true;
129
+ case 'audio':
130
+ if (!caps.audio) {
131
+ dropped.push('audio');
132
+ return false;
133
+ }
134
+ return true;
135
+ case 'resource':
136
+ if (!caps.embeddedContext) {
137
+ dropped.push(b.type);
138
+ return false;
139
+ }
140
+ return true;
141
+ case 'resource_link':
142
+ // Baseline in ACP: every agent must handle a *link* to a resource; only
143
+ // embedded content (`resource`, file contents inline) needs the
144
+ // `embeddedContext` capability.
145
+ return true;
146
+ case 'text':
147
+ return true;
148
+ default:
149
+ // A block type we do not know cannot be forwarded honestly: the agent's
150
+ // schema may reject it and take the whole turn down. Drop it and let the
151
+ // caller log it — the same path image/audio take.
152
+ dropped.push(b.type);
153
+ return false;
154
+ }
155
+ });
156
+ return { kept, dropped };
157
+ }
158
+ /**
159
+ * Exactly what we announce as `clientCapabilities` in `initialize`.
160
+ *
161
+ * Kept here so the announcement and the code that honours it are read together.
162
+ * The rule is strict, and it is the reason this is a constant
163
+ * rather than an inline literal: **a capability is a promise the agent may act
164
+ * on.** Announcing one we cannot service means the agent will call it and we
165
+ * will answer with an error (or worse, hang it), so nothing goes in here without
166
+ * a path behind it.
167
+ *
168
+ * | announced | path |
169
+ * |---|---|
170
+ * | `elicitation.form` | `AcpClient.onRequest('elicitation/create')` → `BridgeServer.awaitElicitation` → GET/POST `/api/session/:id/form` (the TUI's own form UI) |
171
+ *
172
+ * Deliberately **absent**, each for a concrete reason:
173
+ * - `elicitation.url` — there is no browser surface to open, and the spec forbids
174
+ * falling back to form mode for the sensitive flows url mode exists for.
175
+ * - `fs.readTextFile` / `fs.writeTextFile` / `terminal` — not implemented; the
176
+ * agent should use its own tools (see `clientCallbackSupport`).
177
+ * - `session.notices` / `session.compaction` — opencode v2 has no surface for
178
+ * them, so announcing would only produce `notice` / `compaction_*` updates
179
+ * that nothing renders.
180
+ * - `session.configOptions.boolean` — the spec only lets an agent emit a
181
+ * `type: "boolean"` option once the client advertises it, and the TUI's picker
182
+ * renders `select` options only (`/api/model` → the model panel); there is no
183
+ * boolean control in it. Announcing would either promise a control that does
184
+ * not exist or force a rewrite of the agent's boolean into a two-choice select.
185
+ * An agent that needs older clients omits the option or offers a `select`
186
+ * fallback (the spec says so itself), so leaving it out costs nothing.
187
+ */
188
+ export const CLIENT_CAPABILITIES = {
189
+ elicitation: { form: {} },
190
+ // ★ `_meta` is ACP's open extension point, and `terminal_output` is the one entry every
191
+ // ACP client that renders a shell card agrees on: Zed announces exactly this pair
192
+ // (`crates/agent_servers/src/acp/v1.rs`, `client_capabilities_for_agent`:
193
+ // `("terminal_output", true)`), and agents branch on it — some agents keep
194
+ // `const terminalOutputMode = () => clientCaps._meta?.['terminal_output'] === true
195
+ // ? 'terminal_output' : 'terminal_output_delta'`, and only the first form carries the
196
+ // finished command output (`_meta.terminal_output.data`). Without the announcement the
197
+ // agent sends a delta dialect nothing here reads, so the card falls back to its
198
+ // `rawOutput` and shows a JSON record. Announcing it is a negotiation, not a guess:
199
+ // the path that honours it is `toolOutput()` in `translate/events.ts`. It is NOT the
200
+ // `terminal/*` capability below — that one is agent→client *methods*, which we still do
201
+ // not implement and still do not announce.
202
+ // ★ `opencode/child-session-updates` is opencode's negotiated extension for a
203
+ // delegated run's OWN event stream: with it, `opencode acp` sends
204
+ // `opencode/session/child_update` notifications carrying the child's id, its depth,
205
+ // its title and the child's own `session/update` frames. The bridge announces it
206
+ // because it has a path for it (`subagent-sessions.ts`), and only acts when the agent
207
+ // lists it in `agentCapabilities._meta`. Same kind of negotiation as `terminal_output`
208
+ // above: the key is the extension's own name, taken from the adapter
209
+ // (`packages/cli/src/acp/event.ts`), not invented here.
210
+ _meta: { terminal_output: true, 'opencode/child-session-updates': true },
211
+ };
212
+ /**
213
+ * Whether we are willing to service an agent→client callback.
214
+ *
215
+ * We advertise neither `fs` nor `terminal`, so a well-behaved agent will not call
216
+ * them. A non-conforming one might anyway; we answer with an explicit error so it
217
+ * can fall back instead of waiting forever.
218
+ */
219
+ export function clientCallbackSupport(method) {
220
+ if (method === 'elicitation/create') {
221
+ return {
222
+ supported: true,
223
+ reason: 'form mode only; the mode is checked before the handler runs',
224
+ };
225
+ }
226
+ if (method.startsWith('fs/')) {
227
+ return {
228
+ supported: false,
229
+ reason: 'this bridge does not advertise filesystem capabilities; use the agent’s own tools',
230
+ };
231
+ }
232
+ if (method.startsWith('terminal/')) {
233
+ return {
234
+ supported: false,
235
+ reason: 'this bridge does not advertise terminal capabilities; use the agent’s own tools',
236
+ };
237
+ }
238
+ return { supported: true, reason: '' };
239
+ }
240
+ //# sourceMappingURL=capabilities.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capabilities.js","sourceRoot":"","sources":["../../src/acp/capabilities.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AA6CH;;;;GAIG;AACH,MAAM,CAAC,MAAM,eAAe,GAA0B;IACpD,WAAW,EAAE,KAAK;IAClB,YAAY,EAAE,KAAK;IACnB,cAAc,EAAE,KAAK;IACrB,MAAM,EAAE,KAAK;IACb,KAAK,EAAE,KAAK;IACZ,eAAe,EAAE,KAAK;IACtB,QAAQ,EAAE,KAAK;IACf,mBAAmB,EAAE,KAAK;IAC1B,SAAS,EAAE,SAAS;CACrB,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAAsC;IAC1E,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC1C,mEAAmE;QACnE,OAAO,EAAE,GAAG,eAAe,EAAE,CAAC;IAChC,CAAC;IACD,MAAM,IAAI,GAAsB,MAAM,CAAC,iBAAiB,IAAI,EAAE,CAAC;IAC/D,MAAM,MAAM,GAAG,IAAI,CAAC,kBAAkB,IAAI,EAAE,CAAC;IAC7C,wEAAwE;IACxE,MAAM,WAAW,GAAG,IAAI,CAAC,mBAAmB,IAAI,EAAE,CAAC;IACnD,MAAM,SAAS,GAAI,IAA4C,CAAC,KAAK,IAAI,EAAE,CAAC;IAC5E,OAAO;QACL,WAAW,EAAE,IAAI,CAAC,WAAW,KAAK,IAAI;QACtC,YAAY,EAAE,WAAW,CAAC,IAAI,KAAK,SA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AAS,EAAE,KAAK;YAChB,MAAM,EAAE,mFAAmF;SAC5F,CAAC;IACJ,CAAC;IACD,IAAI,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;QACnC,OAAO;YACL,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,iFAAiF;SAC1F,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;AACzC,CAAC"}
@@ -0,0 +1,241 @@
1
+ /**
2
+ * ACP client: spawns an agent process and speaks ACP JSON-RPC over stdio.
3
+ *
4
+ * Two rules drive the whole implementation:
5
+ *
6
+ * 1. **Every inbound request gets an answer.** An ACP agent that asks us
7
+ * something and hears nothing will wait forever. So anything we cannot
8
+ * service is answered with an explicit JSON-RPC error, never dropped.
9
+ * 2. **Timeouts are mandatory.** Several agents have bugs where a request
10
+ * simply never resolves. Without a timeout the HTTP request waiting on it
11
+ * would hang for the lifetime of the process.
12
+ */
13
+ import type { ChildSessionEvent } from '../subagent-sessions.js';
14
+ /** `opencode acp`'s notification for one event in a delegated run (see subagent-sessions). */
15
+ export declare const CHILD_UPDATE_METHOD = "opencode/session/child_update";
16
+ import { EventEmitter } from 'node:events';
17
+ import { type EffectiveCapabilities } from './capabilities.js';
18
+ import type { ContentBlock, ElicitationRequest, ElicitationResponse, PromptResponse, RequestPermissionRequest, RequestPermissionResponse, SessionConfigOption, SessionNewResponse, SessionUpdate } from './types.js';
19
+ export interface AcpClientOptions {
20
+ /** Command to spawn, `my-agent` or `npx`. */
21
+ command: string;
22
+ args?: string[];
23
+ cwd?: string;
24
+ env?: Record<string, string | undefined>;
25
+ /** How long to wait for any single JSON-RPC response. */
26
+ requestTimeoutMs?: number;
27
+ /**
28
+ * Timeout for `session/prompt` specifically.
29
+ *
30
+ * One timeout for everything was wrong: `initialize` and `session/new` answer in
31
+ * milliseconds, while a prompt is a *task* — an agent may work through a dozen
32
+ * tool calls without touching the wire, and 120s of silence is normal for real
33
+ * work. Measured case: a review task with 20+ tool calls was killed mid-flight by
34
+ * the request timeout, and the turn ended with `timed out waiting for
35
+ * session/prompt` while the agent was still working.
36
+ */
37
+ promptTimeoutMs?: number;
38
+ /** Protocol revision we claim. Agents negotiate down. */
39
+ protocolVersion?: number;
40
+ /** Sink for diagnostics; never written to stdout (that is the ACP wire). */
41
+ onLog?: (line: string) => void;
42
+ }
43
+ export interface AcpEvents {
44
+ /** A `session/update` notification. */
45
+ update: [sessionId: string, update: SessionUpdate];
46
+ /** The agent exited; no further calls will succeed. */
47
+ exit: [{
48
+ code: number | null;
49
+ signal: string | null;
50
+ }];
51
+ /**
52
+ * One event of a delegated run (`opencode/session/child_update`), keyed by the ROOT
53
+ * session so it lands on the transcript that owns the subagent card.
54
+ */
55
+ child: [rootSessionId: string, event: ChildSessionEvent];
56
+ /** Diagnostics. */
57
+ log: [line: string];
58
+ }
59
+ /** Raised when the agent answered with a JSON-RPC error. */
60
+ export declare class AcpError extends Error {
61
+ readonly code: number | string;
62
+ constructor(message: string, code?: number | string);
63
+ }
64
+ /** The agent does not implement the method we called. */
65
+ export declare class AcpMethodNotFound extends AcpError {
66
+ constructor(method: string);
67
+ }
68
+ export declare class AcpClient extends EventEmitter<AcpEvents> {
69
+ private readonly options;
70
+ private readonly child;
71
+ private readonly pending;
72
+ private readonly timeoutMs;
73
+ private readonly promptTimeoutMs;
74
+ private readonly protocolVersion;
75
+ private nextId;
76
+ private buffer;
77
+ private closed;
78
+ private caps;
79
+ private agentVersion;
80
+ private pendingRecordedFrames;
81
+ private recordFlushed;
82
+ private recordFile;
83
+ /** Permission requests the agent is currently blocked on. */
84
+ private permissionHandler;
85
+ /** `elicitation/create` — the agent asking the user something. */
86
+ private elicitationHandler;
87
+ constructor(options: AcpClientOptions);
88
+ get capabilities(): EffectiveCapabilities;
89
+ /** Register the handler used to resolve `session/request_permission`. */
90
+ onPermission(handler: (req: RequestPermissionRequest) => Promise<RequestPermissionResponse>): void;
91
+ /**
92
+ * Register the handler used to answer `elicitation/create`.
93
+ *
94
+ * Only ever called for `mode: "form"` — the mode we advertise. The handler may
95
+ * throw to refuse the request outright; that becomes a JSON-RPC error, which is
96
+ * the honest answer when the requested schema cannot be rendered.
97
+ */
98
+ onElicitation(handler: (req: ElicitationRequest) => Promise<ElicitationResponse>): void;
99
+ /**
100
+ * `initialize`. Failure here is fatal: without it we do not know what the
101
+ * agent supports, and guessing is how hangs happen.
102
+ */
103
+ initialize(): Promise<EffectiveCapabilities>;
104
+ newSession(cwd: string): Promise<SessionNewResponse>;
105
+ /**
106
+ * Per-SESSION catalogs: the config options and the standard `models` list are
107
+ * session-scoped in ACP (`session/new`/`load`/`resume` each carry their own), so
108
+ * they are kept per session id rather than in one field. One field was fine while
109
+ * one client meant one session; a shared connection would let the newest session's
110
+ * defaults (and a `set_config_option` meant for another session) leak across.
111
+ */
112
+ private catalogs;
113
+ private lastSessionId;
114
+ /** (Re)select a session's catalog state, remembering it as the most recent one. */
115
+ private catalog;
116
+ /** The options a given session advertised; omitted = the most recently touched one. */
117
+ configOptionsFor(sessionId?: string): SessionConfigOption[];
118
+ /** Any session on this connection advertised a catalog (pool-aware). */
119
+ hasCatalog(): boolean;
120
+ /**
121
+ * The ACP-standard model list: `models: {currentModelId, availableModels[]}`.
122
+ *
123
+ * Agents that use it (qwen, and per the ecosystem survey gemini and kimi) put their
124
+ * models here rather than in an opencode-shaped `configOptions` entry — we ignored
125
+ * the field entirely, so their model picker came up empty (`/api/model` stayed on the
126
+ * `acp/default` placeholder) even though the agent had just told us every model it
127
+ * has. Measured: qwen --acp returns four models this way.
128
+ */
129
+ private noteStandardModels;
130
+ get configOptions(): SessionConfigOption[];
131
+ /**
132
+ * `session/load`. Caller must check `capabilities.loadSession` first.
133
+ * Agents without `loadSession` get an explicit, catchable error.
134
+ */
135
+ loadSession(sessionId: string, cwd: string): Promise<void>;
136
+ /**
137
+ * `session/resume`. ACP defines it as "reconnect to an existing session WITHOUT
138
+ * replaying history" — and that is all it promises.
139
+ *
140
+ * Measured on the backend's plain ACP profile (2026-10-17, probes in
141
+ * docs/KNOWN-ISSUES.md): the call succeeds, the response carries configOptions, no
142
+ * updates follow, and the next turn runs. Whether the agent's model actually still
143
+ * has the earlier conversation was **not consistent**: the same profile answered
144
+ * "there's no word I was asked to remember in this conversation" under one model
145
+ * and recalled the word correctly under another.
146
+ *
147
+ * So describe only what is guaranteed: same session id, empty transcript, and the
148
+ * conversation's continuity left to the agent. Never promise that context survived.
149
+ */
150
+ resumeSession(sessionId: string, cwd: string): Promise<SessionNewResponse>;
151
+ /**
152
+ * `session/list`. the backend returns `{sessionId, cwd}` entries newest first, 100 per
153
+ * page with a cursor. An unpaginated read only ever sees recent sessions — for a
154
+ * directory whose sessions are all older, a "latest" lookup finds nothing.
155
+ */
156
+ listSessions(cwd: string, maxPages?: number): Promise<Array<{
157
+ sessionId: string;
158
+ cwd: string;
159
+ title?: string;
160
+ }>>;
161
+ prompt(sessionId: string, prompt: ContentBlock[]): Promise<PromptResponse>;
162
+ /**
163
+ * `session/set_config_option`. the backend advertises models through a config option
164
+ * (`id: "model"`), so this is how a model switch reaches the agent.
165
+ *
166
+ * Returns the config state the agent answered with: the spec requires the
167
+ * response to carry the **complete** list, which is how dependent changes
168
+ * (reasoning options that follow the model, for instance) reach us at all.
169
+ */
170
+ /**
171
+ * Tell the agent a session is gone (`session/delete`, a stable agent method).
172
+ *
173
+ * Without this the agent keeps the session it created: the bridge forgets it, the
174
+ * UI forgets it, and the agent's own store keeps growing. Best-effort by design —
175
+ * the user asked to delete, and that must succeed locally even if the agent cannot
176
+ * honour it.
177
+ */
178
+ deleteSession(sessionId: string): Promise<void>;
179
+ /**
180
+ * The spelling `set_model` expects for a model the caller names by its bare id.
181
+ *
182
+ * An agent that publishes `models.availableModels` may append a variant to the id
183
+ * (`deepseek-flash[high]`) while `configOptions` offers the bare one; the two
184
+ * methods accept different spellings (see `setConfig`). Match on the bare part and
185
+ * return the standard list's own string, so neither the picker nor the wire has to
186
+ * know which surface the user clicked on.
187
+ */
188
+ private resolveStandardModelId;
189
+ setConfig(sessionId: string, configId: string, value: string): Promise<SessionConfigOption[]>;
190
+ /**
191
+ * Replace the session's config options.
192
+ *
193
+ * Used for both halves of the negotiation: the reply to a `set_config_option`,
194
+ * and an agent-pushed `config_option_update` (the spec sends the complete state
195
+ * in both, so replacing is correct — merging would keep stale values alive).
196
+ */
197
+ applyConfigOptions(sessionId: string, options: SessionConfigOption[] | undefined): void;
198
+ /** `session/cancel` is a notification: fire and forget, per the spec. */
199
+ cancel(sessionId: string): void;
200
+ /** Terminate the agent. Safe to call repeatedly. */
201
+ /** Signal the agent AND its descendants (one process group on POSIX). */
202
+ private killGroup;
203
+ dispose(): Promise<void>;
204
+ private onStdout;
205
+ /**
206
+ * `OPENCODE_ACP_CLIENT_RECORD_FRAMES=<dir>`: append every inbound frame to
207
+ * `<dir>/<backend>.jsonl`, headed by a provenance line.
208
+ *
209
+ * A recorded turn is the only fixture that carries a REAL agent's shapes — the
210
+ * synthetic fake agent can only exercise shapes we thought of. The corpus format
211
+ * follows KiroCrew's: the first line is `_meta` (backend, recorded, date,
212
+ * agent_version) and every line after it is the wire verbatim, so a replay can
213
+ * be weighed against what produced it. Recording never breaks the wire: a
214
+ * write failure is logged and dropped.
215
+ */
216
+ private recordFrame;
217
+ /** Write the buffered frames (header first) once the backend is known. */
218
+ private flushRecordedFrames;
219
+ private onMessage;
220
+ private onNotification;
221
+ /**
222
+ * Agent→client request. This is where "answer everything" matters most:
223
+ * an unhandled request is a deadlock, and a *silently* unhandled one is the
224
+ * hardest class of bug to find later.
225
+ */
226
+ private onRequest;
227
+ private request;
228
+ private notify;
229
+ private respond;
230
+ private respondError;
231
+ private write;
232
+ private failAll;
233
+ }
234
+ /**
235
+ * The `taskkill` arguments that end an agent AND its descendants on Windows.
236
+ *
237
+ * Windows has no signalable process groups, so the portable `process.kill(-pid)`
238
+ * has nothing to do; `taskkill /T` is the tree walk. `/F` is the force step: the
239
+ * SIGKILL pass uses it, the SIGTERM pass lets the app close first.
240
+ */
241
+ export declare function windowsKillArgs(pid: number, signal: NodeJS.Signals): string[];