@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/src/index.ts
CHANGED
|
@@ -41,12 +41,23 @@ export type {
|
|
|
41
41
|
export { ADAPTERS, buildSpawnCommand } from "./adapters.ts";
|
|
42
42
|
export type { Adapter, AdapterPreset } from "./adapters.ts";
|
|
43
43
|
|
|
44
|
+
export { buildClientCapabilities, CLIENT_CAPABILITIES } from "./capabilities.ts";
|
|
44
45
|
export type {
|
|
45
46
|
Capabilities,
|
|
46
47
|
ClientCapabilities,
|
|
48
|
+
ClientCapabilityConfig,
|
|
47
49
|
AgentCapabilities,
|
|
48
50
|
AuthMethod,
|
|
49
51
|
} from "./capabilities.ts";
|
|
52
|
+
|
|
53
|
+
export { TerminalRegistry, UnknownTerminalError } from "./terminals.ts";
|
|
54
|
+
export type {
|
|
55
|
+
CreateTerminalParams,
|
|
56
|
+
TerminalOutput,
|
|
57
|
+
TerminalRegistryOptions,
|
|
58
|
+
} from "./terminals.ts";
|
|
59
|
+
|
|
60
|
+
export { extractChunkText, toActivityEvent } from "./updates.ts";
|
|
50
61
|
export type {
|
|
51
62
|
ConfigOption,
|
|
52
63
|
ConfigOptions,
|
|
@@ -61,6 +72,23 @@ export type { SessionStore, SessionRecord } from "./session-store.ts";
|
|
|
61
72
|
export { SessionManager, mergeSessions } from "./session-manager.ts";
|
|
62
73
|
export type { MergedSession, SessionInput } from "./session-manager.ts";
|
|
63
74
|
|
|
75
|
+
export {
|
|
76
|
+
appendTranscriptLine,
|
|
77
|
+
readTranscript,
|
|
78
|
+
readTranscriptLines,
|
|
79
|
+
} from "./transcript.ts";
|
|
80
|
+
export type {
|
|
81
|
+
ReadTranscriptOptions,
|
|
82
|
+
TranscriptActivityLine,
|
|
83
|
+
TranscriptEntry,
|
|
84
|
+
TranscriptLine,
|
|
85
|
+
TranscriptMessageLine,
|
|
86
|
+
TranscriptMetaLine,
|
|
87
|
+
TranscriptPermissionLine,
|
|
88
|
+
TranscriptRawLine,
|
|
89
|
+
TranscriptRole,
|
|
90
|
+
} from "./transcript.ts";
|
|
91
|
+
|
|
64
92
|
export { ProcessCrashError, NotConnectedError, TimeoutError } from "./errors.ts";
|
|
65
93
|
|
|
66
94
|
export { noopLogger, createConsoleLogger } from "./logger.ts";
|
|
@@ -70,6 +98,12 @@ export type {
|
|
|
70
98
|
PromptResult,
|
|
71
99
|
PromptHandlers,
|
|
72
100
|
ActivityEvent,
|
|
101
|
+
ToolActivity,
|
|
102
|
+
ToolUpdateActivity,
|
|
103
|
+
ToolContent,
|
|
104
|
+
ToolLocation,
|
|
105
|
+
TerminalExitStatus,
|
|
106
|
+
ContentBlock,
|
|
73
107
|
PlanEntry,
|
|
74
108
|
PermissionRequest,
|
|
75
109
|
PermissionOutcome,
|
package/src/repl/repl.ts
CHANGED
|
@@ -304,9 +304,19 @@ function activityMarker(e: ActivityEvent): string | null {
|
|
|
304
304
|
return "thinking";
|
|
305
305
|
case "tool":
|
|
306
306
|
return `tool:${e.title ?? e.toolKind}`;
|
|
307
|
+
case "tool_update":
|
|
308
|
+
// Only the terminal states are worth a marker; progress ticks are too noisy.
|
|
309
|
+
return e.status === "completed" || e.status === "failed"
|
|
310
|
+
? `tool:${e.title ?? e.toolCallId} ${e.status}`
|
|
311
|
+
: null;
|
|
307
312
|
case "plan":
|
|
313
|
+
case "plan_update":
|
|
308
314
|
return "plan";
|
|
315
|
+
case "mode":
|
|
316
|
+
return `mode:${e.modeId}`;
|
|
317
|
+
case "usage":
|
|
318
|
+
return `context:${e.used}/${e.size}`;
|
|
309
319
|
default:
|
|
310
|
-
return null; //
|
|
320
|
+
return null; // bookkeeping updates — nothing for a one-line marker to say
|
|
311
321
|
}
|
|
312
322
|
}
|
package/src/terminals.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/// <reference types="bun" />
|
|
2
|
+
// Client-side terminals (ACP `terminal/*`). The agent asks US to run a command and then
|
|
3
|
+
// polls for output; the tool call it emits carries only a `terminalId`, so without this
|
|
4
|
+
// the whole execute-tool path produces empty UI.
|
|
5
|
+
//
|
|
6
|
+
// We advertise `terminal` in client capabilities, so per spec we MUST implement all five
|
|
7
|
+
// methods. See https://agentclientprotocol.com/protocol/terminals.
|
|
8
|
+
|
|
9
|
+
import type { Logger } from "./logger.ts";
|
|
10
|
+
import { noopLogger } from "./logger.ts";
|
|
11
|
+
import type { TerminalExitStatus } from "./types.ts";
|
|
12
|
+
|
|
13
|
+
export interface CreateTerminalParams {
|
|
14
|
+
command: string;
|
|
15
|
+
args?: string[];
|
|
16
|
+
cwd?: string | null;
|
|
17
|
+
env?: Array<{ name: string; value: string }>;
|
|
18
|
+
/** Bytes of output to retain; older output is dropped from the FRONT. */
|
|
19
|
+
outputByteLimit?: number | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface TerminalOutput {
|
|
23
|
+
output: string;
|
|
24
|
+
truncated: boolean;
|
|
25
|
+
exitStatus: TerminalExitStatus | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface TerminalRegistryOptions {
|
|
29
|
+
/** Fallback cwd when the agent doesn't specify one. */
|
|
30
|
+
cwd?: string;
|
|
31
|
+
/** Extra env for every terminal, merged over process.env. */
|
|
32
|
+
env?: Record<string, string>;
|
|
33
|
+
logger?: Logger;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Thrown when the agent references a terminal that was released or never existed. */
|
|
37
|
+
export class UnknownTerminalError extends Error {
|
|
38
|
+
constructor(terminalId: string) {
|
|
39
|
+
super(`unknown terminalId: ${terminalId}`);
|
|
40
|
+
this.name = "UnknownTerminalError";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface Chunk {
|
|
45
|
+
text: string;
|
|
46
|
+
bytes: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface Entry {
|
|
50
|
+
id: string;
|
|
51
|
+
proc: ReturnType<typeof Bun.spawn>;
|
|
52
|
+
chunks: Chunk[];
|
|
53
|
+
/** Memoized `chunks.join("")`; nulled on every write. */
|
|
54
|
+
joined: string | null;
|
|
55
|
+
totalBytes: number;
|
|
56
|
+
limit: number | null;
|
|
57
|
+
truncated: boolean;
|
|
58
|
+
exitStatus: TerminalExitStatus | null;
|
|
59
|
+
exited: Promise<TerminalExitStatus>;
|
|
60
|
+
// Structural: Bun's and node:stream/web's reader types differ, and we only cancel.
|
|
61
|
+
readers: Array<{ cancel(): Promise<unknown> }>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* How long to keep draining output after the process exits. A killed shell can leave a
|
|
66
|
+
* grandchild holding the pipe, so EOF may never come — waiting on it unboundedly would
|
|
67
|
+
* hang `terminal/wait_for_exit` and with it the agent's whole turn.
|
|
68
|
+
*/
|
|
69
|
+
const DRAIN_GRACE_MS = 250;
|
|
70
|
+
|
|
71
|
+
export class TerminalRegistry {
|
|
72
|
+
private readonly terminals = new Map<string, Entry>();
|
|
73
|
+
private seq = 0;
|
|
74
|
+
private readonly log: Logger;
|
|
75
|
+
|
|
76
|
+
constructor(private readonly options: TerminalRegistryOptions = {}) {
|
|
77
|
+
this.log = options.logger ?? noopLogger;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Spawn a command and return its terminal id. Output accumulates until released. */
|
|
81
|
+
create(params: CreateTerminalParams): string {
|
|
82
|
+
const id = `term-${++this.seq}`;
|
|
83
|
+
const env: Record<string, string> = {
|
|
84
|
+
...(process.env as Record<string, string>),
|
|
85
|
+
...(this.options.env ?? {}),
|
|
86
|
+
};
|
|
87
|
+
for (const v of params.env ?? []) env[v.name] = v.value;
|
|
88
|
+
|
|
89
|
+
const proc = Bun.spawn([params.command, ...(params.args ?? [])], {
|
|
90
|
+
cwd: params.cwd ?? this.options.cwd,
|
|
91
|
+
env,
|
|
92
|
+
stdin: "ignore",
|
|
93
|
+
stdout: "pipe",
|
|
94
|
+
stderr: "pipe",
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const entry: Entry = {
|
|
98
|
+
id,
|
|
99
|
+
proc,
|
|
100
|
+
chunks: [],
|
|
101
|
+
joined: null,
|
|
102
|
+
totalBytes: 0,
|
|
103
|
+
limit: params.outputByteLimit ?? null,
|
|
104
|
+
truncated: false,
|
|
105
|
+
exitStatus: null,
|
|
106
|
+
exited: Promise.resolve({ exitCode: null, signal: null }),
|
|
107
|
+
readers: [],
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// stdout and stderr are interleaved in arrival order — that's what a terminal is.
|
|
111
|
+
const pumps = [
|
|
112
|
+
this.pump(entry, proc.stdout as ReadableStream<Uint8Array>),
|
|
113
|
+
this.pump(entry, proc.stderr as ReadableStream<Uint8Array>),
|
|
114
|
+
];
|
|
115
|
+
|
|
116
|
+
entry.exited = (async () => {
|
|
117
|
+
const code = await proc.exited;
|
|
118
|
+
// Drain whatever was still buffered before reporting the exit status, so a caller
|
|
119
|
+
// that waits for exit and then reads output never races the last few bytes.
|
|
120
|
+
await Promise.race([Promise.allSettled(pumps), Bun.sleep(DRAIN_GRACE_MS)]);
|
|
121
|
+
const status: TerminalExitStatus = {
|
|
122
|
+
exitCode: proc.signalCode ? null : (code ?? null),
|
|
123
|
+
signal: proc.signalCode ?? null,
|
|
124
|
+
};
|
|
125
|
+
entry.exitStatus = status;
|
|
126
|
+
this.log.debug("terminal_exit", { terminalId: id, ...status });
|
|
127
|
+
return status;
|
|
128
|
+
})();
|
|
129
|
+
void entry.exited.catch(() => {});
|
|
130
|
+
|
|
131
|
+
this.terminals.set(id, entry);
|
|
132
|
+
this.log.debug("terminal_create", { terminalId: id, command: params.command, args: params.args });
|
|
133
|
+
return id;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Current output and exit status. Fully synchronous — it reads a buffer the background
|
|
138
|
+
* pumps fill, and never waits on the process. That matters beyond convenience: this is
|
|
139
|
+
* called while dispatching session updates, so an await here would let one wedged
|
|
140
|
+
* command stall every subsequent update on the connection.
|
|
141
|
+
*/
|
|
142
|
+
output(terminalId: string): TerminalOutput {
|
|
143
|
+
const entry = this.require(terminalId);
|
|
144
|
+
// Joining is O(buffered bytes) and a live terminal is read once per update that
|
|
145
|
+
// references it, so hold the result until the next write.
|
|
146
|
+
entry.joined ??= entry.chunks.map((c) => c.text).join("");
|
|
147
|
+
return {
|
|
148
|
+
output: entry.joined,
|
|
149
|
+
truncated: entry.truncated,
|
|
150
|
+
exitStatus: entry.exitStatus,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Resolve once the command exits. */
|
|
155
|
+
waitForExit(terminalId: string): Promise<TerminalExitStatus> {
|
|
156
|
+
return this.require(terminalId).exited;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Kill the command but keep the id valid, so output stays readable. */
|
|
160
|
+
kill(terminalId: string): void {
|
|
161
|
+
const entry = this.require(terminalId);
|
|
162
|
+
try {
|
|
163
|
+
entry.proc.kill("SIGKILL");
|
|
164
|
+
} catch {
|
|
165
|
+
/* already exited */
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Kill and forget. The id becomes invalid for every other method. */
|
|
170
|
+
release(terminalId: string): void {
|
|
171
|
+
const entry = this.terminals.get(terminalId);
|
|
172
|
+
if (!entry) return;
|
|
173
|
+
this.terminals.delete(terminalId);
|
|
174
|
+
try {
|
|
175
|
+
entry.proc.kill("SIGKILL");
|
|
176
|
+
} catch {
|
|
177
|
+
/* already exited */
|
|
178
|
+
}
|
|
179
|
+
// Cancel explicitly: a surviving grandchild can hold the pipes open indefinitely.
|
|
180
|
+
for (const reader of entry.readers) void reader.cancel().catch(() => {});
|
|
181
|
+
entry.readers = [];
|
|
182
|
+
this.log.debug("terminal_release", { terminalId });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Tear everything down (client stop). */
|
|
186
|
+
releaseAll(): void {
|
|
187
|
+
for (const id of [...this.terminals.keys()]) this.release(id);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** True while the id is still ours to read — used to enrich tool-call content. */
|
|
191
|
+
has(terminalId: string): boolean {
|
|
192
|
+
return this.terminals.has(terminalId);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private require(terminalId: string): Entry {
|
|
196
|
+
const entry = this.terminals.get(terminalId);
|
|
197
|
+
if (!entry) throw new UnknownTerminalError(terminalId);
|
|
198
|
+
return entry;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private async pump(entry: Entry, stream: ReadableStream<Uint8Array> | null): Promise<void> {
|
|
202
|
+
if (!stream) return;
|
|
203
|
+
const reader = stream.getReader();
|
|
204
|
+
entry.readers.push(reader);
|
|
205
|
+
const dec = new TextDecoder();
|
|
206
|
+
try {
|
|
207
|
+
for (;;) {
|
|
208
|
+
const { value, done } = await reader.read();
|
|
209
|
+
if (done) break;
|
|
210
|
+
this.append(entry, dec.decode(value, { stream: true }));
|
|
211
|
+
}
|
|
212
|
+
const tail = dec.decode();
|
|
213
|
+
if (tail) this.append(entry, tail);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
this.log.debug("terminal_read_failed", { terminalId: entry.id, error: String(err) });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private append(entry: Entry, text: string): void {
|
|
220
|
+
if (!text) return;
|
|
221
|
+
entry.joined = null;
|
|
222
|
+
entry.chunks.push({ text, bytes: Buffer.byteLength(text, "utf8") });
|
|
223
|
+
entry.totalBytes += Buffer.byteLength(text, "utf8");
|
|
224
|
+
this.trim(entry);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Enforce outputByteLimit by dropping from the FRONT, whole chunks first, then a
|
|
229
|
+
* character-boundary cut inside the oldest surviving chunk (per spec: truncation must
|
|
230
|
+
* not split a character, even if that leaves us slightly under the limit).
|
|
231
|
+
*/
|
|
232
|
+
private trim(entry: Entry): void {
|
|
233
|
+
const limit = entry.limit;
|
|
234
|
+
if (limit == null || limit < 0) return;
|
|
235
|
+
while (entry.totalBytes > limit && entry.chunks.length > 0) {
|
|
236
|
+
const first = entry.chunks[0]!;
|
|
237
|
+
if (entry.totalBytes - first.bytes >= limit) {
|
|
238
|
+
entry.chunks.shift();
|
|
239
|
+
entry.totalBytes -= first.bytes;
|
|
240
|
+
entry.truncated = true;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const drop = entry.totalBytes - limit;
|
|
244
|
+
const cut = charBoundaryCut(first.text, drop);
|
|
245
|
+
const kept = first.text.slice(cut);
|
|
246
|
+
const keptBytes = Buffer.byteLength(kept, "utf8");
|
|
247
|
+
entry.totalBytes -= first.bytes - keptBytes;
|
|
248
|
+
entry.truncated = true;
|
|
249
|
+
if (kept) {
|
|
250
|
+
entry.chunks[0] = { text: kept, bytes: keptBytes };
|
|
251
|
+
} else {
|
|
252
|
+
entry.chunks.shift();
|
|
253
|
+
}
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Smallest index such that dropping `text[0..index)` sheds at least `dropBytes` bytes,
|
|
261
|
+
* landing on a code-point boundary.
|
|
262
|
+
*/
|
|
263
|
+
function charBoundaryCut(text: string, dropBytes: number): number {
|
|
264
|
+
let shed = 0;
|
|
265
|
+
let i = 0;
|
|
266
|
+
while (i < text.length && shed < dropBytes) {
|
|
267
|
+
const code = text.codePointAt(i)!;
|
|
268
|
+
const width = code > 0xffff ? 2 : 1;
|
|
269
|
+
shed += Buffer.byteLength(text.slice(i, i + width), "utf8");
|
|
270
|
+
i += width;
|
|
271
|
+
}
|
|
272
|
+
return i;
|
|
273
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { appendFile, mkdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import type { PromptResult, Usage } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
export type TranscriptRole = "user" | "assistant";
|
|
6
|
+
|
|
7
|
+
export interface TranscriptMetaLine {
|
|
8
|
+
v: 1;
|
|
9
|
+
t: "meta";
|
|
10
|
+
event: "open";
|
|
11
|
+
ts: number;
|
|
12
|
+
internalSessionId?: string | null;
|
|
13
|
+
adapter?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface TranscriptMessageLine {
|
|
17
|
+
v: 1;
|
|
18
|
+
t: "msg";
|
|
19
|
+
role: TranscriptRole;
|
|
20
|
+
text: string;
|
|
21
|
+
ts: number;
|
|
22
|
+
usage?: Usage | null;
|
|
23
|
+
stopReason?: string;
|
|
24
|
+
status?: PromptResult["status"];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface TranscriptActivityLine {
|
|
28
|
+
v: 1;
|
|
29
|
+
t: "activity";
|
|
30
|
+
ts: number;
|
|
31
|
+
kind: string;
|
|
32
|
+
[key: string]: unknown;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface TranscriptPermissionLine {
|
|
36
|
+
v: 1;
|
|
37
|
+
t: "permission";
|
|
38
|
+
ts: number;
|
|
39
|
+
toolCallId?: string;
|
|
40
|
+
title?: string;
|
|
41
|
+
request?: unknown;
|
|
42
|
+
outcome?: unknown;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface TranscriptRawLine {
|
|
46
|
+
v: 1;
|
|
47
|
+
t: "raw";
|
|
48
|
+
ts: number;
|
|
49
|
+
protocol: "acp" | string;
|
|
50
|
+
event: string;
|
|
51
|
+
data: unknown;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export type TranscriptLine =
|
|
55
|
+
| TranscriptMetaLine
|
|
56
|
+
| TranscriptMessageLine
|
|
57
|
+
| TranscriptActivityLine
|
|
58
|
+
| TranscriptPermissionLine
|
|
59
|
+
| TranscriptRawLine;
|
|
60
|
+
|
|
61
|
+
export type TranscriptEntry = TranscriptMessageLine;
|
|
62
|
+
|
|
63
|
+
export interface ReadTranscriptOptions {
|
|
64
|
+
/** Return entries with `ts` lower than this cursor. */
|
|
65
|
+
before?: number;
|
|
66
|
+
/** Return at most this many entries. Keeps the newest matching entries. */
|
|
67
|
+
limit?: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function appendTranscriptLine(
|
|
71
|
+
path: string,
|
|
72
|
+
line: TranscriptLine,
|
|
73
|
+
): Promise<void> {
|
|
74
|
+
await mkdir(dirname(path), { recursive: true });
|
|
75
|
+
await appendFile(path, `${JSON.stringify(line)}\n`, "utf8");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Read the message projection of a transcript. Meta/activity/raw lines are skipped. */
|
|
79
|
+
export async function readTranscript(
|
|
80
|
+
path: string,
|
|
81
|
+
options: ReadTranscriptOptions = {},
|
|
82
|
+
): Promise<TranscriptEntry[]> {
|
|
83
|
+
const lines = await readTranscriptLines(path, options);
|
|
84
|
+
return lines.filter(isTranscriptMessageLine);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Read all recognized transcript lines, preserving oldest-first order. */
|
|
88
|
+
export async function readTranscriptLines(
|
|
89
|
+
path: string,
|
|
90
|
+
options: ReadTranscriptOptions = {},
|
|
91
|
+
): Promise<TranscriptLine[]> {
|
|
92
|
+
let content: string;
|
|
93
|
+
try {
|
|
94
|
+
content = await readFile(path, "utf8");
|
|
95
|
+
} catch {
|
|
96
|
+
return [];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const out: TranscriptLine[] = [];
|
|
100
|
+
for (const raw of content.split(/\r?\n/)) {
|
|
101
|
+
if (!raw.trim()) continue;
|
|
102
|
+
try {
|
|
103
|
+
const line = JSON.parse(raw) as unknown;
|
|
104
|
+
if (!isTranscriptLine(line)) continue;
|
|
105
|
+
if (options.before != null && line.ts >= options.before) continue;
|
|
106
|
+
out.push(line);
|
|
107
|
+
} catch {
|
|
108
|
+
/* skip malformed lines */
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (options.limit != null && options.limit >= 0 && out.length > options.limit) {
|
|
113
|
+
return out.slice(out.length - options.limit);
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function isTranscriptLine(value: unknown): value is TranscriptLine {
|
|
119
|
+
if (!isRecord(value)) return false;
|
|
120
|
+
if (value.v !== 1 || typeof value.t !== "string" || !isFiniteNumber(value.ts)) return false;
|
|
121
|
+
|
|
122
|
+
switch (value.t) {
|
|
123
|
+
case "meta":
|
|
124
|
+
return value.event === "open";
|
|
125
|
+
case "msg":
|
|
126
|
+
return (
|
|
127
|
+
(value.role === "user" || value.role === "assistant") &&
|
|
128
|
+
typeof value.text === "string"
|
|
129
|
+
);
|
|
130
|
+
case "activity":
|
|
131
|
+
return typeof value.kind === "string";
|
|
132
|
+
case "permission":
|
|
133
|
+
return true;
|
|
134
|
+
case "raw":
|
|
135
|
+
return typeof value.protocol === "string" && typeof value.event === "string";
|
|
136
|
+
default:
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function isTranscriptMessageLine(value: TranscriptLine): value is TranscriptMessageLine {
|
|
142
|
+
return value.t === "msg";
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
146
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function isFiniteNumber(value: unknown): value is number {
|
|
150
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
151
|
+
}
|
|
@@ -7,6 +7,17 @@ import * as acp from "@agentclientprotocol/sdk";
|
|
|
7
7
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
8
8
|
import { ProcessCrashError } from "../errors.ts";
|
|
9
9
|
|
|
10
|
+
/** The five `terminal/*` methods a client that advertises `terminal: true` must serve. */
|
|
11
|
+
export interface TerminalHandlers {
|
|
12
|
+
create(params: schema.CreateTerminalRequest): Promise<schema.CreateTerminalResponse>;
|
|
13
|
+
output(params: schema.TerminalOutputRequest): Promise<schema.TerminalOutputResponse>;
|
|
14
|
+
waitForExit(
|
|
15
|
+
params: schema.WaitForTerminalExitRequest,
|
|
16
|
+
): Promise<schema.WaitForTerminalExitResponse>;
|
|
17
|
+
kill(params: schema.KillTerminalRequest): Promise<void>;
|
|
18
|
+
release(params: schema.ReleaseTerminalRequest): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
|
|
10
21
|
export interface AcpTransportOptions {
|
|
11
22
|
/** Full command to spawn: [...execPrefix, ...adapter.command]. */
|
|
12
23
|
command: string[];
|
|
@@ -14,7 +25,11 @@ export interface AcpTransportOptions {
|
|
|
14
25
|
cwd?: string;
|
|
15
26
|
env?: Record<string, string>;
|
|
16
27
|
|
|
17
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* A session/update notification arrived, exactly as the agent sent it — the transport
|
|
30
|
+
* takes these off the wire itself rather than going through the SDK. See
|
|
31
|
+
* `interceptUpdates` for why.
|
|
32
|
+
*/
|
|
18
33
|
onUpdate?: (notification: schema.SessionNotification) => void;
|
|
19
34
|
/** The agent asked for permission (blocking — must resolve to an outcome). */
|
|
20
35
|
onPermissionRequest?: (
|
|
@@ -28,6 +43,12 @@ export interface AcpTransportOptions {
|
|
|
28
43
|
onWriteTextFile?: (
|
|
29
44
|
params: schema.WriteTextFileRequest,
|
|
30
45
|
) => Promise<schema.WriteTextFileResponse>;
|
|
46
|
+
/**
|
|
47
|
+
* `terminal/*`. Supplied together or not at all — the SDK answers an unimplemented
|
|
48
|
+
* terminal method with a null result rather than an error, which reads to the agent
|
|
49
|
+
* as a malformed response, so a partial implementation is worse than none.
|
|
50
|
+
*/
|
|
51
|
+
terminals?: TerminalHandlers;
|
|
31
52
|
/** A line of stderr from the process. */
|
|
32
53
|
onStderr?: (line: string) => void;
|
|
33
54
|
/** The process exited unexpectedly (not via stop()). */
|
|
@@ -59,7 +80,9 @@ export class AcpTransport {
|
|
|
59
80
|
|
|
60
81
|
const stream = acp.ndJsonStream(
|
|
61
82
|
stdinTransform.writable,
|
|
62
|
-
proc.stdout as ReadableStream<Uint8Array>,
|
|
83
|
+
interceptUpdates(proc.stdout as ReadableStream<Uint8Array>, (m) =>
|
|
84
|
+
this.opts.onUpdate?.(m.params as schema.SessionNotification),
|
|
85
|
+
),
|
|
63
86
|
);
|
|
64
87
|
const handler = new ClientHandler(this.opts);
|
|
65
88
|
this.connection = new acp.ClientSideConnection(() => handler, stream);
|
|
@@ -162,10 +185,90 @@ export class AcpTransport {
|
|
|
162
185
|
}
|
|
163
186
|
}
|
|
164
187
|
|
|
165
|
-
/**
|
|
188
|
+
/**
|
|
189
|
+
* Split the agent's ndjson into `session/update` (ours) and everything else (the SDK's).
|
|
190
|
+
*
|
|
191
|
+
* Updates are handed to `onMessage` verbatim and NOT forwarded downstream: the SDK
|
|
192
|
+
* validates them against a zod copy of the update union, so anything newer than the
|
|
193
|
+
* installed SDK is rejected outright with a console.error, and unmodelled fields on
|
|
194
|
+
* known updates are stripped. Notifications carry no response, so intercepting them is
|
|
195
|
+
* invisible to the agent — every request/response line still flows through untouched.
|
|
196
|
+
*/
|
|
197
|
+
function interceptUpdates(
|
|
198
|
+
source: ReadableStream<Uint8Array>,
|
|
199
|
+
onMessage: (message: Record<string, any>) => void,
|
|
200
|
+
): ReadableStream<Uint8Array> {
|
|
201
|
+
const dec = new TextDecoder();
|
|
202
|
+
const enc = new TextEncoder();
|
|
203
|
+
let buf = "";
|
|
204
|
+
|
|
205
|
+
// Re-emits the ORIGINAL line text — reserializing risks mangling numbers we never read.
|
|
206
|
+
const handle = (line: string, controller: TransformStreamDefaultController<Uint8Array>) => {
|
|
207
|
+
if (!line) return;
|
|
208
|
+
let message: Record<string, any> | undefined;
|
|
209
|
+
try {
|
|
210
|
+
message = JSON.parse(line);
|
|
211
|
+
} catch {
|
|
212
|
+
/* not JSON — let the SDK report it */
|
|
213
|
+
}
|
|
214
|
+
if (message?.method === "session/update" && message.id === undefined) {
|
|
215
|
+
onMessage(message);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
controller.enqueue(enc.encode(`${line}\n`));
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
return source.pipeThrough(
|
|
222
|
+
new TransformStream<Uint8Array, Uint8Array>({
|
|
223
|
+
transform(chunk, controller) {
|
|
224
|
+
buf += dec.decode(chunk, { stream: true });
|
|
225
|
+
let i: number;
|
|
226
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
227
|
+
const line = buf.slice(0, i).trim();
|
|
228
|
+
buf = buf.slice(i + 1);
|
|
229
|
+
handle(line, controller);
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
flush(controller) {
|
|
233
|
+
buf += dec.decode();
|
|
234
|
+
handle(buf.trim(), controller);
|
|
235
|
+
buf = "";
|
|
236
|
+
},
|
|
237
|
+
}),
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Routes SDK client-side callbacks to the transport's option handlers.
|
|
243
|
+
*
|
|
244
|
+
* Methods are attached in the CONSTRUCTOR rather than declared, because the SDK probes
|
|
245
|
+
* `client.method?.()` — a declared-but-stubbed method makes us look capable while
|
|
246
|
+
* answering with nonsense. Absent is the honest signal for "not implemented".
|
|
247
|
+
*/
|
|
166
248
|
class ClientHandler implements acp.Client {
|
|
167
|
-
|
|
249
|
+
createTerminal?: acp.Client["createTerminal"];
|
|
250
|
+
terminalOutput?: acp.Client["terminalOutput"];
|
|
251
|
+
waitForTerminalExit?: acp.Client["waitForTerminalExit"];
|
|
252
|
+
killTerminal?: acp.Client["killTerminal"];
|
|
253
|
+
releaseTerminal?: acp.Client["releaseTerminal"];
|
|
254
|
+
readTextFile?: acp.Client["readTextFile"];
|
|
255
|
+
writeTextFile?: acp.Client["writeTextFile"];
|
|
256
|
+
|
|
257
|
+
constructor(private opts: AcpTransportOptions) {
|
|
258
|
+
if (opts.onReadTextFile) this.readTextFile = (p) => opts.onReadTextFile!(p);
|
|
259
|
+
if (opts.onWriteTextFile) this.writeTextFile = (p) => opts.onWriteTextFile!(p);
|
|
260
|
+
|
|
261
|
+
const terminals = opts.terminals;
|
|
262
|
+
if (terminals) {
|
|
263
|
+
this.createTerminal = (p) => terminals.create(p);
|
|
264
|
+
this.terminalOutput = (p) => terminals.output(p);
|
|
265
|
+
this.waitForTerminalExit = (p) => terminals.waitForExit(p);
|
|
266
|
+
this.killTerminal = (p) => terminals.kill(p);
|
|
267
|
+
this.releaseTerminal = (p) => terminals.release(p);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
168
270
|
|
|
271
|
+
/** Safety net: `interceptUpdates` normally takes these before the SDK sees them. */
|
|
169
272
|
async sessionUpdate(params: schema.SessionNotification): Promise<void> {
|
|
170
273
|
this.opts.onUpdate?.(params);
|
|
171
274
|
}
|
|
@@ -176,18 +279,4 @@ class ClientHandler implements acp.Client {
|
|
|
176
279
|
if (this.opts.onPermissionRequest) return this.opts.onPermissionRequest(params);
|
|
177
280
|
return { outcome: { outcome: "cancelled" } };
|
|
178
281
|
}
|
|
179
|
-
|
|
180
|
-
async readTextFile(
|
|
181
|
-
params: schema.ReadTextFileRequest,
|
|
182
|
-
): Promise<schema.ReadTextFileResponse> {
|
|
183
|
-
if (this.opts.onReadTextFile) return this.opts.onReadTextFile(params);
|
|
184
|
-
return { content: "" };
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
async writeTextFile(
|
|
188
|
-
params: schema.WriteTextFileRequest,
|
|
189
|
-
): Promise<schema.WriteTextFileResponse> {
|
|
190
|
-
if (this.opts.onWriteTextFile) return this.opts.onWriteTextFile(params);
|
|
191
|
-
return {};
|
|
192
|
-
}
|
|
193
282
|
}
|