@qlairoslabs/acp-client 0.4.2 → 0.5.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/CONSUMER_GUIDE.md +10 -0
- package/README.md +38 -7
- package/package.json +1 -1
- package/src/adapters.ts +3 -0
- package/src/agent-session.ts +15 -2
- package/src/cli/adapter.ts +69 -0
- package/src/cli/index.ts +33 -10
- package/src/client.ts +122 -49
- package/src/controller.ts +11 -0
- package/src/degraded/pty-client.ts +22 -14
- package/src/degraded/pty-transport.ts +54 -19
- package/src/index.ts +5 -0
- package/src/launcher.ts +86 -0
- package/src/transport/acp-transport.ts +78 -41
package/CONSUMER_GUIDE.md
CHANGED
|
@@ -67,6 +67,7 @@ can supply any `Adapter` object.
|
|
|
67
67
|
const adapters: Record<string, Adapter> = {
|
|
68
68
|
codex: ADAPTERS.codex,
|
|
69
69
|
claude: ADAPTERS.claude,
|
|
70
|
+
pi: ADAPTERS.pi,
|
|
70
71
|
internal: {
|
|
71
72
|
command: ["internal-agent", "--acp"],
|
|
72
73
|
ptyCommand: ["internal-agent"],
|
|
@@ -84,6 +85,15 @@ function resolveAdapter(adapterId: string): Adapter {
|
|
|
84
85
|
The catalog stores `adapterId`, not executable configuration. This resolver therefore
|
|
85
86
|
belongs to the consumer.
|
|
86
87
|
|
|
88
|
+
Presets do not encode a provider's features. After the process starts, the library
|
|
89
|
+
discovers capabilities, authentication methods, configuration, sessions, and harness
|
|
90
|
+
commands through ACP. The Pi preset targets `@automatalabs/pi-acp`, which embeds Pi through
|
|
91
|
+
its published SDK and installs the `pi-acp` executable. The native `pi` command is used
|
|
92
|
+
only for interactive PTY mode.
|
|
93
|
+
|
|
94
|
+
Install the preset executable globally with `npm install -g @automatalabs/pi-acp`, or use
|
|
95
|
+
`{ command: ["npx", "-y", "@automatalabs/pi-acp"] }` as a custom adapter.
|
|
96
|
+
|
|
87
97
|
## Create the catalog and live-session registry
|
|
88
98
|
|
|
89
99
|
`SessionManager` is a metadata catalog, not a registry of running objects and not a
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @qlairoslabs/acp-client
|
|
2
2
|
|
|
3
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
|
|
4
|
+
agents (Codex, Claude, Kimi, Pi, Gemini, Copilot, OpenCode, …) over JSON-RPC 2.0, with a
|
|
5
5
|
**degraded PTY fallback** for agents that don't speak ACP.
|
|
6
6
|
|
|
7
7
|
```ts
|
|
@@ -28,8 +28,8 @@ assumptions that don't fit when you orchestrate **many** agents across **many**
|
|
|
28
28
|
environments:
|
|
29
29
|
|
|
30
30
|
- **No forced `cwd` discovery.** Other libraries crawl up to the git root and impose a
|
|
31
|
-
working directory. This one
|
|
32
|
-
|
|
31
|
+
working directory. This one keeps target-visible `cwd` separate from an optional
|
|
32
|
+
runtime `launcher` that prepares the exact host process.
|
|
33
33
|
- **Introspection over hardcoding.** Models, auth methods, capabilities, and config
|
|
34
34
|
options are all *discovered* from the protocol at runtime, never baked in. The library
|
|
35
35
|
surfaces raw protocol facts and lets you decide what they mean.
|
|
@@ -61,7 +61,7 @@ bun add -g @qlairoslabs/acp-client
|
|
|
61
61
|
| **`AgentController`** | The control plane for **one** agent process: start/stop, prompt, interrupt, switch sessions, swap mode (normal ⇄ degraded), introspect capabilities & config. |
|
|
62
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
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: [...] }`. |
|
|
64
|
+
| **Adapter** | Just how to *launch* an agent: the spawn command. `ADAPTERS` has convenience presets (`codex`, `claude`, `kimi`, `pi`, `gemini`, `copilot`, `opencode`); you can also pass a raw `{ command: [...] }`. Capabilities and commands are discovered after ACP initialization. |
|
|
65
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
66
|
|
|
67
67
|
---
|
|
@@ -273,16 +273,26 @@ shell line and run through `bash` (or `/bin/sh`), because that is how agents use
|
|
|
273
273
|
`claude-code-acp` puts its whole Bash command line, redirections and all, in `command`.
|
|
274
274
|
Set `ACP_TERMINAL_SHELL` to choose a different shell.
|
|
275
275
|
|
|
276
|
-
|
|
277
|
-
|
|
276
|
+
The built-in handlers operate in the library process's host namespace. For a container,
|
|
277
|
+
VM, SSH session, or other runtime boundary, disable them or provide runtime-aware handlers.
|
|
278
|
+
Handler presence is the source of truth for capability advertisement:
|
|
278
279
|
|
|
279
280
|
```ts
|
|
280
281
|
new AcpClient({
|
|
281
282
|
adapter: ADAPTERS.codex,
|
|
282
|
-
|
|
283
|
+
clientHandlers: {
|
|
284
|
+
terminal: false,
|
|
285
|
+
filesystem: {
|
|
286
|
+
readTextFile: async (request) => containerFs.read(request),
|
|
287
|
+
// write omitted: writeTextFile is not advertised
|
|
288
|
+
},
|
|
289
|
+
},
|
|
283
290
|
});
|
|
284
291
|
```
|
|
285
292
|
|
|
293
|
+
`clientCapabilities` remains as a compatibility option. New `clientHandlers` selections
|
|
294
|
+
take precedence and cannot advertise an operation without installing its implementation.
|
|
295
|
+
|
|
286
296
|
### Durable sessions with a catalog
|
|
287
297
|
|
|
288
298
|
`AgentSession` gives a conversation a stable id that persists across reconnects, and
|
|
@@ -464,6 +474,9 @@ A thin wrapper over the library is exposed as `acp-client`:
|
|
|
464
474
|
acp-client chat # new chat with the default adapter
|
|
465
475
|
acp-client chat <SESSION_ID> # resume a session
|
|
466
476
|
acp-client chat --adapter codex # pick an adapter
|
|
477
|
+
acp-client chat --adapter pi # @automatalabs/pi-acp (the pi-acp binary)
|
|
478
|
+
acp-client chat --adapter private --adapter-command '["private-agent","--acp"]'
|
|
479
|
+
acp-client chat --adapter private --adapter-command private-acp --pty-command private-agent
|
|
467
480
|
acp-client chat --exec "docker exec -i my-container" # talk to an agent in a container
|
|
468
481
|
acp-client chat --cwd /workspace --approve # auto-approve tool permissions
|
|
469
482
|
acp-client chat --degraded # force degraded (PTY) mode
|
|
@@ -473,6 +486,24 @@ acp-client chat --wire[=FILE] # dump every raw protocol line (stderr, or
|
|
|
473
486
|
|
|
474
487
|
Activity markers (thinking/tool) show by default; `--no-activity` disables them.
|
|
475
488
|
|
|
489
|
+
Presets are launch shortcuts, not provider definitions. For a custom harness,
|
|
490
|
+
`--adapter-command` accepts either one executable or a JSON argv array; `--pty-command`
|
|
491
|
+
optionally supplies its interactive/degraded counterpart, and `--adapter-name` sets a
|
|
492
|
+
display label. After launch, auth methods, capabilities, configuration, session support,
|
|
493
|
+
and harness commands are discovered over ACP exactly as they are for a preset.
|
|
494
|
+
|
|
495
|
+
The Pi preset expects the `pi-acp` executable installed by:
|
|
496
|
+
|
|
497
|
+
```bash
|
|
498
|
+
npm install -g @automatalabs/pi-acp
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
Alternatively, run it without a global install as a custom adapter:
|
|
502
|
+
|
|
503
|
+
```bash
|
|
504
|
+
acp-client chat --adapter pi --adapter-command '["npx","-y","@automatalabs/pi-acp"]'
|
|
505
|
+
```
|
|
506
|
+
|
|
476
507
|
---
|
|
477
508
|
|
|
478
509
|
## Package exports
|
package/package.json
CHANGED
package/src/adapters.ts
CHANGED
|
@@ -52,6 +52,9 @@ export const ADAPTERS = {
|
|
|
52
52
|
},
|
|
53
53
|
// verified — @agentclientprotocol/codex-acp. The `codex` CLI has no `acp` subcommand.
|
|
54
54
|
codex: { command: ["codex-acp"], ptyCommand: ["codex"], displayName: "Codex" },
|
|
55
|
+
// @automatalabs/pi-acp embeds Pi through its SDK and publishes the `pi-acp` binary.
|
|
56
|
+
// Pi itself remains the interactive PTY command for bridge/degraded mode.
|
|
57
|
+
pi: { command: ["pi-acp"], ptyCommand: ["pi"], displayName: "Pi" },
|
|
55
58
|
// Below: from each project's docs, not spawned here. Correct at time of writing, unverified.
|
|
56
59
|
gemini: { command: ["gemini", "--acp", "--stdio"], ptyCommand: ["gemini"], displayName: "Gemini" },
|
|
57
60
|
copilot: { command: ["copilot", "--acp", "--stdio"], ptyCommand: ["copilot"], displayName: "Copilot" },
|
package/src/agent-session.ts
CHANGED
|
@@ -191,7 +191,11 @@ export interface AgentSessionConfig {
|
|
|
191
191
|
adapterId: string;
|
|
192
192
|
/** Talk over ACP ("normal") or scrape a pty ("degraded"). Default "normal". */
|
|
193
193
|
mode?: AgentMode;
|
|
194
|
+
/** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
|
|
195
|
+
launcher?: AgentControllerConfig["launcher"];
|
|
196
|
+
/** @deprecated Use launcher. */
|
|
194
197
|
execPrefix?: string[];
|
|
198
|
+
/** @deprecated Use launcher and its exact spawnEnv. */
|
|
195
199
|
env?: Record<string, string>;
|
|
196
200
|
cwd?: string;
|
|
197
201
|
/** Default MCP servers bound at session creation/switch, unless a call overrides them. */
|
|
@@ -200,6 +204,8 @@ export interface AgentSessionConfig {
|
|
|
200
204
|
clientInfo?: { name: string; title?: string; version?: string };
|
|
201
205
|
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
202
206
|
clientCapabilities?: AgentControllerConfig["clientCapabilities"];
|
|
207
|
+
/** Client-side ACP implementations; their presence determines advertisement. */
|
|
208
|
+
clientHandlers?: AgentControllerConfig["clientHandlers"];
|
|
203
209
|
logger?: Logger;
|
|
204
210
|
/** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
|
|
205
211
|
wire?: (entry: WireEntry) => void;
|
|
@@ -321,6 +327,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
321
327
|
adapter: config.adapter,
|
|
322
328
|
adapterId: config.adapterId,
|
|
323
329
|
mode: this._mode,
|
|
330
|
+
launcher: config.launcher,
|
|
324
331
|
execPrefix: config.execPrefix,
|
|
325
332
|
env: config.env,
|
|
326
333
|
cwd: config.cwd,
|
|
@@ -332,6 +339,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
332
339
|
defaultPermission: config.defaultPermission,
|
|
333
340
|
clientInfo: config.clientInfo,
|
|
334
341
|
clientCapabilities: config.clientCapabilities,
|
|
342
|
+
clientHandlers: config.clientHandlers,
|
|
335
343
|
logger: config.logger,
|
|
336
344
|
wire: config.wire,
|
|
337
345
|
});
|
|
@@ -348,8 +356,13 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
348
356
|
*/
|
|
349
357
|
static async create(config: AgentSessionConfig): Promise<AgentSession> {
|
|
350
358
|
const session = new AgentSession(config);
|
|
351
|
-
|
|
352
|
-
|
|
359
|
+
try {
|
|
360
|
+
await session.start();
|
|
361
|
+
return session;
|
|
362
|
+
} catch (error) {
|
|
363
|
+
await session.stop().catch(() => {});
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
353
366
|
}
|
|
354
367
|
|
|
355
368
|
private async start(): Promise<void> {
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
import { ADAPTERS, type Adapter } from "../adapters.ts";
|
|
3
|
+
|
|
4
|
+
export interface CliAdapterSelection {
|
|
5
|
+
/** Preset key, or the stable id assigned to a custom adapter. */
|
|
6
|
+
adapterId?: string;
|
|
7
|
+
/** Explicit ACP launch argv. When present, this takes precedence over presets. */
|
|
8
|
+
command?: string[];
|
|
9
|
+
/** Optional interactive launch argv for degraded mode and bridge. */
|
|
10
|
+
ptyCommand?: string[];
|
|
11
|
+
/** Optional custom display label. */
|
|
12
|
+
displayName?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ResolvedCliAdapter {
|
|
16
|
+
adapterId: string;
|
|
17
|
+
adapter: Adapter;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Parse one CLI command value. A plain value represents one executable; commands with
|
|
22
|
+
* arguments use a JSON string array so paths and arguments containing spaces stay exact.
|
|
23
|
+
*/
|
|
24
|
+
export function parseCommandArg(value: string | undefined, flag: string): string[] {
|
|
25
|
+
if (!value?.trim()) throw new Error(`${flag} requires an executable or JSON argv array`);
|
|
26
|
+
const trimmed = value.trim();
|
|
27
|
+
if (!trimmed.startsWith("[")) return [trimmed];
|
|
28
|
+
|
|
29
|
+
let parsed: unknown;
|
|
30
|
+
try {
|
|
31
|
+
parsed = JSON.parse(trimmed);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
throw new Error(`${flag} must be valid JSON: ${String(error)}`);
|
|
34
|
+
}
|
|
35
|
+
if (
|
|
36
|
+
!Array.isArray(parsed) ||
|
|
37
|
+
parsed.length === 0 ||
|
|
38
|
+
parsed.some((part) => typeof part !== "string" || part.length === 0)
|
|
39
|
+
) {
|
|
40
|
+
throw new Error(`${flag} must be a non-empty JSON array of non-empty strings`);
|
|
41
|
+
}
|
|
42
|
+
return parsed;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Resolve a built-in preset or construct the custom adapter supplied by the CLI user. */
|
|
46
|
+
export function resolveCliAdapter(selection: CliAdapterSelection): ResolvedCliAdapter {
|
|
47
|
+
if (selection.command) {
|
|
48
|
+
if (selection.command.length === 0) throw new Error("custom adapter command cannot be empty");
|
|
49
|
+
const adapterId = selection.adapterId?.trim() || basename(selection.command[0]!) || "custom";
|
|
50
|
+
return {
|
|
51
|
+
adapterId,
|
|
52
|
+
adapter: {
|
|
53
|
+
command: [...selection.command],
|
|
54
|
+
...(selection.ptyCommand ? { ptyCommand: [...selection.ptyCommand] } : {}),
|
|
55
|
+
...(selection.displayName ? { displayName: selection.displayName } : {}),
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const adapterId = selection.adapterId?.trim() || "kimi";
|
|
61
|
+
if (!(adapterId in ADAPTERS)) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`unknown adapter preset: ${adapterId}; known presets: ${Object.keys(ADAPTERS).join(", ")}; ` +
|
|
64
|
+
"use --adapter-command for a custom ACP harness",
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
const adapter = ADAPTERS[adapterId as keyof typeof ADAPTERS];
|
|
68
|
+
return { adapterId, adapter };
|
|
69
|
+
}
|
package/src/cli/index.ts
CHANGED
|
@@ -4,9 +4,11 @@
|
|
|
4
4
|
// See SPEC.md "library first, CLI second".
|
|
5
5
|
//
|
|
6
6
|
// Usage:
|
|
7
|
-
// acp-
|
|
7
|
+
// acp-client chat [SESSION_ID] [--adapter kimi] [--exec "docker exec -i <ctr>"]
|
|
8
8
|
// [--cwd /workspace] [--approve] [--verbose] [--debug]
|
|
9
9
|
// [--no-activity] [--degraded] [--wire[=FILE]]
|
|
10
|
+
// acp-client chat [--adapter ID] --adapter-command '["agent","--acp"]'
|
|
11
|
+
// [--pty-command '["agent"]'] [--adapter-name "My Agent"]
|
|
10
12
|
//
|
|
11
13
|
// activity (thinking/tool markers) shows by DEFAULT; --no-activity disables it.
|
|
12
14
|
// --verbose (-v): lifecycle summaries (connect, session_new, prompt_end)
|
|
@@ -16,18 +18,21 @@
|
|
|
16
18
|
|
|
17
19
|
import {
|
|
18
20
|
AgentController,
|
|
19
|
-
ADAPTERS,
|
|
20
21
|
createConsoleLogger,
|
|
21
22
|
createWireLog,
|
|
22
|
-
type
|
|
23
|
+
type Adapter,
|
|
23
24
|
} from "../index.ts";
|
|
24
25
|
import { createControllerCommands, runRepl } from "../repl/index.ts";
|
|
25
26
|
import { DIM, colorEnabled, paint } from "../repl/colors.ts";
|
|
27
|
+
import { parseCommandArg, resolveCliAdapter } from "./adapter.ts";
|
|
26
28
|
|
|
27
29
|
interface Args {
|
|
28
30
|
command: string;
|
|
29
31
|
sessionId?: string;
|
|
30
|
-
|
|
32
|
+
adapterId?: string;
|
|
33
|
+
adapterCommand?: string[];
|
|
34
|
+
ptyCommand?: string[];
|
|
35
|
+
adapterName?: string;
|
|
31
36
|
execPrefix: string[];
|
|
32
37
|
cwd?: string;
|
|
33
38
|
degraded: boolean;
|
|
@@ -42,7 +47,6 @@ interface Args {
|
|
|
42
47
|
function parseArgs(argv: string[]): Args {
|
|
43
48
|
const a: Args = {
|
|
44
49
|
command: argv[0] ?? "chat",
|
|
45
|
-
adapter: "kimi",
|
|
46
50
|
execPrefix: [],
|
|
47
51
|
degraded: false,
|
|
48
52
|
approve: false,
|
|
@@ -52,7 +56,14 @@ function parseArgs(argv: string[]): Args {
|
|
|
52
56
|
};
|
|
53
57
|
for (let i = 1; i < argv.length; i++) {
|
|
54
58
|
const arg = argv[i];
|
|
55
|
-
if (arg === "--adapter") a.
|
|
59
|
+
if (arg === "--adapter") a.adapterId = argv[++i];
|
|
60
|
+
else if (arg === "--adapter-command") {
|
|
61
|
+
a.adapterCommand = parseCommandArg(argv[++i], "--adapter-command");
|
|
62
|
+
}
|
|
63
|
+
else if (arg === "--pty-command") {
|
|
64
|
+
a.ptyCommand = parseCommandArg(argv[++i], "--pty-command");
|
|
65
|
+
}
|
|
66
|
+
else if (arg === "--adapter-name") a.adapterName = argv[++i];
|
|
56
67
|
else if (arg === "--exec") a.execPrefix = (argv[++i] ?? "").split(" ").filter(Boolean);
|
|
57
68
|
else if (arg === "--cwd") a.cwd = argv[++i];
|
|
58
69
|
else if (arg === "--degraded") a.degraded = true;
|
|
@@ -85,9 +96,16 @@ async function chat(args: Args): Promise<void> {
|
|
|
85
96
|
: createWireLog({ path: args.wire });
|
|
86
97
|
if (args.wire) process.stderr.write(`wire log: ${args.wire}\n`);
|
|
87
98
|
|
|
99
|
+
const resolved = resolveCliAdapter({
|
|
100
|
+
adapterId: args.adapterId,
|
|
101
|
+
command: args.adapterCommand,
|
|
102
|
+
ptyCommand: args.ptyCommand,
|
|
103
|
+
displayName: args.adapterName,
|
|
104
|
+
});
|
|
105
|
+
const adapter: Adapter = resolved.adapter;
|
|
88
106
|
const controller = new AgentController({
|
|
89
|
-
adapter
|
|
90
|
-
adapterId:
|
|
107
|
+
adapter,
|
|
108
|
+
adapterId: resolved.adapterId,
|
|
91
109
|
mode: args.degraded ? "degraded" : "normal",
|
|
92
110
|
execPrefix: args.execPrefix,
|
|
93
111
|
cwd: args.cwd,
|
|
@@ -98,7 +116,7 @@ async function chat(args: Args): Promise<void> {
|
|
|
98
116
|
});
|
|
99
117
|
|
|
100
118
|
const { sessionId, resumed } = await controller.start();
|
|
101
|
-
const label =
|
|
119
|
+
const label = adapter.displayName ?? resolved.adapterId;
|
|
102
120
|
const intro = controller.isDegraded
|
|
103
121
|
? `degraded (pty) session (${label}) — no ACP capabilities · /exit to quit, Ctrl-C to interrupt`
|
|
104
122
|
: `${resumed ? "resumed" : "new"} session ${sessionId} (${label}) — ` +
|
|
@@ -107,7 +125,12 @@ async function chat(args: Args): Promise<void> {
|
|
|
107
125
|
const color = colorEnabled(process.stderr);
|
|
108
126
|
const note = (s: string) => process.stderr.write(paint(color, DIM, s) + "\n");
|
|
109
127
|
|
|
110
|
-
const commands = createControllerCommands({
|
|
128
|
+
const commands = createControllerCommands({
|
|
129
|
+
client: controller,
|
|
130
|
+
note,
|
|
131
|
+
color,
|
|
132
|
+
adapterId: resolved.adapterId,
|
|
133
|
+
});
|
|
111
134
|
|
|
112
135
|
try {
|
|
113
136
|
await runRepl(controller, {
|
package/src/client.ts
CHANGED
|
@@ -8,11 +8,10 @@
|
|
|
8
8
|
import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
|
9
9
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
10
10
|
import type { Adapter } from "./adapters.ts";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
11
|
+
import { AcpTransport, type TerminalHandlers } from "./transport/acp-transport.ts";
|
|
12
|
+
import { prepareLaunch, type AcpLauncher } from "./launcher.ts";
|
|
13
13
|
import {
|
|
14
14
|
parseCapabilities,
|
|
15
|
-
buildClientCapabilities,
|
|
16
15
|
type Capabilities,
|
|
17
16
|
type ClientCapabilities,
|
|
18
17
|
type ClientCapabilityConfig,
|
|
@@ -41,11 +40,16 @@ import type {
|
|
|
41
40
|
export interface AcpClientConfig {
|
|
42
41
|
/** How to launch the agent binary. */
|
|
43
42
|
adapter: Adapter;
|
|
44
|
-
/**
|
|
43
|
+
/** Runtime-specific launcher for exact ACP/PTY host process preparation. */
|
|
44
|
+
launcher?: AcpLauncher;
|
|
45
|
+
/**
|
|
46
|
+
* Prefix merged before the adapter command, e.g. ["docker","exec","-i","<ctr>"].
|
|
47
|
+
* @deprecated Use launcher.
|
|
48
|
+
*/
|
|
45
49
|
execPrefix?: string[];
|
|
46
|
-
/**
|
|
50
|
+
/** @deprecated Use launcher and its exact spawnEnv. */
|
|
47
51
|
env?: Record<string, string>;
|
|
48
|
-
/**
|
|
52
|
+
/** Workspace visible to the ACP target and sent in session requests. */
|
|
49
53
|
cwd?: string;
|
|
50
54
|
/** Resume this session id when startSession() is called. */
|
|
51
55
|
sessionId?: string;
|
|
@@ -59,8 +63,14 @@ export interface AcpClientConfig {
|
|
|
59
63
|
* What we let the agent do through us: filesystem reads/writes and terminals. All
|
|
60
64
|
* enabled by default. Disabling one stops us advertising it, so the agent falls back
|
|
61
65
|
* to its own implementation instead of calling a method we won't answer.
|
|
66
|
+
* @deprecated Use clientHandlers; when a new handler selection is present it wins.
|
|
62
67
|
*/
|
|
63
68
|
clientCapabilities?: ClientCapabilityConfig;
|
|
69
|
+
/**
|
|
70
|
+
* Client-side ACP implementations. Omitted selects the built-in host implementation;
|
|
71
|
+
* false disables implementation and advertisement; custom handlers are advertised.
|
|
72
|
+
*/
|
|
73
|
+
clientHandlers?: AcpClientHandlers;
|
|
64
74
|
/** Diagnostics sink. Omit for a silent library. */
|
|
65
75
|
logger?: Logger;
|
|
66
76
|
/**
|
|
@@ -71,6 +81,51 @@ export interface AcpClientConfig {
|
|
|
71
81
|
wire?: (entry: WireEntry) => void;
|
|
72
82
|
}
|
|
73
83
|
|
|
84
|
+
export interface FilesystemHandlers {
|
|
85
|
+
readTextFile?: (
|
|
86
|
+
params: schema.ReadTextFileRequest,
|
|
87
|
+
) => Promise<schema.ReadTextFileResponse>;
|
|
88
|
+
writeTextFile?: (
|
|
89
|
+
params: schema.WriteTextFileRequest,
|
|
90
|
+
) => Promise<schema.WriteTextFileResponse>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface AcpClientHandlers {
|
|
94
|
+
terminal?: TerminalHandlers | false;
|
|
95
|
+
filesystem?: FilesystemHandlers | false;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface ResolvedClientHandlers {
|
|
99
|
+
terminal: "builtin" | TerminalHandlers | false;
|
|
100
|
+
readTextFile: "builtin" | NonNullable<FilesystemHandlers["readTextFile"]> | false;
|
|
101
|
+
writeTextFile: "builtin" | NonNullable<FilesystemHandlers["writeTextFile"]> | false;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function resolveClientHandlers(
|
|
105
|
+
handlers: AcpClientHandlers | undefined,
|
|
106
|
+
legacy: ClientCapabilityConfig | undefined,
|
|
107
|
+
): ResolvedClientHandlers {
|
|
108
|
+
const terminal = handlers?.terminal !== undefined
|
|
109
|
+
? handlers.terminal
|
|
110
|
+
: legacy?.terminal === false ? false : "builtin";
|
|
111
|
+
|
|
112
|
+
if (handlers?.filesystem === false) {
|
|
113
|
+
return { terminal, readTextFile: false, writeTextFile: false };
|
|
114
|
+
}
|
|
115
|
+
if (handlers?.filesystem) {
|
|
116
|
+
return {
|
|
117
|
+
terminal,
|
|
118
|
+
readTextFile: handlers.filesystem.readTextFile ?? false,
|
|
119
|
+
writeTextFile: handlers.filesystem.writeTextFile ?? false,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
terminal,
|
|
124
|
+
readTextFile: legacy?.fs?.readTextFile === false ? false : "builtin",
|
|
125
|
+
writeTextFile: legacy?.fs?.writeTextFile === false ? false : "builtin",
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
74
129
|
export interface StartSessionOptions {
|
|
75
130
|
/** Resume this session. Defaults to config.sessionId. */
|
|
76
131
|
sessionId?: string;
|
|
@@ -154,10 +209,18 @@ export class AcpClient implements AgentClient {
|
|
|
154
209
|
|
|
155
210
|
private readonly log: Logger;
|
|
156
211
|
private readonly clientCapabilities: ClientCapabilities;
|
|
212
|
+
private readonly handlers: ResolvedClientHandlers;
|
|
157
213
|
|
|
158
214
|
constructor(private config: AcpClientConfig) {
|
|
159
215
|
this.log = config.logger ?? noopLogger;
|
|
160
|
-
this.
|
|
216
|
+
this.handlers = resolveClientHandlers(config.clientHandlers, config.clientCapabilities);
|
|
217
|
+
this.clientCapabilities = {
|
|
218
|
+
fs: {
|
|
219
|
+
readTextFile: this.handlers.readTextFile !== false,
|
|
220
|
+
writeTextFile: this.handlers.writeTextFile !== false,
|
|
221
|
+
},
|
|
222
|
+
terminal: this.handlers.terminal !== false,
|
|
223
|
+
};
|
|
161
224
|
}
|
|
162
225
|
|
|
163
226
|
// --- introspection (populated by connect) -------------------------------------
|
|
@@ -204,13 +267,9 @@ export class AcpClient implements AgentClient {
|
|
|
204
267
|
async connect(): Promise<Capabilities> {
|
|
205
268
|
if (this.transport) return this.capabilities;
|
|
206
269
|
|
|
207
|
-
const
|
|
208
|
-
const isDockerExec = command[0] === "docker";
|
|
209
|
-
|
|
210
|
-
this.log.info("connect", { command, dockerExec: isDockerExec });
|
|
211
|
-
|
|
270
|
+
const launch = await prepareLaunch("acp", this.config.launcher, this.config);
|
|
212
271
|
const caps = this.clientCapabilities;
|
|
213
|
-
this.terminals =
|
|
272
|
+
this.terminals = this.handlers.terminal === "builtin"
|
|
214
273
|
? new TerminalRegistry({
|
|
215
274
|
cwd: this.config.cwd,
|
|
216
275
|
env: this.config.env,
|
|
@@ -218,29 +277,34 @@ export class AcpClient implements AgentClient {
|
|
|
218
277
|
})
|
|
219
278
|
: null;
|
|
220
279
|
|
|
280
|
+
const terminalHandlers = this.handlers.terminal === "builtin"
|
|
281
|
+
? this.terminalHandlers(this.terminals!)
|
|
282
|
+
: this.handlers.terminal || undefined;
|
|
283
|
+
const readHandler = this.handlers.readTextFile === "builtin"
|
|
284
|
+
? async (p: schema.ReadTextFileRequest) => ({ content: await readTextFile(p) })
|
|
285
|
+
: this.handlers.readTextFile || undefined;
|
|
286
|
+
const writeHandler = this.handlers.writeTextFile === "builtin"
|
|
287
|
+
? async (p: schema.WriteTextFileRequest) => {
|
|
288
|
+
await writeTextFile(p);
|
|
289
|
+
return {};
|
|
290
|
+
}
|
|
291
|
+
: this.handlers.writeTextFile || undefined;
|
|
292
|
+
|
|
221
293
|
const transport = new AcpTransport({
|
|
222
|
-
|
|
223
|
-
// docker exec resolves paths inside the container's namespace — don't pass a host cwd.
|
|
224
|
-
cwd: isDockerExec ? undefined : this.config.cwd,
|
|
225
|
-
env: this.config.env,
|
|
294
|
+
launch,
|
|
226
295
|
onUpdate: (n) => this.handleUpdate(n),
|
|
227
296
|
onPermissionRequest: (p) => this.handlePermission(p),
|
|
228
|
-
onReadTextFile:
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
onWriteTextFile: caps.fs.writeTextFile
|
|
232
|
-
? async (p) => {
|
|
233
|
-
await writeTextFile(p);
|
|
234
|
-
return {};
|
|
235
|
-
}
|
|
236
|
-
: undefined,
|
|
237
|
-
terminals: this.terminals ? this.terminalHandlers(this.terminals) : undefined,
|
|
297
|
+
onReadTextFile: readHandler,
|
|
298
|
+
onWriteTextFile: writeHandler,
|
|
299
|
+
terminals: terminalHandlers,
|
|
238
300
|
onWire: this.config.wire,
|
|
239
301
|
onStderr: (line) => {
|
|
240
302
|
this.log.debug("agent_stderr", { line });
|
|
241
303
|
this.authStderrSink?.(line);
|
|
242
304
|
},
|
|
243
305
|
onCrash: (code) => {
|
|
306
|
+
this.terminals?.releaseAll();
|
|
307
|
+
this.terminals = null;
|
|
244
308
|
this.transport = null;
|
|
245
309
|
this._sessionId = null;
|
|
246
310
|
this.commandTransition = null;
|
|
@@ -248,28 +312,37 @@ export class AcpClient implements AgentClient {
|
|
|
248
312
|
this.log.error("process_exit", { code });
|
|
249
313
|
},
|
|
250
314
|
});
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
315
|
+
try {
|
|
316
|
+
this.log.info("connect", { command: launch.command });
|
|
317
|
+
await transport.start();
|
|
318
|
+
this.transport = transport;
|
|
319
|
+
|
|
320
|
+
const init = await transport.raceExit(
|
|
321
|
+
transport.initialize({
|
|
322
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
323
|
+
clientCapabilities: caps as unknown as schema.ClientCapabilities,
|
|
324
|
+
clientInfo: this.config.clientInfo ?? {
|
|
325
|
+
name: "acp-lib",
|
|
326
|
+
title: "ACP Lib",
|
|
327
|
+
version: "0.1.0",
|
|
328
|
+
},
|
|
329
|
+
} as schema.InitializeRequest),
|
|
330
|
+
);
|
|
331
|
+
this._capabilities = parseCapabilities(init, caps);
|
|
332
|
+
this.log.info("initialized", {
|
|
333
|
+
agent: this._capabilities.agentInfo?.name,
|
|
334
|
+
protocolVersion: this._capabilities.protocolVersion,
|
|
335
|
+
loadSession: this._capabilities.agent.loadSession,
|
|
336
|
+
});
|
|
337
|
+
this.log.debug("initialize_response", { response: init });
|
|
338
|
+
return this._capabilities;
|
|
339
|
+
} catch (error) {
|
|
340
|
+
this.transport = null;
|
|
341
|
+
await transport.stop().catch((cleanupError) => {
|
|
342
|
+
this.log.warn("launch_cleanup_failed", { error: String(cleanupError) });
|
|
343
|
+
});
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
273
346
|
}
|
|
274
347
|
|
|
275
348
|
/**
|
package/src/controller.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from ".
|
|
|
11
11
|
import type { Capabilities } from "./capabilities.ts";
|
|
12
12
|
import type { ConfigOption, ConfigOptions } from "./config-options.ts";
|
|
13
13
|
import type { Logger } from "./logger.ts";
|
|
14
|
+
import type { AcpLauncher } from "./launcher.ts";
|
|
14
15
|
import type {
|
|
15
16
|
InternalSessionCommand,
|
|
16
17
|
Attachment,
|
|
@@ -38,7 +39,11 @@ export interface AgentControllerConfig {
|
|
|
38
39
|
adapterId: string;
|
|
39
40
|
/** How to talk to the agent on start(). Default "normal". */
|
|
40
41
|
mode?: AgentMode;
|
|
42
|
+
/** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
|
|
43
|
+
launcher?: AcpLauncher;
|
|
44
|
+
/** @deprecated Use launcher. */
|
|
41
45
|
execPrefix?: string[];
|
|
46
|
+
/** @deprecated Use launcher and its exact spawnEnv. */
|
|
42
47
|
env?: Record<string, string>;
|
|
43
48
|
cwd?: string;
|
|
44
49
|
/** Session id to load on start(). */
|
|
@@ -51,6 +56,8 @@ export interface AgentControllerConfig {
|
|
|
51
56
|
clientInfo?: AcpClientConfig["clientInfo"];
|
|
52
57
|
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
53
58
|
clientCapabilities?: AcpClientConfig["clientCapabilities"];
|
|
59
|
+
/** Client-side ACP implementations; their presence determines advertisement. */
|
|
60
|
+
clientHandlers?: AcpClientConfig["clientHandlers"];
|
|
54
61
|
logger?: Logger;
|
|
55
62
|
/** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
|
|
56
63
|
wire?: (entry: WireEntry) => void;
|
|
@@ -196,6 +203,7 @@ export class AgentController implements AgentClient {
|
|
|
196
203
|
const { PtyClient } = await import("./degraded/index.ts");
|
|
197
204
|
const pty = new PtyClient({
|
|
198
205
|
adapter: this.config.adapter,
|
|
206
|
+
launcher: this.config.launcher,
|
|
199
207
|
execPrefix: this.config.execPrefix,
|
|
200
208
|
env: this.config.env,
|
|
201
209
|
cwd: this.config.cwd,
|
|
@@ -379,6 +387,7 @@ export class AgentController implements AgentClient {
|
|
|
379
387
|
const { PtyClient } = await import("./degraded/index.ts");
|
|
380
388
|
const client = new PtyClient({
|
|
381
389
|
adapter,
|
|
390
|
+
launcher: this.config.launcher,
|
|
382
391
|
execPrefix: this.config.execPrefix,
|
|
383
392
|
env: this.config.env,
|
|
384
393
|
cwd: this.config.cwd,
|
|
@@ -395,6 +404,7 @@ export class AgentController implements AgentClient {
|
|
|
395
404
|
|
|
396
405
|
const client = new AcpClient({
|
|
397
406
|
adapter,
|
|
407
|
+
launcher: this.config.launcher,
|
|
398
408
|
execPrefix: this.config.execPrefix,
|
|
399
409
|
env: this.config.env,
|
|
400
410
|
cwd: this.config.cwd,
|
|
@@ -403,6 +413,7 @@ export class AgentController implements AgentClient {
|
|
|
403
413
|
defaultPermission: this.config.defaultPermission,
|
|
404
414
|
clientInfo: this.config.clientInfo,
|
|
405
415
|
clientCapabilities: this.config.clientCapabilities,
|
|
416
|
+
clientHandlers: this.config.clientHandlers,
|
|
406
417
|
logger: this.config.logger,
|
|
407
418
|
wire: this.config.wire,
|
|
408
419
|
});
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "../agent-client.ts";
|
|
14
14
|
import type { Adapter } from "../adapters.ts";
|
|
15
|
-
import {
|
|
15
|
+
import { prepareLaunch, type AcpLauncher } from "../launcher.ts";
|
|
16
16
|
import type { ScreenParser } from "../parser/types.ts";
|
|
17
17
|
import type { PromptResult, PromptHandlers, Attachment } from "../types.ts";
|
|
18
18
|
import { noopLogger, type Logger } from "../logger.ts";
|
|
@@ -26,7 +26,11 @@ const ESC = "\x1b";
|
|
|
26
26
|
|
|
27
27
|
export interface PtyClientOptions {
|
|
28
28
|
adapter: Adapter;
|
|
29
|
+
/** Runtime-specific launcher for exact ACP/PTY host process preparation. */
|
|
30
|
+
launcher?: AcpLauncher;
|
|
31
|
+
/** @deprecated Use launcher. */
|
|
29
32
|
execPrefix?: string[];
|
|
33
|
+
/** @deprecated Use launcher and its exact spawnEnv. */
|
|
30
34
|
env?: Record<string, string>;
|
|
31
35
|
cwd?: string;
|
|
32
36
|
/** Optional smart parser (SML/heuristic). Absent → deterministic extractReply. */
|
|
@@ -80,14 +84,9 @@ export class PtyClient implements AgentClient, Bridgeable {
|
|
|
80
84
|
/** Spawn the interactive CLI and wait for its banner/prompt to settle. */
|
|
81
85
|
async start(): Promise<void> {
|
|
82
86
|
if (this.transport) return;
|
|
83
|
-
const
|
|
84
|
-
this.log.info("pty_connect", { command });
|
|
85
|
-
|
|
86
|
-
this.screen = new EmulatorScreen({ cols: this.cols, rows: this.rows });
|
|
87
|
+
const launch = await prepareLaunch("pty", this.opts.launcher, this.opts);
|
|
87
88
|
const transport = new PtyTransport({
|
|
88
|
-
|
|
89
|
-
cwd: this.opts.cwd,
|
|
90
|
-
env: this.opts.env,
|
|
89
|
+
launch,
|
|
91
90
|
cols: this.cols,
|
|
92
91
|
rows: this.rows,
|
|
93
92
|
onData: (data) => this.onData(data),
|
|
@@ -97,12 +96,21 @@ export class PtyClient implements AgentClient, Bridgeable {
|
|
|
97
96
|
void this.finishTurn("end_turn");
|
|
98
97
|
},
|
|
99
98
|
});
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
99
|
+
try {
|
|
100
|
+
this.log.info("pty_connect", { command: launch.command });
|
|
101
|
+
this.screen = new EmulatorScreen({ cols: this.cols, rows: this.rows });
|
|
102
|
+
await transport.start();
|
|
103
|
+
this.transport = transport;
|
|
104
|
+
|
|
105
|
+
// Drain the startup banner so the first prompt's response isn't polluted by it.
|
|
106
|
+
await this.waitIdle();
|
|
107
|
+
this.log.debug("pty_ready", {});
|
|
108
|
+
} catch (error) {
|
|
109
|
+
await transport.stop().catch((cleanupError) => {
|
|
110
|
+
this.log.warn("pty_launch_cleanup_failed", { error: String(cleanupError) });
|
|
111
|
+
});
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
106
114
|
}
|
|
107
115
|
|
|
108
116
|
prompt(
|
|
@@ -8,11 +8,16 @@
|
|
|
8
8
|
// event callbacks. Everything above stays pty-plumbing-agnostic.
|
|
9
9
|
|
|
10
10
|
import { ProcessCrashError } from "../errors.ts";
|
|
11
|
+
import { onceDispose, type PreparedLaunch } from "../launcher.ts";
|
|
11
12
|
|
|
12
13
|
export interface PtyTransportOptions {
|
|
13
|
-
/**
|
|
14
|
-
|
|
14
|
+
/** Exact host-side process launch, already resolved by the caller's launcher. */
|
|
15
|
+
launch?: PreparedLaunch;
|
|
16
|
+
/** @deprecated Pass launch. */
|
|
17
|
+
command?: string[];
|
|
18
|
+
/** @deprecated Pass launch.spawnCwd. */
|
|
15
19
|
cwd?: string;
|
|
20
|
+
/** @deprecated Pass launch.spawnEnv. Legacy values overlay process.env. */
|
|
16
21
|
env?: Record<string, string>;
|
|
17
22
|
cols?: number;
|
|
18
23
|
rows?: number;
|
|
@@ -35,40 +40,68 @@ export class PtyTransport {
|
|
|
35
40
|
private proc: ReturnType<typeof Bun.spawn> | null = null;
|
|
36
41
|
private terminal: BunTerminal | null = null;
|
|
37
42
|
private stopping = false;
|
|
43
|
+
private readonly disposeLaunch: () => Promise<void>;
|
|
44
|
+
private readonly launch: PreparedLaunch;
|
|
38
45
|
|
|
39
|
-
constructor(private opts: PtyTransportOptions) {
|
|
46
|
+
constructor(private opts: PtyTransportOptions) {
|
|
47
|
+
if (opts.launch) {
|
|
48
|
+
this.launch = opts.launch;
|
|
49
|
+
} else {
|
|
50
|
+
if (!opts.command?.length) throw new Error("PtyTransport requires launch or command");
|
|
51
|
+
this.launch = {
|
|
52
|
+
command: opts.command,
|
|
53
|
+
spawnCwd: opts.cwd,
|
|
54
|
+
spawnEnv: {
|
|
55
|
+
...(process.env as Record<string, string>),
|
|
56
|
+
...(opts.env ?? {}),
|
|
57
|
+
TERM: opts.env?.TERM ?? "xterm-color",
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
this.disposeLaunch = onceDispose(this.launch.dispose);
|
|
62
|
+
}
|
|
40
63
|
|
|
41
64
|
async start(): Promise<void> {
|
|
42
65
|
if (this.proc) return;
|
|
43
66
|
const dec = new TextDecoder();
|
|
44
67
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
if (text) this.opts.onData?.(text);
|
|
68
|
+
let proc: ReturnType<typeof Bun.spawn>;
|
|
69
|
+
try {
|
|
70
|
+
proc = Bun.spawn(this.launch.command, {
|
|
71
|
+
cwd: this.launch.spawnCwd,
|
|
72
|
+
env: this.launch.spawnEnv,
|
|
73
|
+
terminal: {
|
|
74
|
+
cols: this.opts.cols ?? 80,
|
|
75
|
+
rows: this.opts.rows ?? 24,
|
|
76
|
+
data: (_term: unknown, data: Uint8Array) => {
|
|
77
|
+
const text = dec.decode(data, { stream: true });
|
|
78
|
+
if (text) this.opts.onData?.(text);
|
|
79
|
+
},
|
|
58
80
|
},
|
|
59
|
-
}
|
|
60
|
-
}
|
|
81
|
+
} as Parameters<typeof Bun.spawn>[1]);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
await this.disposeLaunch().catch(() => {});
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
61
86
|
|
|
62
87
|
this.proc = proc;
|
|
63
88
|
this.terminal = (proc as unknown as { terminal: BunTerminal }).terminal ?? null;
|
|
64
89
|
|
|
65
90
|
proc.exited
|
|
66
|
-
.then((code) => {
|
|
91
|
+
.then(async (code) => {
|
|
67
92
|
if (this.proc === proc && !this.stopping) {
|
|
68
93
|
this.proc = null;
|
|
69
94
|
this.terminal = null;
|
|
95
|
+
await this.disposeLaunch().catch(() => {});
|
|
70
96
|
this.opts.onExit?.(code ?? null);
|
|
71
97
|
}
|
|
98
|
+
}, async () => {
|
|
99
|
+
if (this.proc === proc && !this.stopping) {
|
|
100
|
+
this.proc = null;
|
|
101
|
+
this.terminal = null;
|
|
102
|
+
await this.disposeLaunch().catch(() => {});
|
|
103
|
+
this.opts.onExit?.(null);
|
|
104
|
+
}
|
|
72
105
|
})
|
|
73
106
|
.catch(() => {});
|
|
74
107
|
}
|
|
@@ -120,8 +153,10 @@ export class PtyTransport {
|
|
|
120
153
|
} catch {
|
|
121
154
|
/* gone */
|
|
122
155
|
}
|
|
156
|
+
await proc.exited.catch(() => {});
|
|
123
157
|
}
|
|
124
158
|
}
|
|
159
|
+
await this.disposeLaunch();
|
|
125
160
|
}
|
|
126
161
|
|
|
127
162
|
get running(): boolean {
|
package/src/index.ts
CHANGED
|
@@ -11,8 +11,12 @@ export type {
|
|
|
11
11
|
SwitchSessionOptions,
|
|
12
12
|
ConnectResult,
|
|
13
13
|
SessionLoadFailure,
|
|
14
|
+
AcpClientHandlers,
|
|
15
|
+
FilesystemHandlers,
|
|
14
16
|
} from "./client.ts";
|
|
15
17
|
|
|
18
|
+
export type { AcpLauncher, PreparedLaunch, LaunchKind } from "./launcher.ts";
|
|
19
|
+
|
|
16
20
|
export {
|
|
17
21
|
AgentController,
|
|
18
22
|
parseConfigValue,
|
|
@@ -68,6 +72,7 @@ export type {
|
|
|
68
72
|
TerminalOutput,
|
|
69
73
|
TerminalRegistryOptions,
|
|
70
74
|
} from "./terminals.ts";
|
|
75
|
+
export type { TerminalHandlers } from "./transport/acp-transport.ts";
|
|
71
76
|
|
|
72
77
|
export { extractChunkText, extractResponseChunk, toActivityEvent } from "./updates.ts";
|
|
73
78
|
|
package/src/launcher.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { Adapter } from "./adapters.ts";
|
|
2
|
+
import { buildPtyCommand, buildSpawnCommand } from "./adapters.ts";
|
|
3
|
+
|
|
4
|
+
export type LaunchKind = "acp" | "pty";
|
|
5
|
+
|
|
6
|
+
/** A fully resolved host process launch. The environment is exact, not an overlay. */
|
|
7
|
+
export interface PreparedLaunch {
|
|
8
|
+
command: string[];
|
|
9
|
+
spawnCwd?: string;
|
|
10
|
+
/** Complete environment for the directly spawned process. */
|
|
11
|
+
spawnEnv: Record<string, string>;
|
|
12
|
+
/** Release resources created while preparing this launch. Called exactly once. */
|
|
13
|
+
dispose?: () => void | Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Translates an adapter command into a runtime-specific host process launch. */
|
|
17
|
+
export interface AcpLauncher {
|
|
18
|
+
prepare(request: {
|
|
19
|
+
kind: LaunchKind;
|
|
20
|
+
targetCommand: readonly string[];
|
|
21
|
+
}): Promise<PreparedLaunch>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface LegacyLaunchOptions {
|
|
25
|
+
adapter: Adapter;
|
|
26
|
+
execPrefix?: string[];
|
|
27
|
+
env?: Record<string, string>;
|
|
28
|
+
cwd?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Resolve the new launcher contract, or reproduce the historical adapter/execPrefix
|
|
33
|
+
* behavior for callers that have not migrated yet.
|
|
34
|
+
*/
|
|
35
|
+
export async function prepareLaunch(
|
|
36
|
+
kind: LaunchKind,
|
|
37
|
+
launcher: AcpLauncher | undefined,
|
|
38
|
+
legacy: LegacyLaunchOptions,
|
|
39
|
+
): Promise<PreparedLaunch> {
|
|
40
|
+
const targetCommand = kind === "acp" ? legacy.adapter.command : legacy.adapter.ptyCommand;
|
|
41
|
+
if (!targetCommand?.length) {
|
|
42
|
+
// Preserve buildPtyCommand's established error for adapters without a PTY command.
|
|
43
|
+
if (kind === "pty") buildPtyCommand(legacy.adapter);
|
|
44
|
+
throw new Error("adapter command cannot be empty");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (launcher) {
|
|
48
|
+
const prepared = await launcher.prepare({ kind, targetCommand: [...targetCommand] });
|
|
49
|
+
if (!prepared.command.length) {
|
|
50
|
+
await prepared.dispose?.();
|
|
51
|
+
throw new Error("launcher returned an empty command");
|
|
52
|
+
}
|
|
53
|
+
if (prepared.spawnEnv == null) {
|
|
54
|
+
await prepared.dispose?.();
|
|
55
|
+
throw new Error("launcher must return a complete spawnEnv");
|
|
56
|
+
}
|
|
57
|
+
return prepared;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const command = kind === "acp"
|
|
61
|
+
? buildSpawnCommand(legacy.adapter, legacy.execPrefix)
|
|
62
|
+
: buildPtyCommand(legacy.adapter, legacy.execPrefix);
|
|
63
|
+
const env = {
|
|
64
|
+
...(process.env as Record<string, string>),
|
|
65
|
+
...(legacy.env ?? {}),
|
|
66
|
+
};
|
|
67
|
+
if (kind === "pty") env.TERM = legacy.env?.TERM ?? "xterm-color";
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
command,
|
|
71
|
+
// This inference exists only in the compatibility adapter. Explicit launchers own cwd.
|
|
72
|
+
spawnCwd: kind === "acp" && command[0] === "docker" ? undefined : legacy.cwd,
|
|
73
|
+
spawnEnv: env,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Wrap a prepared launch's cleanup in an exactly-once async operation. */
|
|
78
|
+
export function onceDispose(dispose?: PreparedLaunch["dispose"]): () => Promise<void> {
|
|
79
|
+
let result: Promise<void> | null = null;
|
|
80
|
+
return () => {
|
|
81
|
+
result ??= Promise.resolve().then(async () => {
|
|
82
|
+
await dispose?.();
|
|
83
|
+
});
|
|
84
|
+
return result;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import * as acp from "@agentclientprotocol/sdk";
|
|
7
7
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
8
8
|
import { ProcessCrashError } from "../errors.ts";
|
|
9
|
+
import { onceDispose, type PreparedLaunch } from "../launcher.ts";
|
|
9
10
|
import type { WireEntry } from "../types.ts";
|
|
10
11
|
|
|
11
12
|
/** The five `terminal/*` methods a client that advertises `terminal: true` must serve. */
|
|
@@ -20,11 +21,8 @@ export interface TerminalHandlers {
|
|
|
20
21
|
}
|
|
21
22
|
|
|
22
23
|
export interface AcpTransportOptions {
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
/** cwd for the spawned process. Omit for `docker exec` (host path won't resolve in-container). */
|
|
26
|
-
cwd?: string;
|
|
27
|
-
env?: Record<string, string>;
|
|
24
|
+
/** Exact host-side process launch, already resolved by the caller's launcher. */
|
|
25
|
+
launch: PreparedLaunch;
|
|
28
26
|
|
|
29
27
|
/**
|
|
30
28
|
* A session/update notification arrived, exactly as the agent sent it — the transport
|
|
@@ -67,8 +65,11 @@ export class AcpTransport {
|
|
|
67
65
|
private connection: acp.ClientSideConnection | null = null;
|
|
68
66
|
private stopping = false;
|
|
69
67
|
private tap?: (dir: WireEntry["dir"], line: string) => void;
|
|
68
|
+
private readonly disposeLaunch: () => Promise<void>;
|
|
70
69
|
|
|
71
|
-
constructor(private opts: AcpTransportOptions) {
|
|
70
|
+
constructor(private opts: AcpTransportOptions) {
|
|
71
|
+
this.disposeLaunch = onceDispose(opts.launch.dispose);
|
|
72
|
+
}
|
|
72
73
|
|
|
73
74
|
async start(): Promise<void> {
|
|
74
75
|
if (this.proc) return;
|
|
@@ -77,54 +78,90 @@ export class AcpTransport {
|
|
|
77
78
|
// Bun's FileSink (from stdin:"pipe") lacks getWriter().
|
|
78
79
|
const stdinTransform = new TransformStream<Uint8Array, Uint8Array>();
|
|
79
80
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
81
|
+
let proc: ReturnType<typeof Bun.spawn>;
|
|
82
|
+
try {
|
|
83
|
+
proc = Bun.spawn(this.opts.launch.command, {
|
|
84
|
+
cwd: this.opts.launch.spawnCwd,
|
|
85
|
+
env: this.opts.launch.spawnEnv,
|
|
86
|
+
stdin: stdinTransform.readable,
|
|
87
|
+
stdout: "pipe",
|
|
88
|
+
stderr: "pipe",
|
|
89
|
+
});
|
|
90
|
+
} catch (error) {
|
|
91
|
+
await this.disposeLaunch().catch(() => {});
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
87
94
|
this.proc = proc;
|
|
88
95
|
|
|
89
|
-
|
|
90
|
-
|
|
96
|
+
try {
|
|
97
|
+
const wire = this.opts.onWire;
|
|
98
|
+
const tap = wire ? (dir: WireEntry["dir"], line: string) => wire({ dir, ts: Date.now(), line }) : undefined;
|
|
91
99
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
100
|
+
const stream = acp.ndJsonStream(
|
|
101
|
+
// Outgoing bytes are forwarded untouched; the tap only reads them on the way past.
|
|
102
|
+
tap ? tapOutgoing(stdinTransform.writable, (line) => tap("out", line)) : stdinTransform.writable,
|
|
103
|
+
interceptUpdates(
|
|
104
|
+
proc.stdout as ReadableStream<Uint8Array>,
|
|
105
|
+
(m) => this.opts.onUpdate?.(m.params as schema.SessionNotification),
|
|
106
|
+
tap && ((line) => tap("in", line)),
|
|
107
|
+
),
|
|
108
|
+
);
|
|
109
|
+
this.tap = tap;
|
|
110
|
+
const handler = new ClientHandler(this.opts);
|
|
111
|
+
this.connection = new acp.ClientSideConnection(() => handler, stream);
|
|
104
112
|
|
|
105
|
-
|
|
113
|
+
if (proc.stderr) this.pumpStderr(proc.stderr as ReadableStream<Uint8Array>);
|
|
106
114
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
115
|
+
proc.exited
|
|
116
|
+
.then(async (code) => {
|
|
117
|
+
if (this.proc === proc && !this.stopping) {
|
|
118
|
+
this.proc = null;
|
|
119
|
+
this.connection = null;
|
|
120
|
+
await this.disposeLaunch().catch(() => {});
|
|
121
|
+
this.opts.onCrash?.(code ?? null);
|
|
122
|
+
}
|
|
123
|
+
}, async () => {
|
|
124
|
+
if (this.proc === proc && !this.stopping) {
|
|
125
|
+
this.proc = null;
|
|
126
|
+
this.connection = null;
|
|
127
|
+
await this.disposeLaunch().catch(() => {});
|
|
128
|
+
this.opts.onCrash?.(null);
|
|
129
|
+
}
|
|
130
|
+
})
|
|
131
|
+
.catch(() => {});
|
|
132
|
+
} catch (error) {
|
|
133
|
+
await this.stop().catch(() => {});
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
116
136
|
}
|
|
117
137
|
|
|
118
138
|
async stop(): Promise<void> {
|
|
119
139
|
this.stopping = true;
|
|
120
|
-
|
|
140
|
+
const proc = this.proc;
|
|
141
|
+
this.proc = null;
|
|
142
|
+
this.connection = null;
|
|
143
|
+
if (!proc) {
|
|
144
|
+
await this.disposeLaunch();
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
121
147
|
try {
|
|
122
|
-
|
|
148
|
+
proc.kill("SIGTERM");
|
|
123
149
|
} catch {
|
|
124
150
|
/* already exited */
|
|
125
151
|
}
|
|
126
|
-
|
|
127
|
-
|
|
152
|
+
const exited = await Promise.race([
|
|
153
|
+
proc.exited.then(() => true, () => true),
|
|
154
|
+
new Promise<boolean>((resolve) => setTimeout(() => resolve(false), 500)),
|
|
155
|
+
]);
|
|
156
|
+
if (!exited) {
|
|
157
|
+
try {
|
|
158
|
+
proc.kill("SIGKILL");
|
|
159
|
+
} catch {
|
|
160
|
+
/* already exited */
|
|
161
|
+
}
|
|
162
|
+
await proc.exited.catch(() => {});
|
|
163
|
+
}
|
|
164
|
+
await this.disposeLaunch();
|
|
128
165
|
}
|
|
129
166
|
|
|
130
167
|
private conn(): acp.ClientSideConnection {
|