@qlairoslabs/acp-client 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Facundo Hannoch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,222 @@
1
+ # @qlairoslabs/acp-client
2
+
3
+ An embeddable, model-agnostic **Agent Client Protocol (ACP)** client: talk to AI coding
4
+ agents (Codex, Claude, Kimi, Gemini, Copilot, OpenCode, …) over JSON-RPC 2.0, with a
5
+ **degraded PTY fallback** for agents that don't speak ACP.
6
+
7
+ ```ts
8
+ import { AgentController, ADAPTERS } from "@qlairoslabs/acp-client";
9
+
10
+ const agent = new AgentController({ adapter: ADAPTERS.codex, adapterId: "codex" });
11
+ await agent.start();
12
+ const { text } = await agent.prompt("Say hello in one sentence.");
13
+ console.log(text);
14
+ await agent.stop();
15
+ ```
16
+
17
+ > **Runtime:** this package currently requires **[Bun](https://bun.sh) ≥ 1.3.5**.
18
+ > The transport layer is built on `Bun.spawn`. Node support is planned (see
19
+ > [Roadmap](#roadmap)); the spawn layer is already isolated behind a single module to make
20
+ > that a drop-in addition.
21
+
22
+ ---
23
+
24
+ ## Why this exists
25
+
26
+ ACP is a clean, model-agnostic way to drive coding agents, but the existing clients make
27
+ assumptions that don't fit when you orchestrate **many** agents across **many**
28
+ environments:
29
+
30
+ - **No forced `cwd` discovery.** Other libraries crawl up to the git root and impose a
31
+ working directory. This one takes `cwd` (and an `execPrefix` like `docker exec -i …`) as
32
+ plain config, so you can talk to agents inside containers or arbitrary runtimes.
33
+ - **Introspection over hardcoding.** Models, auth methods, capabilities, and config
34
+ options are all *discovered* from the protocol at runtime, never baked in. The library
35
+ surfaces raw protocol facts and lets you decide what they mean.
36
+ - **A fallback for agents that don't fully support ACP.** Some providers lack crucial
37
+ operations (e.g. `login`), and some only expose ACP through an SDK that breaks
38
+ subscription-based auth. For those, a **degraded mode** drives the agent's native
39
+ interactive CLI through a PTY and parses the terminal output. It's expected to work worse
40
+ than real ACP (hence "degraded") but it keeps the same output contract so your
41
+ rendering code doesn't change.
42
+
43
+ ---
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ # as a dependency in a Bun project
49
+ bun add @qlairoslabs/acp-client
50
+
51
+ # or for the CLI, globally
52
+ bun add -g @qlairoslabs/acp-client
53
+ ```
54
+
55
+ ---
56
+
57
+ ## Core concepts
58
+
59
+ | Abstraction | What it is |
60
+ |---|---|
61
+ | **`AgentController`** | The control plane for **one** agent process: start/stop, prompt, interrupt, switch sessions, swap mode (normal ⇄ degraded), introspect capabilities & config. |
62
+ | **`AgentSession`** | A **durable conversation** with a stable identity that survives reconnects and mode-swaps. Wraps an `AgentController` and (optionally) records itself to a catalog. The front face for consumers that want persistence. |
63
+ | **`SessionManager` + `SessionStore`** | The session **catalog**: routing metadata (which adapter/mode/cwd a session belongs to), *not* conversation content. Merges your catalog with the agent's live `session/list`. Ships a `FileSessionStore`; inject your own (e.g. a database) for custom backends. |
64
+ | **Adapter** | Just how to *launch* an agent: the spawn command. `ADAPTERS` has presets (`codex`, `claude`, `kimi`, `gemini`, `copilot`, `opencode`); you can also pass a raw `{ command: [...] }`. |
65
+ | **Mode** | `"normal"` (real ACP over JSON-RPC) or `"degraded"` (drive the native CLI through a PTY and parse it). Both implement the same `AgentClient` output contract. |
66
+
67
+ ---
68
+
69
+ ## Usage
70
+
71
+ ### One-shot prompt
72
+
73
+ ```ts
74
+ import { AgentController, ADAPTERS, createConsoleLogger } from "@qlairoslabs/acp-client";
75
+
76
+ const agent = new AgentController({
77
+ adapter: ADAPTERS.codex,
78
+ adapterId: "codex",
79
+ cwd: process.cwd(),
80
+ defaultPermission: "cancel", // "approve" to auto-accept tool permissions
81
+ logger: createConsoleLogger({ minLevel: "info" }),
82
+ });
83
+
84
+ const { sessionId, resumed } = await agent.start();
85
+ console.log(resumed ? "resumed" : "new", sessionId);
86
+
87
+ const result = await agent.prompt("Refactor utils.ts for readability.");
88
+ console.log(result.text, result.stopReason, result.usage);
89
+
90
+ await agent.stop();
91
+ ```
92
+
93
+ ### Streaming activity (thinking / tool calls)
94
+
95
+ ```ts
96
+ await agent.prompt("Find and fix the failing test.", {
97
+ onChunk: (text) => process.stdout.write(text), // response text as it streams
98
+ onActivity: (event) => console.error("·", event.type), // thinking / tool calls / plan
99
+ onPermissionRequest: (req) => ({ outcome: "selected", optionId: req.options[0].optionId }),
100
+ });
101
+ ```
102
+
103
+ If you omit `onPermissionRequest`, the client falls back to the controller's
104
+ `defaultPermission` (`"approve"` / `"cancel"`).
105
+
106
+ ### Durable sessions with a catalog
107
+
108
+ `AgentSession` gives a conversation a stable id that persists across reconnects, and
109
+ records routing metadata so you can list and resume sessions later.
110
+
111
+ ```ts
112
+ import {
113
+ AgentSession,
114
+ ADAPTERS,
115
+ SessionManager,
116
+ FileSessionStore,
117
+ } from "@qlairoslabs/acp-client";
118
+
119
+ const sessions = new SessionManager(new FileSessionStore()); // ~/.acp-lib/sessions
120
+
121
+ const session = await AgentSession.create({
122
+ adapter: ADAPTERS.codex,
123
+ adapterId: "codex",
124
+ sessions, // ← records itself to the catalog on start & each prompt
125
+ });
126
+
127
+ await session.prompt("Start working on the auth module.");
128
+
129
+ // later. List everything we know about, catalog ∪ the agent's live list
130
+ for (const s of await session.listSessions()) {
131
+ console.log(s.source, s.id, s.title); // source: "catalog" | "agent" | "both"
132
+ }
133
+
134
+ await session.stop();
135
+ ```
136
+
137
+ ### Interactive REPL
138
+
139
+ The REPL and its slash-commands (`/help`, `/new`, `/sessions`, `/load`, `/config`,
140
+ `/degrade`, …) are reusable. Wire them to your own UI, or just run them.
141
+
142
+ ```ts
143
+ import { runRepl, createAgentCommands } from "@qlairoslabs/acp-client/repl";
144
+ import { AgentController, ADAPTERS } from "@qlairoslabs/acp-client";
145
+
146
+ const agent = new AgentController({ adapter: ADAPTERS.codex, adapterId: "codex" });
147
+ const { sessionId, resumed } = await agent.start();
148
+
149
+ const commands = createAgentCommands({
150
+ client: agent,
151
+ note: (msg) => process.stderr.write(msg + "\n"),
152
+ color: true,
153
+ // sessionManager + adapterId here to persist /new, /load, /fork to a catalog
154
+ });
155
+
156
+ try {
157
+ await runRepl(agent, {
158
+ intro: `${resumed ? "resumed" : "new"} session ${sessionId}`,
159
+ activity: true,
160
+ spinner: true,
161
+ onSlashCommand: commands.onSlashCommand,
162
+ });
163
+ } finally {
164
+ await agent.stop();
165
+ }
166
+ ```
167
+
168
+ ### CLI
169
+
170
+ A thin wrapper over the library is exposed as `acp-client`:
171
+
172
+ ```bash
173
+ acp-client chat # new chat with the default adapter
174
+ acp-client chat <SESSION_ID> # resume a session
175
+ acp-client chat --adapter codex # pick an adapter
176
+ acp-client chat --exec "docker exec -i my-container" # talk to an agent in a container
177
+ acp-client chat --cwd /workspace --approve # auto-approve tool permissions
178
+ acp-client chat --degraded # force degraded (PTY) mode
179
+ acp-client chat -v | -d # verbose lifecycle / debug raw protocol
180
+ ```
181
+
182
+ Activity markers (thinking/tool) show by default; `--no-activity` disables them.
183
+
184
+ ---
185
+
186
+ ## Package exports
187
+
188
+ The core barrel never pulls in `node-pty` / parsing deps. Degraded and parser support are
189
+ opt-in subpaths.
190
+
191
+ | Import | Contents |
192
+ |---|---|
193
+ | `@qlairoslabs/acp-client` | Core: `AgentController`, `AgentSession`, `AcpClient`, `SessionManager`, `FileSessionStore`, `ADAPTERS`, loggers, types. |
194
+ | `@qlairoslabs/acp-client/repl` | `runRepl`, `createAgentCommands` (interactive layer). |
195
+ | `@qlairoslabs/acp-client/degraded` | The PTY fallback transport (`Bun.spawn({ terminal })` + xterm parsing). |
196
+ | `@qlairoslabs/acp-client/parser` | Terminal-output parsers used by degraded mode. |
197
+ | `@qlairoslabs/acp-client/cli` | The CLI entry point. |
198
+
199
+ ---
200
+
201
+ ## Roadmap
202
+
203
+ - **Node runtime support.** The only Bun-coupled code is the transport layer
204
+ (`src/transport/acp-transport.ts` and `src/degraded/pty-transport.ts`). Everything above
205
+ it is runtime-agnostic, so Node support means adding sibling transports
206
+ (`child_process.spawn` / `node-pty`) selected at runtime (no changes to the client),
207
+ controller, sessions, or REPL.
208
+
209
+ ---
210
+
211
+ ## Development
212
+
213
+ ```bash
214
+ bun install
215
+ bun run typecheck # tsc --noEmit
216
+ bun test # unit tests
217
+ bun run check # typecheck + test
218
+ ```
219
+
220
+ ## License
221
+
222
+ [MIT](./LICENSE) © Facundo Hannoch
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@qlairoslabs/acp-client",
3
+ "version": "0.1.0",
4
+ "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
+ "type": "module",
6
+ "module": "src/index.ts",
7
+ "license": "MIT",
8
+ "author": "Facundo Hannoch <ffacu594@gmail.com>",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/facuHannoch/acp-lib.git"
12
+ },
13
+ "homepage": "https://github.com/facuHannoch/acp-lib#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/facuHannoch/acp-lib/issues"
16
+ },
17
+ "keywords": [
18
+ "acp",
19
+ "agent-client-protocol",
20
+ "ai-agent",
21
+ "coding-agent",
22
+ "jsonrpc",
23
+ "codex",
24
+ "claude",
25
+ "kimi",
26
+ "repl",
27
+ "bun"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "src"
34
+ ],
35
+ "exports": {
36
+ ".": "./src/index.ts",
37
+ "./repl": "./src/repl/index.ts",
38
+ "./degraded": "./src/degraded/index.ts",
39
+ "./parser": "./src/parser/index.ts",
40
+ "./cli": "./src/cli/index.ts"
41
+ },
42
+ "bin": {
43
+ "acp-client": "./src/cli/index.ts"
44
+ },
45
+ "scripts": {
46
+ "test": "bun test",
47
+ "typecheck": "tsc --noEmit",
48
+ "check": "bun run typecheck && bun test",
49
+ "pack:dry": "bun pm pack --dry-run"
50
+ },
51
+ "engines": {
52
+ "bun": ">=1.3.5"
53
+ },
54
+ "dependencies": {
55
+ "@agentclientprotocol/sdk": "0.25.1",
56
+ "@xterm/headless": "^6.0.0"
57
+ },
58
+ "devDependencies": {
59
+ "@types/bun": "latest",
60
+ "typescript": "^5"
61
+ }
62
+ }
@@ -0,0 +1,52 @@
1
+ // Adapters carry ONLY what's needed to LAUNCH the connection — the command.
2
+ // Everything else (auth methods, capabilities, features) is DISCOVERED from initialize.
3
+ // See SPEC.md "Adapters" + "Core principles".
4
+
5
+ export interface Adapter {
6
+ /** The command to spawn the ACP agent binary, e.g. ["kimi", "acp"]. */
7
+ command: string[];
8
+ /**
9
+ * The command to launch the agent's INTERACTIVE CLI for degraded (pty) mode, e.g.
10
+ * ["codex"] (vs ACP ["codex-acp"]). Omit if the agent has no interactive mode —
11
+ * degraded mode then refuses to start for that adapter.
12
+ */
13
+ ptyCommand?: string[];
14
+ /** Optional human label, purely cosmetic. */
15
+ displayName?: string;
16
+ }
17
+
18
+ /**
19
+ * Convenient presets. NOT exhaustive and NOT authoritative — a caller can always pass
20
+ * a raw `{ command: [...] }`. These only encode how to start the binary; they say
21
+ * nothing about what the agent supports.
22
+ */
23
+ export const ADAPTERS = {
24
+ kimi: { command: ["kimi", "acp"], ptyCommand: ["kimi"], displayName: "Kimi" },
25
+ claude: { command: ["claude-agent-acp"], ptyCommand: ["claude"], displayName: "Claude" },
26
+ codex: { command: ["codex-acp"], ptyCommand: ["codex"], displayName: "Codex" },
27
+ gemini: { command: ["gemini", "--acp", "--stdio"], ptyCommand: ["gemini"], displayName: "Gemini" },
28
+ copilot: { command: ["copilot", "--acp", "--stdio"], ptyCommand: ["copilot"], displayName: "Copilot" },
29
+ opencode: { command: ["opencode", "acp"], ptyCommand: ["opencode"], displayName: "OpenCode" },
30
+ } satisfies Record<string, Adapter>;
31
+
32
+ export type AdapterPreset = keyof typeof ADAPTERS;
33
+
34
+ /**
35
+ * Merge an exec prefix (e.g. ["docker","exec","-i","<container>"]) with the adapter
36
+ * command. The adapter doesn't know or care how it's executed — the client owns the
37
+ * prefix. See SPEC.md "Exec prefix (Docker etc.)".
38
+ */
39
+ export function buildSpawnCommand(adapter: Adapter, execPrefix: string[] = []): string[] {
40
+ return [...execPrefix, ...adapter.command];
41
+ }
42
+
43
+ /**
44
+ * Like buildSpawnCommand but for the interactive (degraded/pty) command. Throws if the
45
+ * adapter has no `ptyCommand` — degraded mode is impossible without an interactive CLI.
46
+ */
47
+ export function buildPtyCommand(adapter: Adapter, execPrefix: string[] = []): string[] {
48
+ if (!adapter.ptyCommand || adapter.ptyCommand.length === 0) {
49
+ throw new Error("adapter has no ptyCommand — degraded (pty) mode is unavailable for it");
50
+ }
51
+ return [...execPrefix, ...adapter.ptyCommand];
52
+ }
@@ -0,0 +1,50 @@
1
+ // AgentClient — the shared OUTPUT contract. This interface IS the "same output
2
+ // contract" from SPEC.md made structural: both AcpClient (core) and PtyClient
3
+ // (degraded, deferred) implement it, so a caller's rendering code targets this and
4
+ // works in either mode.
5
+ //
6
+ // The rich INPUT surfaces (capabilities, configOptions, sessions, authenticate) live
7
+ // ONLY on AcpClient — they don't exist on this interface because they genuinely don't
8
+ // exist in degraded mode.
9
+
10
+ import type { PromptResult, PromptHandlers, Attachment } from "./types.ts";
11
+
12
+ export interface InterruptOptions {
13
+ /** Also drop any queued prompts, not just the in-flight one. */
14
+ clearQueue?: boolean;
15
+ }
16
+
17
+ export interface BridgeOptions {
18
+ /** Input stream to read keystrokes from. Default process.stdin. */
19
+ input?: NodeJS.ReadStream;
20
+ /** Output stream to write raw pty bytes to. Default process.stdout. */
21
+ output?: NodeJS.WritableStream;
22
+ /** Bytes that end the bridge and return control. Default [0x1d Ctrl-], 0x03 Ctrl-C]. */
23
+ exitBytes?: number[];
24
+ /** Chrome/status messages (the bridge banner). Default → process.stderr. */
25
+ onStatus?: (msg: string) => void;
26
+ }
27
+
28
+ /**
29
+ * A client whose underlying terminal can be handed directly to the user (degraded/pty
30
+ * only). The user drives the real CLI; we relay bytes both ways until an exit chord.
31
+ * Use for tty-auth (login) and as an escape hatch when scraping can't read a TUI.
32
+ */
33
+ export interface Bridgeable {
34
+ bridge(options?: BridgeOptions): Promise<void>;
35
+ }
36
+
37
+ export interface AgentClient {
38
+ /** Send a prompt and resolve with the turn result. The main entry point. */
39
+ prompt(
40
+ text: string,
41
+ handlers?: PromptHandlers,
42
+ attachments?: Attachment[],
43
+ ): Promise<PromptResult>;
44
+
45
+ /** Cancel the in-flight prompt; the pending prompt() resolves with status "cancelled". */
46
+ interrupt(options?: InterruptOptions): void;
47
+
48
+ /** Tear down the underlying process/transport. */
49
+ stop(): Promise<void>;
50
+ }
@@ -0,0 +1,212 @@
1
+ // AgentSession — the durable conversation and the library's FRONT FACE. This is what a
2
+ // consumer (the orchestration hub, the CLI) holds: a conversation with a stable identity
3
+ // that persists across reconnects/mode-swaps, backed by a SessionManager catalog.
4
+ //
5
+ // It owns identity (our `id`, adapter, mode, agentSessionId, title) and persistence, and
6
+ // HOLDS an AgentController for the live connection (the control plane). It implements
7
+ // AgentClient, so the REPL and any caller can prompt it directly.
8
+ //
9
+ // Adapter lives HERE, not on the controller: switching adapter = a new AgentSession (the
10
+ // agent dies on switch). Mode-swap (degrade/upgrade) stays within one AgentSession.
11
+
12
+ import { AgentController, type AgentMode } from "./controller.ts";
13
+ import type { Adapter } from "./adapters.ts";
14
+ import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
15
+ import type { Capabilities } from "./capabilities.ts";
16
+ import type { ConfigOptions } from "./config-options.ts";
17
+ import type { ConnectResult } from "./client.ts";
18
+ import type { Logger } from "./logger.ts";
19
+ import type { SessionManager, MergedSession } from "./session-manager.ts";
20
+ import type {
21
+ AgentCommand,
22
+ Attachment,
23
+ PromptHandlers,
24
+ PromptResult,
25
+ SessionListEntry,
26
+ } from "./types.ts";
27
+
28
+ export interface AgentSessionConfig {
29
+ /** The resolved adapter this conversation talks to. */
30
+ adapter: Adapter;
31
+ /** Stable adapter id for the catalog/display (e.g. "codex"). */
32
+ adapterId: string;
33
+ /** Talk over ACP ("normal") or scrape a pty ("degraded"). Default "normal". */
34
+ mode?: AgentMode;
35
+ execPrefix?: string[];
36
+ env?: Record<string, string>;
37
+ cwd?: string;
38
+ defaultPermission?: "approve" | "cancel";
39
+ clientInfo?: { name: string; title?: string; version?: string };
40
+ logger?: Logger;
41
+ /** Optional catalog. When present, the session records itself here. */
42
+ sessions?: SessionManager;
43
+ /** Our stable catalog id. Minted if omitted (a fresh conversation); pass a record's id to resume. */
44
+ id?: string;
45
+ /** Agent session to load on start (resume an existing agent conversation). */
46
+ agentSessionId?: string;
47
+ title?: string;
48
+ }
49
+
50
+ export class AgentSession implements AgentClient, Bridgeable {
51
+ /** Our stable catalog id — decoupled from the agent's (mutable) session id. */
52
+ readonly id: string;
53
+ readonly adapterId: string;
54
+
55
+ private readonly controller: AgentController;
56
+ private readonly sessions?: SessionManager;
57
+ private _agentSessionId: string | null;
58
+ private _mode: AgentMode;
59
+ private _cwd?: string;
60
+ private _title?: string;
61
+
62
+ private constructor(config: AgentSessionConfig) {
63
+ this.id = config.id ?? crypto.randomUUID();
64
+ this.adapterId = config.adapterId;
65
+ this.sessions = config.sessions;
66
+ this._mode = config.mode ?? "normal";
67
+ this._cwd = config.cwd;
68
+ this._title = config.title;
69
+ this._agentSessionId = config.agentSessionId ?? null;
70
+ this.controller = new AgentController({
71
+ adapter: config.adapter,
72
+ adapterId: config.adapterId,
73
+ mode: this._mode,
74
+ execPrefix: config.execPrefix,
75
+ env: config.env,
76
+ cwd: config.cwd,
77
+ sessionId: config.agentSessionId,
78
+ defaultPermission: config.defaultPermission,
79
+ clientInfo: config.clientInfo,
80
+ logger: config.logger,
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Start a conversation. A FRESH one if no `id`/`agentSessionId`; a RESUMED one if
86
+ * `agentSessionId` is given (the controller loads it). To resume from the catalog, the
87
+ * caller resolves the record's adapter and passes the record's fields here.
88
+ */
89
+ static async create(config: AgentSessionConfig): Promise<AgentSession> {
90
+ const session = new AgentSession(config);
91
+ await session.start();
92
+ return session;
93
+ }
94
+
95
+ private async start(): Promise<void> {
96
+ const result = await this.controller.start();
97
+ this._agentSessionId = result.sessionId || this._agentSessionId;
98
+ await this.persist();
99
+ }
100
+
101
+ // --- identity ----------------------------------------------------------------
102
+ get agentSessionId(): string | null {
103
+ return this._agentSessionId;
104
+ }
105
+ get mode(): AgentMode {
106
+ return this._mode;
107
+ }
108
+ get cwd(): string | undefined {
109
+ return this._cwd;
110
+ }
111
+ get title(): string | undefined {
112
+ return this._title;
113
+ }
114
+ /** Escape hatch to the live control plane (config, caps, getCommands, login, …). */
115
+ get connection(): AgentController {
116
+ return this.controller;
117
+ }
118
+
119
+ // --- AgentClient -------------------------------------------------------------
120
+ async prompt(
121
+ text: string,
122
+ handlers?: PromptHandlers,
123
+ attachments?: Attachment[],
124
+ ): Promise<PromptResult> {
125
+ const res = await this.controller.prompt(text, handlers, attachments);
126
+ if (!this._title && text.trim()) {
127
+ this._title = text.trim().replace(/\s+/g, " ").slice(0, 60);
128
+ }
129
+ // A session may have been created lazily on first prompt (degraded has none).
130
+ this._agentSessionId = this.controller.currentSessionId ?? this._agentSessionId;
131
+ await this.persist();
132
+ return res;
133
+ }
134
+
135
+ interrupt(options?: InterruptOptions): void {
136
+ this.controller.interrupt(options);
137
+ }
138
+
139
+ async stop(): Promise<void> {
140
+ await this.controller.stop();
141
+ }
142
+
143
+ // --- mode swap (catalog-affecting) -------------------------------------------
144
+ async setMode(mode: AgentMode): Promise<ConnectResult> {
145
+ const result = await this.controller.setMode(mode);
146
+ this._mode = this.controller.currentMode;
147
+ this._agentSessionId = result.sessionId || null; // the agent session changes on swap
148
+ await this.persist();
149
+ return result;
150
+ }
151
+
152
+ // --- thin proxies to the live connection -------------------------------------
153
+ get capabilities(): Capabilities {
154
+ return this.controller.capabilities;
155
+ }
156
+ get configOptions(): ConfigOptions {
157
+ return this.controller.configOptions;
158
+ }
159
+ get agentCommands(): AgentCommand[] {
160
+ return this.controller.agentCommands;
161
+ }
162
+ get isDegraded(): boolean {
163
+ return this.controller.isDegraded;
164
+ }
165
+ bridge(options?: BridgeOptions): Promise<void> {
166
+ return this.controller.bridge(options);
167
+ }
168
+ authenticate(
169
+ methodId: string,
170
+ handlers?: { onOutput?: (line: string) => void },
171
+ ): Promise<unknown> {
172
+ return this.controller.authenticate(methodId, handlers);
173
+ }
174
+
175
+ // --- sessions (merged catalog + live) ----------------------------------------
176
+ /** The merged session list: our catalog ∪ the agent's live list (ACP mode). */
177
+ async listSessions(): Promise<MergedSession[]> {
178
+ let agentEntries: SessionListEntry[] = [];
179
+ if (
180
+ !this.controller.isDegraded &&
181
+ this.controller.capabilities.agent.sessionCapabilities.list
182
+ ) {
183
+ try {
184
+ agentEntries = (await this.controller.listSessions()).sessions;
185
+ } catch {
186
+ /* agent list broken/empty — fall back to catalog only */
187
+ }
188
+ }
189
+ if (this.sessions) return this.sessions.listMerged(agentEntries, this.adapterId);
190
+ return agentEntries.map((e) => ({
191
+ id: e.sessionId,
192
+ agentSessionId: e.sessionId,
193
+ adapter: this.adapterId,
194
+ cwd: e.cwd,
195
+ title: e.title,
196
+ updatedAt: e.updatedAt,
197
+ source: "agent" as const,
198
+ }));
199
+ }
200
+
201
+ private async persist(): Promise<void> {
202
+ if (!this.sessions) return;
203
+ await this.sessions.record({
204
+ id: this.id,
205
+ agentSessionId: this._agentSessionId,
206
+ adapter: this.adapterId,
207
+ mode: this._mode,
208
+ cwd: this._cwd,
209
+ title: this._title,
210
+ });
211
+ }
212
+ }