@qlairoslabs/acp-client 0.1.2 → 0.2.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/README.md +78 -1
- package/package.json +1 -1
- package/src/agent-session.ts +152 -9
- package/src/capabilities.ts +30 -3
- package/src/client.ts +85 -8
- package/src/controller.ts +3 -0
- package/src/fs-access.ts +38 -0
- package/src/index.ts +34 -0
- package/src/repl/repl.ts +11 -1
- package/src/terminals.ts +273 -0
- package/src/transcript.ts +151 -0
- package/src/transport/acp-transport.ts +107 -18
- package/src/types.ts +101 -10
- package/src/updates.ts +127 -13
package/README.md
CHANGED
|
@@ -95,7 +95,8 @@ await agent.stop();
|
|
|
95
95
|
```ts
|
|
96
96
|
await agent.prompt("Find and fix the failing test.", {
|
|
97
97
|
onChunk: (text) => process.stdout.write(text), // response text as it streams
|
|
98
|
-
onActivity: (event) =>
|
|
98
|
+
onActivity: (event) => render(event), // thinking / tool calls / plan / …
|
|
99
|
+
onUpdate: (raw) => log(raw), // every raw session/update, unmapped
|
|
99
100
|
onPermissionRequest: (req) => ({ outcome: "selected", optionId: req.options[0].optionId }),
|
|
100
101
|
});
|
|
101
102
|
```
|
|
@@ -103,6 +104,55 @@ await agent.prompt("Find and fix the failing test.", {
|
|
|
103
104
|
If you omit `onPermissionRequest`, the client falls back to the controller's
|
|
104
105
|
`defaultPermission` (`"approve"` / `"cancel"`).
|
|
105
106
|
|
|
107
|
+
Every session update except the response text reaches `onActivity`, discriminated by
|
|
108
|
+
`kind`: `thinking`, `user_message`, `tool`, `tool_update`, `plan`, `plan_update`,
|
|
109
|
+
`plan_removed`, `commands`, `mode`, `usage`, `session_info`, `config`, and `unknown` for
|
|
110
|
+
anything the protocol adds later (the raw payload rides along on `raw`).
|
|
111
|
+
|
|
112
|
+
**Tool calls arrive incrementally, and you must merge them.** Agents announce a call
|
|
113
|
+
before they know much about it and fill it in afterwards, so the command, the diff and
|
|
114
|
+
the output usually land on a later `tool_update` — not on the initial `tool`:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
const calls = new Map<string, ToolActivity>();
|
|
118
|
+
|
|
119
|
+
onActivity: (event) => {
|
|
120
|
+
if (event.kind === "tool") calls.set(event.toolCallId, event);
|
|
121
|
+
if (event.kind === "tool_update") {
|
|
122
|
+
// Only the fields the agent CHANGED are present. Absent means unchanged —
|
|
123
|
+
// spreading is exactly right. `content` and `locations` REPLACE wholesale
|
|
124
|
+
// (the schema says "replace the content collection"): never concatenate them,
|
|
125
|
+
// agents that stream a growing tool input resend the whole value each time.
|
|
126
|
+
const call = calls.get(event.toolCallId);
|
|
127
|
+
if (call) calls.set(event.toolCallId, { ...call, ...event, kind: "tool" });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`event.content` is where the output lives — `{type:"content"}` (with `text` pre-extracted
|
|
133
|
+
for text blocks), `{type:"diff"}`, `{type:"terminal"}`, or `{type:"other"}` with the raw
|
|
134
|
+
payload for shapes we don't model.
|
|
135
|
+
|
|
136
|
+
### Terminals and filesystem access
|
|
137
|
+
|
|
138
|
+
The client advertises the `terminal` and `fs` client capabilities and implements them:
|
|
139
|
+
agents route their shell commands through `terminal/create` and read/write files through
|
|
140
|
+
`fs/read_text_file` and `fs/write_text_file` on us. Terminal tool calls carry only a
|
|
141
|
+
`terminalId` over the wire; the client resolves the live output before handing you the
|
|
142
|
+
event, so `content` entries of type `terminal` come with `output`, `truncated` and
|
|
143
|
+
`exitStatus` filled in.
|
|
144
|
+
|
|
145
|
+
Commands run as child processes of your app, with your environment. To opt out — letting
|
|
146
|
+
the agent fall back to its own implementation — turn the capability off, which also stops
|
|
147
|
+
us advertising it:
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
new AcpClient({
|
|
151
|
+
adapter: ADAPTERS.codex,
|
|
152
|
+
clientCapabilities: { terminal: false, fs: { writeTextFile: false } },
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
106
156
|
### Durable sessions with a catalog
|
|
107
157
|
|
|
108
158
|
`AgentSession` gives a conversation a stable id that persists across reconnects, and
|
|
@@ -134,6 +184,33 @@ for (const s of await session.listSessions()) {
|
|
|
134
184
|
await session.stop();
|
|
135
185
|
```
|
|
136
186
|
|
|
187
|
+
### Optional chat transcript
|
|
188
|
+
|
|
189
|
+
Pass `transcriptPath` or `transcriptDir` to `AgentSession` to append a lightweight JSONL
|
|
190
|
+
chat transcript that can be read later without starting the agent. `transcriptPath` is an
|
|
191
|
+
exact file path chosen by the caller; `transcriptDir` lets the library write
|
|
192
|
+
`<agentSessionId>.jsonl` inside that directory. Supplying both is a config error.
|
|
193
|
+
|
|
194
|
+
The transcript stores user messages and final assistant replies. Set
|
|
195
|
+
`transcriptActivity: true` to also record tool calls, thinking and plans as `t:"activity"`
|
|
196
|
+
lines — `readTranscript()` still returns messages only, so read those back with
|
|
197
|
+
`readTranscriptLines()`.
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
import { AgentSession, ADAPTERS, readTranscript } from "@qlairoslabs/acp-client";
|
|
201
|
+
|
|
202
|
+
const session = await AgentSession.create({
|
|
203
|
+
adapter: ADAPTERS.codex,
|
|
204
|
+
adapterId: "codex",
|
|
205
|
+
agentSessionId: "conv-123",
|
|
206
|
+
transcriptDir: "/absolute/path/to/chats",
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
await session.prompt("Summarize the repo.");
|
|
210
|
+
|
|
211
|
+
const messages = await readTranscript("/absolute/path/to/chats/conv-123.jsonl");
|
|
212
|
+
```
|
|
213
|
+
|
|
137
214
|
### Interactive REPL
|
|
138
215
|
|
|
139
216
|
The REPL and its slash-commands (`/help`, `/new`, `/sessions`, `/load`, `/config`,
|
package/package.json
CHANGED
package/src/agent-session.ts
CHANGED
|
@@ -9,15 +9,17 @@
|
|
|
9
9
|
// Adapter lives HERE, not on the controller: switching adapter = a new AgentSession (the
|
|
10
10
|
// agent dies on switch). Mode-swap (degrade/upgrade) stays within one AgentSession.
|
|
11
11
|
|
|
12
|
-
import { AgentController, type AgentMode } from "./controller.ts";
|
|
12
|
+
import { AgentController, type AgentControllerConfig, type AgentMode } from "./controller.ts";
|
|
13
13
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
14
|
+
import { join } from "node:path";
|
|
14
15
|
import type { Adapter } from "./adapters.ts";
|
|
15
16
|
import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
|
|
16
17
|
import type { Capabilities } from "./capabilities.ts";
|
|
17
18
|
import type { ConfigOptions } from "./config-options.ts";
|
|
18
19
|
import type { ConnectResult } from "./client.ts";
|
|
19
|
-
import type
|
|
20
|
+
import { noopLogger, type Logger } from "./logger.ts";
|
|
20
21
|
import type { SessionManager, MergedSession } from "./session-manager.ts";
|
|
22
|
+
import { appendTranscriptLine, type TranscriptLine } from "./transcript.ts";
|
|
21
23
|
import type {
|
|
22
24
|
AgentCommand,
|
|
23
25
|
Attachment,
|
|
@@ -26,6 +28,14 @@ import type {
|
|
|
26
28
|
SessionListEntry,
|
|
27
29
|
} from "./types.ts";
|
|
28
30
|
|
|
31
|
+
interface QueueItem {
|
|
32
|
+
text: string;
|
|
33
|
+
handlers?: PromptHandlers;
|
|
34
|
+
attachments?: Attachment[];
|
|
35
|
+
resolve: (r: PromptResult) => void;
|
|
36
|
+
reject: (e: unknown) => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
29
39
|
export interface AgentSessionConfig {
|
|
30
40
|
/** The resolved adapter this conversation talks to. */
|
|
31
41
|
adapter: Adapter;
|
|
@@ -40,9 +50,21 @@ export interface AgentSessionConfig {
|
|
|
40
50
|
mcpServers?: schema.McpServer[];
|
|
41
51
|
defaultPermission?: "approve" | "cancel";
|
|
42
52
|
clientInfo?: { name: string; title?: string; version?: string };
|
|
53
|
+
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
54
|
+
clientCapabilities?: AgentControllerConfig["clientCapabilities"];
|
|
43
55
|
logger?: Logger;
|
|
44
56
|
/** Optional catalog. When present, the session records itself here. */
|
|
45
57
|
sessions?: SessionManager;
|
|
58
|
+
/** Absolute path to an append-only transcript file. Omitted means no transcript. */
|
|
59
|
+
transcriptPath?: string;
|
|
60
|
+
/** Directory for a library-named transcript file: `<agentSessionId>.jsonl`. */
|
|
61
|
+
transcriptDir?: string;
|
|
62
|
+
/**
|
|
63
|
+
* Also record activity (thinking, tool calls and their output, plans) as `t:"activity"`
|
|
64
|
+
* lines. Off by default — it makes transcripts much larger, and `readTranscript()`
|
|
65
|
+
* ignores them either way; read them with `readTranscriptLines()`.
|
|
66
|
+
*/
|
|
67
|
+
transcriptActivity?: boolean;
|
|
46
68
|
/** Our stable AgentSession id. Minted if omitted; pass a record's agentSessionId to resume. */
|
|
47
69
|
agentSessionId?: string;
|
|
48
70
|
/** ACP/harness session to load on start (resume an existing provider conversation). */
|
|
@@ -57,15 +79,31 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
57
79
|
|
|
58
80
|
private readonly controller: AgentController;
|
|
59
81
|
private readonly sessions?: SessionManager;
|
|
82
|
+
private readonly transcriptPath?: string;
|
|
83
|
+
private readonly transcriptActivity: boolean;
|
|
84
|
+
private readonly log: Logger;
|
|
85
|
+
private transcriptWrite: Promise<void> = Promise.resolve();
|
|
86
|
+
private queue: QueueItem[] = [];
|
|
87
|
+
private pumping = false;
|
|
60
88
|
private _internalSessionId: string | null;
|
|
61
89
|
private _mode: AgentMode;
|
|
62
90
|
private _cwd?: string;
|
|
63
91
|
private _title?: string;
|
|
64
92
|
|
|
65
93
|
private constructor(config: AgentSessionConfig) {
|
|
94
|
+
if (config.transcriptPath && config.transcriptDir) {
|
|
95
|
+
throw new Error("AgentSessionConfig cannot specify both transcriptPath and transcriptDir");
|
|
96
|
+
}
|
|
66
97
|
this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
|
|
67
98
|
this.adapterId = config.adapterId;
|
|
68
99
|
this.sessions = config.sessions;
|
|
100
|
+
this.transcriptPath =
|
|
101
|
+
config.transcriptPath ??
|
|
102
|
+
(config.transcriptDir
|
|
103
|
+
? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
|
|
104
|
+
: undefined);
|
|
105
|
+
this.transcriptActivity = config.transcriptActivity === true;
|
|
106
|
+
this.log = config.logger ?? noopLogger;
|
|
69
107
|
this._mode = config.mode ?? "normal";
|
|
70
108
|
this._cwd = config.cwd;
|
|
71
109
|
this._title = config.title;
|
|
@@ -81,6 +119,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
81
119
|
mcpServers: config.mcpServers,
|
|
82
120
|
defaultPermission: config.defaultPermission,
|
|
83
121
|
clientInfo: config.clientInfo,
|
|
122
|
+
clientCapabilities: config.clientCapabilities,
|
|
84
123
|
logger: config.logger,
|
|
85
124
|
});
|
|
86
125
|
}
|
|
@@ -100,6 +139,14 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
100
139
|
const result = await this.controller.start();
|
|
101
140
|
this._internalSessionId = result.sessionId || this._internalSessionId;
|
|
102
141
|
await this.persist();
|
|
142
|
+
await this.appendTranscript({
|
|
143
|
+
v: 1,
|
|
144
|
+
t: "meta",
|
|
145
|
+
event: "open",
|
|
146
|
+
ts: Date.now(),
|
|
147
|
+
internalSessionId: this._internalSessionId,
|
|
148
|
+
adapter: this.adapterId,
|
|
149
|
+
});
|
|
103
150
|
}
|
|
104
151
|
|
|
105
152
|
// --- identity ----------------------------------------------------------------
|
|
@@ -126,17 +173,96 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
126
173
|
handlers?: PromptHandlers,
|
|
127
174
|
attachments?: Attachment[],
|
|
128
175
|
): Promise<PromptResult> {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
this.
|
|
176
|
+
return new Promise<PromptResult>((resolve, reject) => {
|
|
177
|
+
this.queue.push({ text, handlers, attachments, resolve, reject });
|
|
178
|
+
void this.pump();
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private async pump(): Promise<void> {
|
|
183
|
+
if (this.pumping) return;
|
|
184
|
+
this.pumping = true;
|
|
185
|
+
try {
|
|
186
|
+
while (this.queue.length > 0) {
|
|
187
|
+
const item = this.queue.shift()!;
|
|
188
|
+
try {
|
|
189
|
+
item.resolve(await this.runPrompt(item));
|
|
190
|
+
} catch (err) {
|
|
191
|
+
item.reject(err);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
} finally {
|
|
195
|
+
this.pumping = false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private async runPrompt(item: QueueItem): Promise<PromptResult> {
|
|
200
|
+
await this.appendTranscript({
|
|
201
|
+
v: 1,
|
|
202
|
+
t: "msg",
|
|
203
|
+
role: "user",
|
|
204
|
+
text: item.text,
|
|
205
|
+
ts: Date.now(),
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const chunks: string[] = [];
|
|
209
|
+
const wrappedHandlers: PromptHandlers = {
|
|
210
|
+
...item.handlers,
|
|
211
|
+
onChunk: (chunk) => {
|
|
212
|
+
chunks.push(chunk);
|
|
213
|
+
item.handlers?.onChunk?.(chunk);
|
|
214
|
+
},
|
|
215
|
+
onActivity: (event) => {
|
|
216
|
+
if (this.transcriptActivity) {
|
|
217
|
+
// Fire and forget: activity is observational, and appendTranscript already
|
|
218
|
+
// serializes writes — blocking the agent's update stream on disk would stall
|
|
219
|
+
// streaming for the caller.
|
|
220
|
+
void this.appendTranscript({ v: 1, t: "activity", ts: Date.now(), ...event });
|
|
221
|
+
}
|
|
222
|
+
item.handlers?.onActivity?.(event);
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
try {
|
|
227
|
+
const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
|
|
228
|
+
if (!this._title && item.text.trim()) {
|
|
229
|
+
this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
|
|
230
|
+
}
|
|
231
|
+
// A session may have been created lazily on first prompt (degraded has none).
|
|
232
|
+
this._internalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
|
|
233
|
+
await this.persist();
|
|
234
|
+
await this.appendTranscript({
|
|
235
|
+
v: 1,
|
|
236
|
+
t: "msg",
|
|
237
|
+
role: "assistant",
|
|
238
|
+
text: res.text,
|
|
239
|
+
ts: Date.now(),
|
|
240
|
+
usage: res.usage,
|
|
241
|
+
stopReason: res.stopReason,
|
|
242
|
+
status: res.status,
|
|
243
|
+
});
|
|
244
|
+
return res;
|
|
245
|
+
} catch (err) {
|
|
246
|
+
await this.appendTranscript({
|
|
247
|
+
v: 1,
|
|
248
|
+
t: "msg",
|
|
249
|
+
role: "assistant",
|
|
250
|
+
text: chunks.join(""),
|
|
251
|
+
ts: Date.now(),
|
|
252
|
+
stopReason: "error",
|
|
253
|
+
status: "error",
|
|
254
|
+
});
|
|
255
|
+
throw err;
|
|
132
256
|
}
|
|
133
|
-
// A session may have been created lazily on first prompt (degraded has none).
|
|
134
|
-
this._internalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
|
|
135
|
-
await this.persist();
|
|
136
|
-
return res;
|
|
137
257
|
}
|
|
138
258
|
|
|
139
259
|
interrupt(options?: InterruptOptions): void {
|
|
260
|
+
if (options?.clearQueue) {
|
|
261
|
+
const dropped = this.queue.splice(0);
|
|
262
|
+
for (const item of dropped) {
|
|
263
|
+
item.resolve({ text: "", stopReason: "cancelled", status: "cancelled", usage: null });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
140
266
|
this.controller.interrupt(options);
|
|
141
267
|
}
|
|
142
268
|
|
|
@@ -213,4 +339,21 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
213
339
|
title: this._title,
|
|
214
340
|
});
|
|
215
341
|
}
|
|
342
|
+
|
|
343
|
+
private async appendTranscript(line: TranscriptLine): Promise<void> {
|
|
344
|
+
if (!this.transcriptPath) return;
|
|
345
|
+
this.transcriptWrite = this.transcriptWrite
|
|
346
|
+
.catch(() => {})
|
|
347
|
+
.then(async () => {
|
|
348
|
+
try {
|
|
349
|
+
await appendTranscriptLine(this.transcriptPath!, line);
|
|
350
|
+
} catch (err) {
|
|
351
|
+
this.log.warn("transcript_write_failed", {
|
|
352
|
+
path: this.transcriptPath,
|
|
353
|
+
error: String(err),
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
await this.transcriptWrite;
|
|
358
|
+
}
|
|
216
359
|
}
|
package/src/capabilities.ts
CHANGED
|
@@ -56,14 +56,41 @@ export interface AgentCapabilities {
|
|
|
56
56
|
};
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* What the caller lets us do on the agent's behalf. Advertising a capability is a
|
|
61
|
+
* PROMISE to implement it — an agent that believes we have terminals will route every
|
|
62
|
+
* shell command through `terminal/create` and render nothing if we can't answer. So
|
|
63
|
+
* these flags gate the handlers and the advertisement together.
|
|
64
|
+
*/
|
|
65
|
+
export interface ClientCapabilityConfig {
|
|
66
|
+
fs?: { readTextFile?: boolean; writeTextFile?: boolean };
|
|
67
|
+
terminal?: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The client capabilities we advertise by default — everything we implement. */
|
|
60
71
|
export const CLIENT_CAPABILITIES: ClientCapabilities = {
|
|
61
72
|
fs: { readTextFile: true, writeTextFile: true },
|
|
62
73
|
terminal: true,
|
|
63
74
|
};
|
|
64
75
|
|
|
76
|
+
/** Resolve caller overrides against the defaults. Omitted = default (enabled). */
|
|
77
|
+
export function buildClientCapabilities(
|
|
78
|
+
config?: ClientCapabilityConfig,
|
|
79
|
+
): ClientCapabilities {
|
|
80
|
+
return {
|
|
81
|
+
fs: {
|
|
82
|
+
readTextFile: config?.fs?.readTextFile ?? CLIENT_CAPABILITIES.fs.readTextFile,
|
|
83
|
+
writeTextFile: config?.fs?.writeTextFile ?? CLIENT_CAPABILITIES.fs.writeTextFile,
|
|
84
|
+
},
|
|
85
|
+
terminal: config?.terminal ?? CLIENT_CAPABILITIES.terminal,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
65
89
|
/** Parse a raw InitializeResponse into our nested Capabilities model. */
|
|
66
|
-
export function parseCapabilities(
|
|
90
|
+
export function parseCapabilities(
|
|
91
|
+
init: schema.InitializeResponse,
|
|
92
|
+
client: ClientCapabilities = CLIENT_CAPABILITIES,
|
|
93
|
+
): Capabilities {
|
|
67
94
|
const a = (init.agentCapabilities ?? {}) as Record<string, any>;
|
|
68
95
|
const prompt = a.promptCapabilities ?? {};
|
|
69
96
|
const mcp = a.mcpCapabilities ?? {};
|
|
@@ -73,7 +100,7 @@ export function parseCapabilities(init: schema.InitializeResponse): Capabilities
|
|
|
73
100
|
return {
|
|
74
101
|
protocolVersion: init.protocolVersion,
|
|
75
102
|
agentInfo,
|
|
76
|
-
client
|
|
103
|
+
client,
|
|
77
104
|
agent: {
|
|
78
105
|
loadSession: a.loadSession === true,
|
|
79
106
|
promptCapabilities: {
|
package/src/client.ts
CHANGED
|
@@ -12,15 +12,20 @@ import { buildSpawnCommand } from "./adapters.ts";
|
|
|
12
12
|
import { AcpTransport } from "./transport/acp-transport.ts";
|
|
13
13
|
import {
|
|
14
14
|
parseCapabilities,
|
|
15
|
-
|
|
15
|
+
buildClientCapabilities,
|
|
16
16
|
type Capabilities,
|
|
17
|
+
type ClientCapabilities,
|
|
18
|
+
type ClientCapabilityConfig,
|
|
17
19
|
} from "./capabilities.ts";
|
|
18
20
|
import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
|
|
19
|
-
import { extractChunkText, toActivityEvent } from "./updates.ts";
|
|
21
|
+
import { extractChunkText, toActivityEvent, toAgentCommands } from "./updates.ts";
|
|
22
|
+
import { TerminalRegistry } from "./terminals.ts";
|
|
23
|
+
import { readTextFile, writeTextFile } from "./fs-access.ts";
|
|
20
24
|
import { NotConnectedError } from "./errors.ts";
|
|
21
25
|
import { noopLogger, type Logger } from "./logger.ts";
|
|
22
26
|
import type { AgentClient, InterruptOptions } from "./agent-client.ts";
|
|
23
27
|
import type {
|
|
28
|
+
ActivityEvent,
|
|
24
29
|
PromptResult,
|
|
25
30
|
PromptHandlers,
|
|
26
31
|
PermissionRequest,
|
|
@@ -28,6 +33,7 @@ import type {
|
|
|
28
33
|
Attachment,
|
|
29
34
|
SessionListPage,
|
|
30
35
|
AgentCommand,
|
|
36
|
+
ToolContent,
|
|
31
37
|
} from "./types.ts";
|
|
32
38
|
|
|
33
39
|
export interface AcpClientConfig {
|
|
@@ -45,6 +51,12 @@ export interface AcpClientConfig {
|
|
|
45
51
|
defaultPermission?: "approve" | "cancel";
|
|
46
52
|
/** Identification sent in initialize. */
|
|
47
53
|
clientInfo?: { name: string; title?: string; version?: string };
|
|
54
|
+
/**
|
|
55
|
+
* What we let the agent do through us: filesystem reads/writes and terminals. All
|
|
56
|
+
* enabled by default. Disabling one stops us advertising it, so the agent falls back
|
|
57
|
+
* to its own implementation instead of calling a method we won't answer.
|
|
58
|
+
*/
|
|
59
|
+
clientCapabilities?: ClientCapabilityConfig;
|
|
48
60
|
/** Diagnostics sink. Omit for a silent library. */
|
|
49
61
|
logger?: Logger;
|
|
50
62
|
}
|
|
@@ -114,10 +126,15 @@ export class AcpClient implements AgentClient {
|
|
|
114
126
|
// caller can show it — auth output almost always arrives on stderr, not the protocol.
|
|
115
127
|
private authStderrSink: ((line: string) => void) | null = null;
|
|
116
128
|
|
|
129
|
+
// Terminals the AGENT is driving through us. Null when the capability is disabled.
|
|
130
|
+
private terminals: TerminalRegistry | null = null;
|
|
131
|
+
|
|
117
132
|
private readonly log: Logger;
|
|
133
|
+
private readonly clientCapabilities: ClientCapabilities;
|
|
118
134
|
|
|
119
135
|
constructor(private config: AcpClientConfig) {
|
|
120
136
|
this.log = config.logger ?? noopLogger;
|
|
137
|
+
this.clientCapabilities = buildClientCapabilities(config.clientCapabilities);
|
|
121
138
|
}
|
|
122
139
|
|
|
123
140
|
// --- introspection (populated by connect) -------------------------------------
|
|
@@ -164,6 +181,15 @@ export class AcpClient implements AgentClient {
|
|
|
164
181
|
|
|
165
182
|
this.log.info("connect", { command, dockerExec: isDockerExec });
|
|
166
183
|
|
|
184
|
+
const caps = this.clientCapabilities;
|
|
185
|
+
this.terminals = caps.terminal
|
|
186
|
+
? new TerminalRegistry({
|
|
187
|
+
cwd: this.config.cwd,
|
|
188
|
+
env: this.config.env,
|
|
189
|
+
logger: this.config.logger,
|
|
190
|
+
})
|
|
191
|
+
: null;
|
|
192
|
+
|
|
167
193
|
const transport = new AcpTransport({
|
|
168
194
|
command,
|
|
169
195
|
// docker exec resolves paths inside the container's namespace — don't pass a host cwd.
|
|
@@ -171,6 +197,16 @@ export class AcpClient implements AgentClient {
|
|
|
171
197
|
env: this.config.env,
|
|
172
198
|
onUpdate: (n) => this.handleUpdate(n),
|
|
173
199
|
onPermissionRequest: (p) => this.handlePermission(p),
|
|
200
|
+
onReadTextFile: caps.fs.readTextFile
|
|
201
|
+
? async (p) => ({ content: await readTextFile(p) })
|
|
202
|
+
: undefined,
|
|
203
|
+
onWriteTextFile: caps.fs.writeTextFile
|
|
204
|
+
? async (p) => {
|
|
205
|
+
await writeTextFile(p);
|
|
206
|
+
return {};
|
|
207
|
+
}
|
|
208
|
+
: undefined,
|
|
209
|
+
terminals: this.terminals ? this.terminalHandlers(this.terminals) : undefined,
|
|
174
210
|
onStderr: (line) => {
|
|
175
211
|
this.log.debug("agent_stderr", { line });
|
|
176
212
|
this.authStderrSink?.(line);
|
|
@@ -187,7 +223,7 @@ export class AcpClient implements AgentClient {
|
|
|
187
223
|
const init = await transport.raceExit(
|
|
188
224
|
transport.initialize({
|
|
189
225
|
protocolVersion: PROTOCOL_VERSION,
|
|
190
|
-
clientCapabilities:
|
|
226
|
+
clientCapabilities: caps as unknown as schema.ClientCapabilities,
|
|
191
227
|
clientInfo: this.config.clientInfo ?? {
|
|
192
228
|
name: "acp-lib",
|
|
193
229
|
title: "ACP Lib",
|
|
@@ -195,7 +231,7 @@ export class AcpClient implements AgentClient {
|
|
|
195
231
|
},
|
|
196
232
|
} as schema.InitializeRequest),
|
|
197
233
|
);
|
|
198
|
-
this._capabilities = parseCapabilities(init);
|
|
234
|
+
this._capabilities = parseCapabilities(init, caps);
|
|
199
235
|
this.log.info("initialized", {
|
|
200
236
|
agent: this._capabilities.agentInfo?.name,
|
|
201
237
|
protocolVersion: this._capabilities.protocolVersion,
|
|
@@ -422,10 +458,29 @@ export class AcpClient implements AgentClient {
|
|
|
422
458
|
const t = this.transport;
|
|
423
459
|
this.transport = null;
|
|
424
460
|
this._sessionId = null;
|
|
461
|
+
this.terminals?.releaseAll();
|
|
462
|
+
this.terminals = null;
|
|
425
463
|
if (t) await t.stop();
|
|
426
464
|
this.log.info("stopped", {});
|
|
427
465
|
}
|
|
428
466
|
|
|
467
|
+
/** Adapt the registry to the transport's async handler shape. */
|
|
468
|
+
private terminalHandlers(registry: TerminalRegistry) {
|
|
469
|
+
return {
|
|
470
|
+
create: async (p: schema.CreateTerminalRequest) => ({
|
|
471
|
+
terminalId: registry.create(p as Parameters<TerminalRegistry["create"]>[0]),
|
|
472
|
+
}),
|
|
473
|
+
output: async (p: schema.TerminalOutputRequest) => {
|
|
474
|
+
const { output, truncated, exitStatus } = registry.output(p.terminalId);
|
|
475
|
+
return { output, truncated, exitStatus };
|
|
476
|
+
},
|
|
477
|
+
waitForExit: async (p: schema.WaitForTerminalExitRequest) =>
|
|
478
|
+
registry.waitForExit(p.terminalId),
|
|
479
|
+
kill: async (p: schema.KillTerminalRequest) => registry.kill(p.terminalId),
|
|
480
|
+
release: async (p: schema.ReleaseTerminalRequest) => registry.release(p.terminalId),
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
|
|
429
484
|
// --- prompting ----------------------------------------------------------------
|
|
430
485
|
|
|
431
486
|
prompt(
|
|
@@ -544,9 +599,7 @@ export class AcpClient implements AgentClient {
|
|
|
544
599
|
this._configOptions = parseConfigOptions((update as Record<string, any>).configOptions);
|
|
545
600
|
}
|
|
546
601
|
if (kind === "available_commands_update") {
|
|
547
|
-
this._agentCommands = ((update as Record<string, any>).availableCommands
|
|
548
|
-
(c: Record<string, any>) => ({ name: c.name, description: c.description ?? "" }),
|
|
549
|
-
);
|
|
602
|
+
this._agentCommands = toAgentCommands((update as Record<string, any>).availableCommands);
|
|
550
603
|
}
|
|
551
604
|
|
|
552
605
|
if (!this.active) {
|
|
@@ -557,13 +610,37 @@ export class AcpClient implements AgentClient {
|
|
|
557
610
|
}
|
|
558
611
|
if (notification.sessionId && notification.sessionId !== this._sessionId) return;
|
|
559
612
|
|
|
613
|
+
this.active.handlers?.onUpdate?.(notification);
|
|
614
|
+
|
|
560
615
|
const text = extractChunkText(update);
|
|
561
616
|
if (text) {
|
|
562
617
|
this.active.chunks.push(text);
|
|
563
618
|
this.active.handlers?.onChunk?.(text);
|
|
564
619
|
}
|
|
565
620
|
const activity = toActivityEvent(update);
|
|
566
|
-
if (activity) this.active.handlers?.onActivity?.(activity);
|
|
621
|
+
if (activity) this.active.handlers?.onActivity?.(this.enrich(activity));
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Fill in terminal output on tool-call content. The agent only sends a `terminalId`
|
|
626
|
+
* (it's polling us for the bytes), so without this the caller sees a tool call it
|
|
627
|
+
* cannot render — the terminal is OURS, and only we can read it.
|
|
628
|
+
*/
|
|
629
|
+
private enrich(event: ActivityEvent): ActivityEvent {
|
|
630
|
+
if (event.kind !== "tool" && event.kind !== "tool_update") return event;
|
|
631
|
+
const registry = this.terminals;
|
|
632
|
+
if (!registry || !event.content?.some((c) => c.type === "terminal")) return event;
|
|
633
|
+
|
|
634
|
+
const content = event.content.map((c): ToolContent => {
|
|
635
|
+
if (c.type !== "terminal" || !registry.has(c.terminalId)) return c;
|
|
636
|
+
try {
|
|
637
|
+
const snapshot = registry.output(c.terminalId);
|
|
638
|
+
return { ...c, ...snapshot };
|
|
639
|
+
} catch {
|
|
640
|
+
return c; // released between the check and the read
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
return { ...event, content };
|
|
567
644
|
}
|
|
568
645
|
|
|
569
646
|
private async handlePermission(
|
package/src/controller.ts
CHANGED
|
@@ -38,6 +38,8 @@ export interface AgentControllerConfig {
|
|
|
38
38
|
mcpServers?: schema.McpServer[];
|
|
39
39
|
defaultPermission?: "approve" | "cancel";
|
|
40
40
|
clientInfo?: AcpClientConfig["clientInfo"];
|
|
41
|
+
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
42
|
+
clientCapabilities?: AcpClientConfig["clientCapabilities"];
|
|
41
43
|
logger?: Logger;
|
|
42
44
|
}
|
|
43
45
|
|
|
@@ -369,6 +371,7 @@ export class AgentController implements AgentClient {
|
|
|
369
371
|
sessionId,
|
|
370
372
|
defaultPermission: this.config.defaultPermission,
|
|
371
373
|
clientInfo: this.config.clientInfo,
|
|
374
|
+
clientCapabilities: this.config.clientCapabilities,
|
|
372
375
|
logger: this.config.logger,
|
|
373
376
|
});
|
|
374
377
|
// connect() is fatal (no connection = nothing to do). startSession() is NOT: an
|
package/src/fs-access.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Client-side filesystem access (ACP `fs/read_text_file`, `fs/write_text_file`).
|
|
2
|
+
//
|
|
3
|
+
// We advertise the fs capabilities, so these must actually work — previously the
|
|
4
|
+
// transport answered every read with `{content: ""}` and silently discarded writes,
|
|
5
|
+
// which reads to an agent as "the file is empty" / "the write succeeded".
|
|
6
|
+
|
|
7
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
|
|
10
|
+
export interface ReadTextFileParams {
|
|
11
|
+
path: string;
|
|
12
|
+
/** 1-based line to start from. */
|
|
13
|
+
line?: number | null;
|
|
14
|
+
/** Maximum number of lines to return. */
|
|
15
|
+
limit?: number | null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface WriteTextFileParams {
|
|
19
|
+
path: string;
|
|
20
|
+
content: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Read a file, honouring the protocol's optional line window. */
|
|
24
|
+
export async function readTextFile(params: ReadTextFileParams): Promise<string> {
|
|
25
|
+
const content = await readFile(params.path, "utf8");
|
|
26
|
+
if (params.line == null && params.limit == null) return content;
|
|
27
|
+
|
|
28
|
+
const lines = content.split("\n");
|
|
29
|
+
const start = Math.max((params.line ?? 1) - 1, 0);
|
|
30
|
+
const end = params.limit != null ? start + Math.max(params.limit, 0) : lines.length;
|
|
31
|
+
return lines.slice(start, end).join("\n");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Write a file, creating parent directories as needed. */
|
|
35
|
+
export async function writeTextFile(params: WriteTextFileParams): Promise<void> {
|
|
36
|
+
await mkdir(dirname(params.path), { recursive: true });
|
|
37
|
+
await writeFile(params.path, params.content, "utf8");
|
|
38
|
+
}
|