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,743 @@
1
+ /**
2
+ * HTTP surface: an opencode v2 compatible server in front of one ACP agent.
3
+ *
4
+ * Route shapes come from opencode's own TUI test fixture plus the backend-oc's proven
5
+ * bridge, so the *contract* is observed rather than guessed. The boot routes
6
+ * below return deliberately boring values — the goal is that the client starts
7
+ * and opens a session, not that every panel is populated yet. Anything the
8
+ * client asks that we do not implement is answered with a truthful empty value
9
+ * rather than a 404, because several client screens treat 404 as fatal.
10
+ */
11
+ /** Exported for the tests: the accepted spellings are the contract with agents. */
12
+ export declare function modelValueParts(value: string): {
13
+ providerID?: string;
14
+ modelID: string;
15
+ };
16
+ import type { ElicitationRequest } from './acp/types.js';
17
+ import { type FormInfo, type Location, type PromptBody } from './contract.js';
18
+ /**
19
+ * The launch command as one readable line, for the footer when the agent never names
20
+ * itself. Three rules, each learned from what the line looks like on screen:
21
+ * - a value behind a secret-looking flag (`--token`, `--api-key`, `--password`, …) is
22
+ * masked, since this line is on screen and in screenshots;
23
+ * - absolute paths are shortened to their tail, because the footer is narrow and
24
+ * `node /Users/me/very/deep/tree/agent.mjs` spends the whole width on one directory;
25
+ * - the whole thing is capped, because a long `npx …` invocation would push the layout.
26
+ *
27
+ * Note the client title-cases this field (`Locale.titlecase` in its footer), so `bash` will
28
+ * read `Bash`. Passing the command verbatim is still the point: it stays a truthful
29
+ * identifier even when its capitals are not ours to choose.
30
+ */
31
+ export declare function displayAgentCommand(command: string): string;
32
+ export interface BridgeServerOptions {
33
+ /** Command that launches the ACP agent, `my-agent`. */
34
+ command: string;
35
+ args?: string[];
36
+ /** Working directory exposed to the client and passed to `session/new`. */
37
+ directory: string;
38
+ host?: string;
39
+ port?: number;
40
+ /**
41
+ * The resolved opencode client binary's version (e.g. `2.1.0`). `/api/info`
42
+ * reports it so the launched TUI does not warn that the server is older than
43
+ * itself; the launcher always knows this before it starts the TUI.
44
+ */
45
+ clientVersion?: string;
46
+ /** Extra env for the agent process. */
47
+ env?: Record<string, string | undefined>;
48
+ /**
49
+ * An existing the backend session to continue instead of creating one: the
50
+ * AGENT's own id (a UUID), translated from what the user typed by the
51
+ * launcher via the session map. This is what `session/load` is asked for.
52
+ */
53
+ resumeSession?: string;
54
+ /**
55
+ * The id the user TYPED for `--session` (the visible `ses_…`). The TUI is
56
+ * launched with this id and asks for it, so the pre-created session must be
57
+ * keyed by it too — otherwise the TUI's request misses the record, falls to
58
+ * the adoption path, and a SECOND agent process loads the same backend
59
+ * session. Measured: with the translated UUID as the pre-created record's
60
+ * id, dsh (one writer per session) refused the second load and the TUI opened
61
+ * an empty conversation wearing a title this bridge had marked as not-resumed.
62
+ */
63
+ resumeVisibleSessionId?: string;
64
+ /**
65
+ * `-c`/`--continue`: the launcher wants the NEWEST conversation, imported via
66
+ * session/list. With this set the pre-created record does NOT eagerly spawn
67
+ * an agent: two concurrent agent processes on one workspace measured as a
68
+ * refused load (dsh: one writer per workspace — the eager shell's session/new
69
+ * plus the adopted conversation's session/load = "Internal error" twice, then
70
+ * a blank "resumed" conversation). The empty record still exists for the
71
+ * routes that need one; nothing spawns until the user actually prompts it.
72
+ */
73
+ continueMode?: boolean;
74
+ /**
75
+ * Why `-c` had nothing to continue, so the fallback can name the cause instead
76
+ * of leaving a directory title looking like a continuation that lost its
77
+ * history. `no-list` is a CAPABILITY gap (the agent has no `session/list`).
78
+ */
79
+ continueModeReason?: 'no-list' | 'nothing' | 'failed';
80
+ /**
81
+ * Eagerly bring up the FIRST agent session (and with it the model catalog the
82
+ * agent advertises) instead of waiting for the first prompt. Set by the
83
+ * wrapped-subcommand bridge: `oc-acp-client models -- <agent>` has no
84
+ * prompt coming — nobody would ever start the agent — and `models` answers
85
+ * from the catalog, so without this the answer is the `acp/default`
86
+ * placeholder no matter which agent is attached. The TUI never sets this:
87
+ * its sessions are per-tab and start on the first message.
88
+ */
89
+ eagerCatalog?: boolean;
90
+ onLog?: (line: string) => void;
91
+ }
92
+ export declare class BridgeServer {
93
+ private readonly options;
94
+ private readonly state;
95
+ /**
96
+ * The most recently PROMPTED session's visible id. The single strongest signal
97
+ * about "which conversation did the user actually use this run", because the
98
+ * bridge sets it itself at the top of the prompt handler. Undefined until the
99
+ * user actually sends a message.
100
+ *
101
+ * Read through `promptedSessionId()` — deliberately in memory, not over HTTP:
102
+ * the exit epilogue reads it while shutting down, and a fetch at that moment
103
+ * raced the listener closing (measured: the line kept the TUI's native one).
104
+ */
105
+ private lastPromptedSessionId;
106
+ /**
107
+ * The most recently VIEWED session's visible id: set by `POST /api/session/:id/view`
108
+ * and by the singular `GET /api/session/:id`.
109
+ *
110
+ * Wider than "prompted" on purpose. Resuming a session and leaving without
111
+ * typing never reaches the prompt path, and keying the exit epilogue off
112
+ * prompts alone made the bridge fall back to the TUI's native
113
+ * `opencode -s <visible id>` line — which names neither this product nor an id
114
+ * the native daemon knows. It ranks BELOW the user's own `--session`/`-c`
115
+ * intent, though: with several restored tabs the client hydrates each one in
116
+ * turn, so this can end up naming a tab the user never opened.
117
+ */
118
+ private lastViewedSessionId;
119
+ private readonly hub;
120
+ private readonly agents;
121
+ /**
122
+ * One ACP connection per (command, args) — the agent program, not the tab.
123
+ *
124
+ * ACP sessions are independent on one connection (Martty ships this shape: one
125
+ * stdio connection, many session tabs), and a whole agent process per tab is what
126
+ * made every new tab pay a cold start. Sessions still keep their own catalog
127
+ * (`AcpClient` tracks config per session id) and their own translator; only the
128
+ * process is shared.
129
+ */
130
+ private readonly pools;
131
+ /**
132
+ * The transcript load a *read* is currently waiting on. See the `/message` route: one
133
+ * at a time, because a client hydrates every remembered tab at once and each of those
134
+ * loads belongs to its own agent process here (unlike the native single-process server,
135
+ * where it is a database read). A second read while one is in flight answers from what
136
+ * we have instead of starting another load — that is what makes tab hydration lazy.
137
+ */
138
+ private readLoad;
139
+ /**
140
+ * Sessions whose transcript read was answered WITHOUT loading, because another
141
+ * tab was mid-load. If one of them turns out to be the tab on screen (the
142
+ * startup burst can invert), it is loaded as soon as the focus signal arrives —
143
+ * one extra load, never the whole burst.
144
+ */
145
+ private deferredLoads;
146
+ /**
147
+ * The session the client is looking at, for the model catalog.
148
+ *
149
+ * `/api/model` carries only `location[directory]` — no session id — yet the catalog must
150
+ * be the one of the tab's OWN agent: two tabs may be bound to dsh and to opencode, and
151
+ * offering dsh's models on the opencode tab means every pick is rejected by the agent.
152
+ * A tab switch makes the client read that session (mount sync); the startup tab
153
+ * prefetch reads many sessions in one burst. So a read only moves the focus when it
154
+ * arrives after a quiet gap — the visible mount comes first at connect, the prefetch
155
+ * lands inside the same second and is ignored — while a human tab switch always does.
156
+ */
157
+ private focus;
158
+ /**
159
+ * Which agent each record's translator is already listening to. Needed because a
160
+ * translator can exist BEFORE an agent does (a turn that failed to start still has
161
+ * to render its own failure), and the listener must be wired exactly once per
162
+ * agent — not once per translator.
163
+ */
164
+ private readonly wiredTranslators;
165
+ private readonly pendingPermissions;
166
+ /** Forms the TUI is showing and the agent is still waiting on, by form id. */
167
+ private readonly pendingForms;
168
+ /** One best-effort session/list import per workspace, so startup does not spawn repeatedly. */
169
+ private readonly discoveredSessionDirectories;
170
+ private readonly discoveringSessionDirectories;
171
+ private server;
172
+ /** Set by `listen()`; `ServerInfo.urls` reports it back to the client. */
173
+ private listenUrl;
174
+ private readonly log;
175
+ private readonly clientVersion;
176
+ constructor(options: BridgeServerOptions);
177
+ get location(): Location;
178
+ /**
179
+ * Stable id for the project we serve. Not a workspace: see `location`.
180
+ * Lazy because class field initialisers run before the constructor assigns
181
+ * `options`.
182
+ */
183
+ private get projectId();
184
+ /**
185
+ * The agent command this bridge was launched with — the default owner for new sessions.
186
+ *
187
+ * ACP never says which agent owns a session (`session/resume`/`load` just take an id), so a
188
+ * remembered tab from another backend would otherwise be resumed into whatever agent this
189
+ * run launched: measured, a session created with `opencode acp` reopened under `dsh` gave an
190
+ * empty tab with nothing on screen explaining why. The session map records the binding, and
191
+ * a restored tab is reattached with ITS agent instead.
192
+ */
193
+ private agentBinding;
194
+ listen(): Promise<{
195
+ host: string;
196
+ port: number;
197
+ }>;
198
+ /** Where this server is reachable, for `ServerInfo.urls`. */
199
+ private url;
200
+ close(): Promise<void>;
201
+ private handle;
202
+ private handleSessionRoute;
203
+ /**
204
+ * Guarantee a session exists. The TUI expects to *find* one rather than
205
+ * create it, so a lazily-created default keeps its composer enabled from the
206
+ * first frame.
207
+ */
208
+ /**
209
+ * The session a fresh client should open.
210
+ *
211
+ * The TUI never creates a session on its own — it looks one up — so a launched
212
+ * client has to be told which id to open. Calling this first
213
+ * guarantees one exists.
214
+ */
215
+ primarySessionId(): string;
216
+ /**
217
+ * Wait until the ACP session has advertised its config options, so
218
+ * `/api/model` answers with the backend's real list from the first request.
219
+ *
220
+ * Without this a launched client connects within milliseconds, reads the
221
+ * placeholder model before `session/new` lands, and submits it as a choice —
222
+ * which the backend then rejects as invalid params, leaving the session pinned to a
223
+ * model that cannot answer.
224
+ */
225
+ waitForCatalog(timeoutMs?: number): Promise<void>;
226
+ /**
227
+ * Give sessions created before the agent reported its models a real model.
228
+ *
229
+ * A session created while the catalog was still the `acp/default` placeholder has no model, or
230
+ * (before the guard in the POST /api/session handler) carries the placeholder itself. Either
231
+ * way the assistant card's footer cannot resolve it: the card looks the message's
232
+ * `providerID`/`id` up in the model catalog and falls back to printing them verbatim, so a
233
+ * placeholder renders as `acp/unknown`. Adopting the first *real* catalog entry keeps the
234
+ * footer honest without inventing a model the agent never advertised.
235
+ */
236
+ /**
237
+ * The model to name when a session has none of its own: the first *real* catalog entry,
238
+ * never the `acp/default` placeholder. Handing the placeholder to the projection makes the
239
+ * assistant footer print `acp/unknown`, which looks like a broken model rather than "this
240
+ * backend has not reported one".
241
+ */
242
+ /**
243
+ * The first real model in the catalog, or undefined while it is still the placeholder.
244
+ *
245
+ * Accepts `id` as well as `modelID`. The catalog builds every entry with both (see `add()`), but
246
+ * an agent-supplied entry does not always carry `modelID` — measured against the fixture, whose
247
+ * option value produces `{id: "model-1"}` only. Requiring `modelID` made this return undefined
248
+ * for a perfectly real model, so the replay repair saw "no real model" and the card footer kept
249
+ * printing `acp/unknown`.
250
+ */
251
+ /** The real default of THIS ACP session's catalog; the global one only before it exists. */
252
+ /**
253
+ * Is this catalog row a real model, or the `acp/default` placeholder?
254
+ *
255
+ * ★ Identified by the ROW, not by the provider. "providerID !== 'acp'" looked right while
256
+ * every agent put its models under its own provider id — but an agent that advertises no
257
+ * provider grouping (codex-acp) has all 32 of its models under `acp` too, so that test
258
+ * called every one of them a placeholder: `defaultModel()` fell back to nothing, a new
259
+ * session got no model, the TUI submitted the placeholder, and the run reported
260
+ * "Failed to switch model: Internal error" against an agent that had answered perfectly.
261
+ */
262
+ private isRealModel;
263
+ private defaultModelFor;
264
+ private defaultModel;
265
+ private adoptCatalogModels;
266
+ /** Re-derive the model named by already-replayed history entries once a real one exists. */
267
+ /** Repair every session's replayed history once a real model is known. Idempotent. */
268
+ private repairHistoryModels;
269
+ private rescoreHistoryModels;
270
+ /**
271
+ * Follow the backend's title for this session and tell the client when it moves.
272
+ *
273
+ * A rename can arrive two ways: the TUI's PATCH (handled where it lands) or,
274
+ * more interestingly, from anywhere else - the `/session-title` skill writes a
275
+ * request, a backend-side plugin renames it inside the backend, and the bridge would never
276
+ * know. Polling the projection store is what makes the sidebar follow along,
277
+ * and it is the same shape as the SSE keepalive: cheap, idempotent, no events
278
+ * to subscribe to.
279
+ */
280
+ /**
281
+ * A skill id → its inlined text block (the official toModelOutput envelope), or
282
+ * undefined when no skill by that name is installed. Shares the scan /api/skill uses
283
+ * (config skill/skills and the workspace's .opencode/skill(s)), because the prompt
284
+ * body carries only the id the picker chose. The envelope is the official one so an
285
+ * agent sees byte-identical instructions to what the official server would send:
286
+ * content, base directory note, and up to ten sibling files (the official sample).
287
+ */
288
+ private skillBlock;
289
+ /**
290
+ * Import the agent's own sessions for a directory (`session/list`), so the
291
+ * client's session list shows them and `-c`/`--continue` can pick the latest.
292
+ *
293
+ * The public entry for the launcher's `--continue`: the TUI's -c asks
294
+ * `GET /api/session?limit=1&order=desc` and navigates to the first row —
295
+ * without the import the answer is empty on a fresh bridge (it holds nothing
296
+ * in memory), so "continue the last session" opened a blank conversation
297
+ * instead. Importing up front is the same discovery GET /api/session already
298
+ * does lazily; this just makes it happen before the TUI asks.
299
+ */
300
+ discoverSessions(directory: string): Promise<void>;
301
+ /**
302
+ * The session the user actually PROMPTED this run, for the launcher's exit
303
+ * epilogue — read from memory, not over HTTP.
304
+ *
305
+ * Measured: fetching it over HTTP at child-exit raced the shutdown (the
306
+ * handler logs "the TUI exited, shutting down" before the request arrives,
307
+ * the server closes under it, and the answer is null) — so the owner's
308
+ * Continue line fell back to the native one intermittently, exactly when the
309
+ * shutdown was quick. The launcher holds the server object, so it can just
310
+ * ask the memory the prompt path wrote.
311
+ */
312
+ promptedSessionId(): string | undefined;
313
+ /**
314
+ * Give an unnamed session the first words of its first prompt.
315
+ *
316
+ * Only once, and only over our own defaults: an agent title, a user rename, or a
317
+ * previously derived title all outrank it (see `SessionRecord.titleFrom*`).
318
+ * Persisted to the session map once the pairing is known, so a restored tab shows
319
+ * the name the conversation got from its first prompt instead of the directory
320
+ * basename (owner's call, 2026-10-18): a plain-ACP agent provides no titles at all,
321
+ * so without this every restore fell back to the directory. The map stores titles
322
+ * already; a derived title is a title, not conversation text.
323
+ */
324
+ /**
325
+ * A title that came back from the map: keep it, and remember that it is not a
326
+ * default, so the first prompt cannot overwrite it. A title carrying a resume
327
+ * marker (`[new conversation] …`) is the exception: the fresh conversation may
328
+ * still be named by its first message.
329
+ */
330
+ private adoptStoredTitle;
331
+ private deriveTitle;
332
+ /**
333
+ * Persist a session's current title into the map.
334
+ *
335
+ * The title is **bidirectional**: we derive one from the first prompt, the agent
336
+ * pushes one (`session_info_update`), `session/list` carries one, and the user can
337
+ * rename. Whichever wins in memory, the map must hold the LATEST title — otherwise a
338
+ * restore shows a stale one (measured: a plain-ACP session whose agent provides no
339
+ * titles fell back to the directory basename on every reopen). The map's `title` field
340
+ * therefore means "the conversation's last known name", not "the agent's title"; the
341
+ * in-memory ranking (`titleFromAgent` > `titleFromUser` > derived) is unchanged.
342
+ *
343
+ * Markers (`[no history] …`) are display decoration added at restore time and are
344
+ * never persisted.
345
+ */
346
+ private persistTitle;
347
+ /**
348
+ * The last session the client read or focused, for the exit epilogue's
349
+ * fallback tier. Kept separate from `promptedSessionId()` so the ranking lives
350
+ * in one readable place (`epilogueSessionId` in the launcher) instead of
351
+ * hiding inside an accessor.
352
+ */
353
+ /**
354
+ * Append a non-conversation notice to a session's transcript.
355
+ *
356
+ * Projected as the client's `Session.Message.System`, which the TUI renders as a
357
+ * `◈ Notice` row — the same surface the official client uses for "Instructions
358
+ * updated". The bridge uses it to say WHY a restored tab is empty: the session
359
+ * resumed, but the agent has no `session/load`, so the earlier conversation is
360
+ * not replayed. A notice is not a user or assistant turn, so it never counts as
361
+ * conversation content and does not affect the turn lifecycle.
362
+ */
363
+ private appendNotice;
364
+ viewedSessionId(): string | undefined;
365
+ private discoverAgentSessions;
366
+ private ensureSession;
367
+ private prompt;
368
+ /**
369
+ * `agent.prompt` with one recovery step for a stale "active prompt".
370
+ *
371
+ * This is the desync the mid-turn steer used to cause: our record says idle, the
372
+ * agent still has a prompt registered, and it answers `Session already has an
373
+ * active ACP prompt` — which used to surface as a red line at the end of the new
374
+ * reply. A cancel clears the agent's stale prompt; then the prompt runs once.
375
+ */
376
+ private runPrompt;
377
+ /**
378
+ * Run the next queued prompt for this session. The client only ever sees the
379
+ * hand-off (`session.inbox.delivered`); the turn itself is identical to a
380
+ * steer, so it reuses the same translator.
381
+ */
382
+ private deliverPending;
383
+ /**
384
+ * A valid `SessionStatsInfo` with no activity. The bridge keeps no usage
385
+ * ledger, but the shape must be complete: `/stats` reads `stats.range.from`
386
+ * and `stats.tokens` unguarded.
387
+ */
388
+ private emptyStats;
389
+ private startShell;
390
+ /**
391
+ * Stop a shell and everything it started.
392
+ *
393
+ * The direct child is a shell (`shell: true`), so a plain `child.kill()`
394
+ * leaves the real command running. Signalling the whole process group is what
395
+ * makes `!sleep 300` actually stop.
396
+ */
397
+ private killShell;
398
+ /**
399
+ * The envelope id a shell event must carry, matched to the shipped client.
400
+ *
401
+ * Read from v2.0.28, not guessed: the transport derives
402
+ * eventIDFromMessage(id) = id.replace(/^msg_/, 'evt_')
403
+ * and the store derives the inverse, `evt_` -> `msg_`. So the request arrives with
404
+ * `id: msg_abc`, the wait binds by comparing its `eventID` (`evt_abc`) with the event's
405
+ * id, and the store turns that same id back into `msg_abc` to find the row it inserted.
406
+ * Sending the raw `msg_abc` as the envelope id satisfied neither.
407
+ */
408
+ /**
409
+ * The event id for a shell's own events.
410
+ *
411
+ * Both v2 client generations derive the shell MESSAGE id from the event id with
412
+ * `event.id.replace(/^evt_/, "msg_")` (`SessionMessage.ID.fromEvent` in the store, and
413
+ * the same replace in the TUI's rows). Returning the bare `sh_…` id therefore produced
414
+ * a row that pointed at `sh_…` while the store's message is `msg_sh_…`: v2.1's rows
415
+ * appended the row anyway, but v2.2 resolves `props.message(row.messageID)` before
416
+ * rendering it and dropped the row entirely — a `!command` showed nothing at all.
417
+ */
418
+ private eventIdForShell;
419
+ /**
420
+ * Record a `!command` as the client's own shell message, keyed by shell id.
421
+ *
422
+ * The published schema gives a shell its **own top-level message type**
423
+ * (`Session.Message.Shell`: `{type:"shell", shellID, command, status, exit?, output?}`), and
424
+ * the TUI matches on `message.type === "shell"` to render it. This is what a reopened
425
+ * transcript is rebuilt from, so a shell stored any other way — a `tool` part, say — came
426
+ * back as a generic tool card without its shell context. Updating in place keeps one row for
427
+ * the whole run, which is also what the client does with `session.shell.ended`.
428
+ */
429
+ private rememberShell;
430
+ /**
431
+ * The tool row the transcript expands a `!command` in.
432
+ *
433
+ * Read from the shipped source: `packages/tui/src/routes/session/rows.ts` creates a
434
+ * message from `session.shell.started` using `event.id.replace(/^evt_/, "msg_")`, and
435
+ * `packages/tui/src/routes/session/index.tsx` renders that message's tool part with
436
+ * `Shell(props: ToolProps)`, reading `props.metadata.shellID`, `props.input.command`,
437
+ * `props.input.workdir` and `props.part.state.status`, then fetching the text from
438
+ * `/api/shell/:id/output` itself. Emitting only `session.shell.*` created no such part, so
439
+ * there was nothing to expand — the shapes below are copied from our own tool events,
440
+ * which the real-TUI acceptance already proves render.
441
+ */
442
+ private emitShellTool;
443
+ /** The `session.shell.ended` payload, emitted from one place for both routes. */
444
+ private emitShellEnded;
445
+ /**
446
+ * Resolve when the shell settles, or when `ms` is up — whichever first. The session
447
+ * shell route answers only after this, because its response is the client's
448
+ * "the command finished" signal.
449
+ */
450
+ private waitForShell;
451
+ private finishShell;
452
+ /** `ShellInfo`: `child` and the raw transcript stay server-side. */
453
+ private shellInfo;
454
+ private readonly translators;
455
+ private readonly pendingAgents;
456
+ /** True once any agent has advertised `session/new` config options. */
457
+ private get agentConfigReady();
458
+ /** Live `!` shell commands, keyed by the id handed back to the client. */
459
+ private readonly shells;
460
+ /** The ids a client remembers, and the agent's id behind each (the one file we write). */
461
+ private readonly sessionMap;
462
+ /**
463
+ * Session ids the user deleted. The client keeps its own list across runs and asks for
464
+ * ids this process never created, which we adopt so a remembered tab works — but a tab
465
+ * the user deleted must stay gone, or deleting looks like it failed.
466
+ */
467
+ private readonly deletedSessions;
468
+ /** Prompts accepted while a turn is running, in arrival order. */
469
+ private readonly pendingInbox;
470
+ /**
471
+ * Sessions with an `agent.prompt` in flight (including the gap while
472
+ * `ensureAgent` runs). ACP allows one active prompt per session; a second
473
+ * request queues behind this one.
474
+ */
475
+ private readonly promptsInFlight;
476
+ /**
477
+ * The backend's title for this session, from the standard `session/list`.
478
+ *
479
+ * That is where ACP carries titles - `session/list` entries are
480
+ * `{sessionId, cwd, title, updatedAt}` - and it replaces reading a backend's
481
+ * own store, which is what used to supply this. Best effort: an agent without
482
+ * `session/list`, or without a title on the entry, leaves the directory
483
+ * basename in place.
484
+ */
485
+ private applyBackendTitle;
486
+ /** The backend's own name, once it has introduced itself. */
487
+ private backendName;
488
+ /**
489
+ * What to call the agent when it never introduced itself.
490
+ *
491
+ * ACP makes `agentInfo` a SHOULD, so plenty of agents say nothing. The launch command
492
+ * is then the one piece of identity that is always true and reproducible — it is what
493
+ * the user typed — and it beats the `acp` placeholder, which tells them nothing. It is
494
+ * shown as a single line: secrets in named flags are masked, long commands truncated.
495
+ */
496
+ private launchName;
497
+ /**
498
+ * The agent changed its own session configuration: a model fallback under rate
499
+ * limits, a mode switch after planning, options adjusted from what it learned
500
+ * mid-turn.
501
+ *
502
+ * ACP sends the **complete** config state with the update, so ours is replaced
503
+ * rather than merged. The UI then has to be moved with the event its store
504
+ * actually reads for this — `session.model.selected`, which writes
505
+ * `session.info[id].model` (the composer and the context meter read that).
506
+ */
507
+ private applyConfigOptionUpdate;
508
+ /**
509
+ * The record's translator, created on demand and NOT wired to an agent.
510
+ *
511
+ * Split out of `attachTranslator` for exactly one case: a turn that cannot start
512
+ * at all (the agent process fails to spawn, initialize, or answer `session/new`).
513
+ * The user's message is already on screen by then, and without a translator there
514
+ * was nothing that could put the failure next to it — the request rejected, the
515
+ * transcript stayed empty, and the screen kept a user row followed by nothing
516
+ * forever (AGENTS.md §5.1's second silent-failure path). With this the prompt path
517
+ * can open a turn and close it with the error, the same shape a rejected
518
+ * `session/prompt` produces.
519
+ */
520
+ private translatorFor;
521
+ private attachTranslator;
522
+ /**
523
+ * A single primary agent mirroring the ACP session. ACP exposes no agent
524
+ * list, and the client's composer silently refuses to submit while
525
+ * `local.agent.current()` is empty.
526
+ */
527
+ private primaryAgent;
528
+ /**
529
+ * Project ACP's `session/new` config options into opencode's model/provider
530
+ * catalogue. the backend advertises models through one option (category `model`)
531
+ * whose choices are grouped by provider, each value a JSON array string like
532
+ * `["acme","some-model"]`.
533
+ */
534
+ /**
535
+ * The catalog to serve. With `only`, just that session's agent — the tab in front. Without
536
+ * it, every live agent (the old union), which is what startup and a fresh client get.
537
+ */
538
+ private modelCatalog;
539
+ /**
540
+ * Persist a visible→agent pairing the map does not know yet.
541
+ *
542
+ * ★ Why this exists: a restore that succeeds is a FACT about the pairing, and
543
+ * the map is the only place it survives the process. Two cases had no entry:
544
+ * `-c` (the launcher synthesises a `ses_acp_…` visible id from the agent's own
545
+ * session list) and a resume by an agent-native id. The exit epilogue then
546
+ * handed the user a `-s <id>` line naming an id the map had never heard of —
547
+ * which now fails loudly at startup ("unknown session id") instead of silently
548
+ * opening a blank conversation.
549
+ *
550
+ * `missingOnly` is for the recovery path: when the map ALREADY points at the
551
+ * conversation the user asked for, a failed load must not move that pointer to
552
+ * the fresh session we started instead — the next run should try the real one
553
+ * again. It only fills in a pairing that did not exist at all.
554
+ */
555
+ /**
556
+ * Record that this conversation was advanced, for `-c`'s recency ranking.
557
+ *
558
+ * Only a pair the map already holds can be re-stamped: without a pairing there is no
559
+ * agent id to file, and the pairing write itself (which happens when the agent session
560
+ * exists) marks the row used.
561
+ */
562
+ private noteUsed;
563
+ private rememberPairing;
564
+ /**
565
+ * Move every per-session map from the shell's id to the id the client chose.
566
+ *
567
+ * Called from `POST /api/session` when it adopts the pre-created shell instead of
568
+ * creating a second record. The shell may already own a warm agent (the `/api/model`
569
+ * warm-up), a translator, and pending permission/form entries; the agent's own ACP
570
+ * session is untouched, so the first prompt reuses it instead of spawning another.
571
+ */
572
+ private rekeySession;
573
+ /** Must match the client's mount sync: a tab switch is a mount, a prefetch is a burst. */
574
+ private static readonly FOCUS_GAP_MS;
575
+ /**
576
+ * Load one transcript, owning the single-flight slot.
577
+ *
578
+ * Extracted so the focus path can trigger the same load the read path does: the
579
+ * tab on screen must not stay empty just because a background tab's read won
580
+ * the startup race.
581
+ */
582
+ private loadTranscript;
583
+ /**
584
+ * The tab on screen lost the startup race: load it now.
585
+ *
586
+ * Called when a lazily answered read turns out to be the focused session — from
587
+ * the focus signal itself and from the end of whatever load was holding the
588
+ * slot. Only the focused one is chased; the rest keep the lazy contract.
589
+ */
590
+ private loadDeferredIfFocused;
591
+ private noteFocus;
592
+ private focusRecord;
593
+ /** The bridge session that owns an ACP session id (for routing shared-connection callbacks). */
594
+ private bridgeIdForAgentSession;
595
+ private ensureAgent;
596
+ /**
597
+ * Answer an `elicitation/create` from the agent by asking the user through the
598
+ * TUI's own form surface.
599
+ *
600
+ * The mapping is one-way and lossless in the direction that matters: the agent
601
+ * declares a flat JSON Schema, we publish it as a `Form.Info`, the TUI renders
602
+ * it, and the answer it hands back becomes `content` on an `accept`. A schema
603
+ * we cannot render completely is refused with a JSON-RPC error rather than
604
+ * shown partially — a partial form would collect an answer that silently does
605
+ * not match the agent's schema, and the agent cannot tell that from a good one.
606
+ */
607
+ private awaitElicitation;
608
+ /**
609
+ * Settle a pending form from the TUI. Returns false when the id is unknown —
610
+ * a double reply, or one for a form the agent already gave up on.
611
+ */
612
+ private settleForm;
613
+ /**
614
+ * Answer every permission request this session's agent is blocked on with the
615
+ * `cancelled` outcome.
616
+ *
617
+ * ACP: "The Client **MUST** respond to all pending `session/request_permission`
618
+ * requests with the `cancelled` outcome" — once the turn is aborted, no answer
619
+ * is coming, and the agent has no timeout of its own.
620
+ */
621
+ private cancelPendingPermissions;
622
+ /** Dismiss every form this session is showing; the elicitation gets `cancel`. */
623
+ private cancelPendingForms;
624
+ private awaitPermission;
625
+ /**
626
+ * Answer a pending permission request.
627
+ *
628
+ * Returns false when the request is unknown — already answered, expired by the agent, or
629
+ * settled by an interrupt. The route turns that into `404` rather than `204`: the official
630
+ * TUI's data suite has a case for a permission that expired before its reply, and a silent
631
+ * success there leaves the client believing it answered something. The form route already
632
+ * answers `404` for the same situation; the two must agree.
633
+ */
634
+ private replyPermission;
635
+ }
636
+ /**
637
+ * The fallback title taken from the first user message.
638
+ *
639
+ * ★ ACP has no client-side title method, and agents without a title surface (the
640
+ * backend's plain ACP profile sends no `session_info_update` and no titles in
641
+ * `session/list`) leave every session on the client's "New session" forever. The
642
+ * user's own words are the only deterministic, local source of a name — so the
643
+ * first prompt becomes the title, and an agent-provided title replaces it later.
644
+ *
645
+ * One line, whitespace collapsed, at most `max` code points, `…` when cut. Empty
646
+ * (an attachment-only prompt) yields nothing: a title made of nothing is worse
647
+ * than the default.
648
+ */
649
+ export declare function derivedTitle(text: string, max?: number): string | undefined;
650
+ /**
651
+ * A session title that carries one of our markers, without stacking them.
652
+ *
653
+ * The title is the only surface we have for "what this restored tab actually
654
+ * is" (the client persists it into its tab layout, which is the point — and also
655
+ * why a wrong one is expensive: `[not resumed]` outlived the bug that wrote it).
656
+ * So each marker must be idempotent: a record re-created from a map that already
657
+ * carries a marker must not grow `[new conversation] [new conversation] …`, and
658
+ * the legacy `[not resumed]` prefix must be dropped rather than nested.
659
+ */
660
+ /** Remove any stacked display markers from a title (`[no history] x` → `x`). */
661
+ export declare function stripTitleMarkers(current: string | undefined): string;
662
+ export declare function markTitle(current: string | undefined, fallback: string, marker: string): string;
663
+ /**
664
+ * Map an ACP form elicitation onto the form the opencode TUI renders.
665
+ *
666
+ * Throws `AcpError(-32602)` for anything we cannot render **completely**: a
667
+ * partially rendered form would collect an answer that does not match the
668
+ * agent's schema, and the agent has no way to tell that from a correct one.
669
+ * An explicit refusal lets it fall back or fail the operation, which is what the
670
+ * spec requires agents to handle.
671
+ *
672
+ * The supported subset is form mode's own restriction (`packages/schema`'s
673
+ * `Form.Field` union): string (optionally an enum), number, integer, boolean, and
674
+ * a string array with an enum — which is the TUI's `multiselect`.
675
+ */
676
+ export declare function formFromElicitation(sessionId: string, formId: string, request: ElicitationRequest): FormInfo;
677
+ /**
678
+ * The model a config-option list currently selects, in the shape the TUI reads
679
+ * (`{providerID, modelID}`, matched against `ModelInfo.providerID`/`.id`).
680
+ *
681
+ * Returns undefined unless both halves are present: a session model the client
682
+ * cannot match makes it show "model (unavailable)".
683
+ */
684
+ /**
685
+ * Apply `GET /api/session`'s query to the sessions we hold.
686
+ *
687
+ * Mirrors `SessionStore.list` (opencode v2.2.6, `packages/core/src/session/store.ts`):
688
+ * - `search` matches the TITLE (a `LIKE %…%`) — not the id, so a client searching an id
689
+ * correctly finds nothing;
690
+ * - `parentID=null` keeps root sessions only, a value keeps that parent's children;
691
+ * - `archived=false` drops archived ones, `true` keeps only those;
692
+ * - `order` sorts by `time.updated` (the field the client itself sorts on), `desc` by
693
+ * default;
694
+ * - `limit` caps the result AFTER ordering, and `cursor` is not implemented — the route
695
+ * never paged before, and a cursor the client cannot advance would be worse than none.
696
+ *
697
+ * `project`, `subpath` and `directory` are about a multi-project store this bridge does not
698
+ * have (one directory per run), so they are accepted and ignored — the same shape as the
699
+ * `location[directory]` handling above.
700
+ */
701
+ export declare function sessionListQuery<T extends {
702
+ id: string;
703
+ title?: string;
704
+ parentID?: string;
705
+ time: {
706
+ updated: number;
707
+ archived?: number;
708
+ };
709
+ }>(sessions: readonly T[], query: URLSearchParams): T[];
710
+ /**
711
+ * the backend's own title for a session, or undefined.
712
+ *
713
+ * the backend keeps it in its projection store; the sidebar in the opencode TUI renders
714
+ * `session.title`, so reading it here is what makes an external launcher show
715
+ * the backend web instead of the directory basename.
716
+ */
717
+ /**
718
+ * Attachments we cannot forward. An image can be passed to the agent as an ACP
719
+ * image block, but nothing else can: we announce no `fs/*` and no `terminal/*`, so
720
+ * a file's *contents* have no route. It must not be dropped in silence — that is
721
+ * the failure this function exists to make impossible.
722
+ *
723
+ * A file is forwardable when it carries inline image data (`{data, mime: image/*}`),
724
+ * OR when it is a `file://` URI whose name or mime says image — the real TUI's
725
+ * `@file` picker sends exactly that shape (measured v2.0.30), and reading the
726
+ * local file it names is the only way to build the ACP image block the agent
727
+ * expects.
728
+ */
729
+ export declare function unsupportedAttachments(payload: PromptBody): string[];
730
+ /** Accept the `parts` array, a bare `text` field, and the TUI's `files`. */
731
+ export declare function promptParts(payload: PromptBody): Array<{
732
+ type: string;
733
+ text?: string;
734
+ [k: string]: unknown;
735
+ }>;
736
+ /**
737
+ * The physical spelling of a path (symlinks resolved), or the text when it cannot be
738
+ * resolved. macOS is the reason this exists: `/var/...` and `/private/var/...` are the
739
+ * same directory spelled two ways, and comparing or hashing the raw strings split one
740
+ * workspace into two identities.
741
+ */
742
+ export declare function canonicalPath(directory: string): string;
743
+ export declare function projectIdFor(directory: string): string;