@qlairoslabs/acp-client 0.1.5 → 0.3.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 +209 -4
- package/package.json +2 -1
- package/src/activity.ts +513 -0
- package/src/agent-session.ts +244 -2
- package/src/capabilities.ts +30 -3
- package/src/cli/index.ts +21 -3
- package/src/client.ts +93 -8
- package/src/controller.ts +7 -0
- package/src/fs-access.ts +38 -0
- package/src/index.ts +41 -1
- package/src/repl/repl.ts +11 -1
- package/src/terminals.ts +273 -0
- package/src/transcript.ts +228 -16
- package/src/transport/acp-transport.ts +164 -21
- package/src/types.ts +129 -12
- package/src/updates.ts +137 -14
- package/src/wire-log.ts +85 -0
package/src/transcript.ts
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
|
-
|
|
1
|
+
// The chat transcript: one JSON object per line, append-only, readable without starting
|
|
2
|
+
// the agent. Deliberately lightweight and harness-agnostic — it is not a replacement for
|
|
3
|
+
// whatever full-fidelity record the provider keeps.
|
|
4
|
+
//
|
|
5
|
+
// FILE CONTRACT
|
|
6
|
+
//
|
|
7
|
+
// - `t:"msg"` DELIMITS A TURN. A turn is `msg(user) → activity… → msg(assistant)`; writes
|
|
8
|
+
// serialize in call order, so that nesting always holds. A trailing user message with no
|
|
9
|
+
// assistant message after it means the turn DIED IN FLIGHT (crash, kill, cancel) — the
|
|
10
|
+
// activity lines inside it are the record of what it was doing.
|
|
11
|
+
// - `t:"activity"` lines are SETTLED RECORDS, not raw deltas. FOLD THEM LAST-WINS ON
|
|
12
|
+
// `recordId` — `foldRecords()` from `./activity.ts` is exactly that, and is the only
|
|
13
|
+
// supported way to read them. A tool call normally writes 2–3 lines (announced → input →
|
|
14
|
+
// settled); later lines supersede earlier ones with the same `recordId`. `reason` lets a
|
|
15
|
+
// compact view take only `settled`/`flushed` without folding at all.
|
|
16
|
+
// - `reason:"flushed"` means the turn ended with that record still open, written at its
|
|
17
|
+
// real status. It is NOT `settled`.
|
|
18
|
+
// - Lines with neither `recordId` nor `reason` are raw activity deltas written by 0.2.x, from
|
|
19
|
+
// before this format. Those two fields are the discriminator, which is why `v` is still 1.
|
|
20
|
+
// - Unrecognized `t` values and malformed lines are SKIPPED, never fatal: a partially
|
|
21
|
+
// written final line (torn write) costs that line only.
|
|
22
|
+
// - `ts` is wall-clock milliseconds and is the ordering key ACROSS types, so a reader can
|
|
23
|
+
// interleave `msg` and `activity` on one timeline.
|
|
24
|
+
//
|
|
25
|
+
// Any future change to fold semantics or line meaning bumps `v`.
|
|
26
|
+
|
|
27
|
+
import { appendFile, mkdir, open, readFile, type FileHandle } from "node:fs/promises";
|
|
2
28
|
import { dirname } from "node:path";
|
|
3
|
-
import
|
|
29
|
+
import { foldRecords, type AggregatedRecord, type EmitReason } from "./activity.ts";
|
|
30
|
+
import type { ActivityEvent, PromptResult, Usage } from "./types.ts";
|
|
4
31
|
|
|
5
32
|
export type TranscriptRole = "user" | "assistant";
|
|
6
33
|
|
|
@@ -24,11 +51,22 @@ export interface TranscriptMessageLine {
|
|
|
24
51
|
status?: PromptResult["status"];
|
|
25
52
|
}
|
|
26
53
|
|
|
54
|
+
/**
|
|
55
|
+
* One aggregated activity record, flattened: the `ActivityEvent`'s own fields sit at the
|
|
56
|
+
* top level beside the envelope. Fold last-wins on `recordId` (see the file contract at
|
|
57
|
+
* the top of this module).
|
|
58
|
+
*/
|
|
27
59
|
export interface TranscriptActivityLine {
|
|
28
60
|
v: 1;
|
|
29
61
|
t: "activity";
|
|
30
62
|
ts: number;
|
|
31
63
|
kind: string;
|
|
64
|
+
/** Fold key. Absent on raw activity lines written by 0.2.x. */
|
|
65
|
+
recordId?: string;
|
|
66
|
+
/** Lifecycle position. Absent on raw activity lines written by 0.2.x. */
|
|
67
|
+
reason?: EmitReason;
|
|
68
|
+
/** Set when `maxBytes` clipped a field on this line. */
|
|
69
|
+
truncated?: boolean;
|
|
32
70
|
[key: string]: unknown;
|
|
33
71
|
}
|
|
34
72
|
|
|
@@ -63,10 +101,37 @@ export type TranscriptEntry = TranscriptMessageLine;
|
|
|
63
101
|
export interface ReadTranscriptOptions {
|
|
64
102
|
/** Return entries with `ts` lower than this cursor. */
|
|
65
103
|
before?: number;
|
|
66
|
-
/**
|
|
104
|
+
/**
|
|
105
|
+
* Return at most this many entries, keeping the NEWEST matching ones.
|
|
106
|
+
*
|
|
107
|
+
* `limit` counts entries that SURVIVE `types` — ask for twenty messages and you get
|
|
108
|
+
* twenty messages, however many activity lines sit between them.
|
|
109
|
+
*
|
|
110
|
+
* With a limit the file is read backwards from EOF in chunks, so the cost is
|
|
111
|
+
* proportional to the region that holds `limit` matches rather than to the whole
|
|
112
|
+
* transcript. Narrow `types` on an activity-heavy file widens that region: twenty
|
|
113
|
+
* messages may span thousands of activity lines, and in the worst case the read reaches
|
|
114
|
+
* the start of the file — which is what every read did before the tail read existed.
|
|
115
|
+
*/
|
|
67
116
|
limit?: number;
|
|
117
|
+
/**
|
|
118
|
+
* Keep only these line types. Omit for everything recognized.
|
|
119
|
+
*
|
|
120
|
+
* This is what makes `limit` mean what you asked for. `["msg", "activity"]` is the
|
|
121
|
+
* interleaved chat view; `meta` and `raw` are noise a renderer would discard anyway,
|
|
122
|
+
* and excluding them here stops them consuming the budget.
|
|
123
|
+
*/
|
|
124
|
+
types?: Array<TranscriptLine["t"]>;
|
|
68
125
|
}
|
|
69
126
|
|
|
127
|
+
/** Backwards read granularity. Big enough that a typical page needs one or two reads. */
|
|
128
|
+
const TAIL_CHUNK_BYTES = 64 * 1024;
|
|
129
|
+
|
|
130
|
+
const LF = 0x0a;
|
|
131
|
+
|
|
132
|
+
/** Views from `subarray` keep the source's buffer kind; pin the loose form. */
|
|
133
|
+
type Bytes = Uint8Array<ArrayBufferLike>;
|
|
134
|
+
|
|
70
135
|
export async function appendTranscriptLine(
|
|
71
136
|
path: string,
|
|
72
137
|
line: TranscriptLine,
|
|
@@ -75,20 +140,36 @@ export async function appendTranscriptLine(
|
|
|
75
140
|
await appendFile(path, `${JSON.stringify(line)}\n`, "utf8");
|
|
76
141
|
}
|
|
77
142
|
|
|
78
|
-
/**
|
|
143
|
+
/**
|
|
144
|
+
* Read the message projection of a transcript. Meta/activity/raw lines are skipped, and
|
|
145
|
+
* `limit` counts MESSAGES — the entries this returns — not lines.
|
|
146
|
+
*
|
|
147
|
+
* `types` is forced: this function is the message projection, so honouring a caller's
|
|
148
|
+
* `types` would be incoherent.
|
|
149
|
+
*/
|
|
79
150
|
export async function readTranscript(
|
|
80
151
|
path: string,
|
|
81
152
|
options: ReadTranscriptOptions = {},
|
|
82
153
|
): Promise<TranscriptEntry[]> {
|
|
83
|
-
const lines = await readTranscriptLines(path, options);
|
|
154
|
+
const lines = await readTranscriptLines(path, { ...options, types: ["msg"] });
|
|
84
155
|
return lines.filter(isTranscriptMessageLine);
|
|
85
156
|
}
|
|
86
157
|
|
|
87
|
-
/**
|
|
158
|
+
/**
|
|
159
|
+
* Read all recognized transcript lines, preserving oldest-first order.
|
|
160
|
+
*
|
|
161
|
+
* `before` + `limit` are the pagination contract: page back through a conversation by
|
|
162
|
+
* passing the oldest returned `ts` as the next `before`.
|
|
163
|
+
*/
|
|
88
164
|
export async function readTranscriptLines(
|
|
89
165
|
path: string,
|
|
90
166
|
options: ReadTranscriptOptions = {},
|
|
91
167
|
): Promise<TranscriptLine[]> {
|
|
168
|
+
const types = options.types ? new Set<string>(options.types) : undefined;
|
|
169
|
+
if (options.limit != null && options.limit >= 0) {
|
|
170
|
+
return readTail(path, options.limit, options.before, types);
|
|
171
|
+
}
|
|
172
|
+
|
|
92
173
|
let content: string;
|
|
93
174
|
try {
|
|
94
175
|
content = await readFile(path, "utf8");
|
|
@@ -98,20 +179,151 @@ export async function readTranscriptLines(
|
|
|
98
179
|
|
|
99
180
|
const out: TranscriptLine[] = [];
|
|
100
181
|
for (const raw of content.split(/\r?\n/)) {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
182
|
+
const line = parseTranscriptLine(raw, options.before, types);
|
|
183
|
+
if (line) out.push(line);
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Un-flatten one activity line back into the record it was written from.
|
|
190
|
+
*
|
|
191
|
+
* Null for a line that predates this format (no `recordId`/`reason`) — those are raw
|
|
192
|
+
* deltas and cannot be folded. `seq` is 0: it is a live-stream ordering device for the
|
|
193
|
+
* mid-turn join, never a file field.
|
|
194
|
+
*
|
|
195
|
+
* Exported because a reader that interleaves `msg` and `activity` on one `ts` timeline
|
|
196
|
+
* needs per-line conversion; use `readActivityRecords` if you only want the folded state.
|
|
197
|
+
*/
|
|
198
|
+
export function toActivityRecord(line: TranscriptActivityLine): AggregatedRecord | null {
|
|
199
|
+
if (!line.recordId || !line.reason) return null;
|
|
200
|
+
const { v, t, ts, recordId, reason, ...event } = line;
|
|
201
|
+
return { recordId, reason, seq: 0, event: event as unknown as ActivityEvent };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The folded activity state of a transcript: everything that happened, one entry per
|
|
206
|
+
* `recordId`, last write winning. This is THE read path for activity — the same fold the
|
|
207
|
+
* live stream uses, so a reload shows what was watched.
|
|
208
|
+
*/
|
|
209
|
+
export async function readActivityRecords(
|
|
210
|
+
path: string,
|
|
211
|
+
options: ReadTranscriptOptions = {},
|
|
212
|
+
): Promise<Map<string, AggregatedRecord>> {
|
|
213
|
+
const records: AggregatedRecord[] = [];
|
|
214
|
+
// `types` forced for the same reason as readTranscript: `limit` should count the thing
|
|
215
|
+
// this returns. Note the newest N activity lines always carry the LATEST state of what
|
|
216
|
+
// they cover, since a later line supersedes an earlier one with the same `recordId`.
|
|
217
|
+
for (const line of await readTranscriptLines(path, { ...options, types: ["activity"] })) {
|
|
218
|
+
if (line.t !== "activity") continue;
|
|
219
|
+
const record = toActivityRecord(line);
|
|
220
|
+
if (record) records.push(record);
|
|
221
|
+
}
|
|
222
|
+
return foldRecords(records);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The newest `limit` matching lines, read backwards from EOF.
|
|
227
|
+
*
|
|
228
|
+
* Accumulates RAW BYTES and decodes only the assembled tail, so a multi-byte character
|
|
229
|
+
* split across a chunk boundary is whole again before anyone looks at it. The leading
|
|
230
|
+
* fragment of each block is a line whose beginning we haven't read yet, so it is carried
|
|
231
|
+
* into the next iteration rather than parsed.
|
|
232
|
+
*/
|
|
233
|
+
async function readTail(
|
|
234
|
+
path: string,
|
|
235
|
+
limit: number,
|
|
236
|
+
before?: number,
|
|
237
|
+
types?: Set<string>,
|
|
238
|
+
): Promise<TranscriptLine[]> {
|
|
239
|
+
if (limit === 0) return [];
|
|
240
|
+
|
|
241
|
+
let handle: FileHandle;
|
|
242
|
+
try {
|
|
243
|
+
handle = await open(path, "r");
|
|
244
|
+
} catch {
|
|
245
|
+
return [];
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
try {
|
|
249
|
+
const { size } = await handle.stat();
|
|
250
|
+
const newestFirst: TranscriptLine[] = [];
|
|
251
|
+
const decoder = new TextDecoder();
|
|
252
|
+
let end = size;
|
|
253
|
+
let carry: Bytes = new Uint8Array(0);
|
|
254
|
+
|
|
255
|
+
while (end > 0 && newestFirst.length < limit) {
|
|
256
|
+
const start = Math.max(0, end - TAIL_CHUNK_BYTES);
|
|
257
|
+
const block = concatBytes(await readBytes(handle, start, end - start), carry);
|
|
258
|
+
end = start;
|
|
259
|
+
|
|
260
|
+
let body: Bytes;
|
|
261
|
+
if (start === 0) {
|
|
262
|
+
body = block; // reached the beginning: nothing is partial any more
|
|
263
|
+
carry = new Uint8Array(0);
|
|
264
|
+
} else {
|
|
265
|
+
const firstBreak = block.indexOf(LF);
|
|
266
|
+
if (firstBreak < 0) {
|
|
267
|
+
carry = block; // a single line longer than one chunk
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
carry = block.subarray(0, firstBreak);
|
|
271
|
+
body = block.subarray(firstBreak + 1);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const raws = decoder.decode(body).split(/\r?\n/);
|
|
275
|
+
for (let i = raws.length - 1; i >= 0 && newestFirst.length < limit; i--) {
|
|
276
|
+
const line = parseTranscriptLine(raws[i]!, before, types);
|
|
277
|
+
if (line) newestFirst.push(line);
|
|
278
|
+
}
|
|
109
279
|
}
|
|
280
|
+
|
|
281
|
+
return newestFirst.reverse();
|
|
282
|
+
} finally {
|
|
283
|
+
await handle.close();
|
|
110
284
|
}
|
|
285
|
+
}
|
|
111
286
|
|
|
112
|
-
|
|
113
|
-
|
|
287
|
+
/**
|
|
288
|
+
* One line → a recognized entry, or null (blank, malformed, unknown, or filtered out).
|
|
289
|
+
*
|
|
290
|
+
* Every rejection happens HERE, which is what makes `limit` count survivors: both read
|
|
291
|
+
* paths tally what this returns, so narrowing `types` narrows what the budget is spent on
|
|
292
|
+
* without either loop knowing about it.
|
|
293
|
+
*/
|
|
294
|
+
function parseTranscriptLine(
|
|
295
|
+
raw: string,
|
|
296
|
+
before?: number,
|
|
297
|
+
types?: Set<string>,
|
|
298
|
+
): TranscriptLine | null {
|
|
299
|
+
if (!raw.trim()) return null;
|
|
300
|
+
try {
|
|
301
|
+
const line = JSON.parse(raw) as unknown;
|
|
302
|
+
if (!isTranscriptLine(line)) return null;
|
|
303
|
+
if (types && !types.has(line.t)) return null;
|
|
304
|
+
if (before != null && line.ts >= before) return null;
|
|
305
|
+
return line;
|
|
306
|
+
} catch {
|
|
307
|
+
return null; // skip malformed lines
|
|
114
308
|
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async function readBytes(handle: FileHandle, start: number, length: number): Promise<Uint8Array> {
|
|
312
|
+
const buf = new Uint8Array(length);
|
|
313
|
+
let read = 0;
|
|
314
|
+
while (read < length) {
|
|
315
|
+
const { bytesRead } = await handle.read(buf, read, length - read, start + read);
|
|
316
|
+
if (bytesRead <= 0) break;
|
|
317
|
+
read += bytesRead;
|
|
318
|
+
}
|
|
319
|
+
return read === length ? buf : buf.subarray(0, read);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
|
|
323
|
+
if (b.length === 0) return a;
|
|
324
|
+
const out = new Uint8Array(a.length + b.length);
|
|
325
|
+
out.set(a, 0);
|
|
326
|
+
out.set(b, a.length);
|
|
115
327
|
return out;
|
|
116
328
|
}
|
|
117
329
|
|
|
@@ -6,6 +6,18 @@
|
|
|
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 type { WireEntry } from "../types.ts";
|
|
10
|
+
|
|
11
|
+
/** The five `terminal/*` methods a client that advertises `terminal: true` must serve. */
|
|
12
|
+
export interface TerminalHandlers {
|
|
13
|
+
create(params: schema.CreateTerminalRequest): Promise<schema.CreateTerminalResponse>;
|
|
14
|
+
output(params: schema.TerminalOutputRequest): Promise<schema.TerminalOutputResponse>;
|
|
15
|
+
waitForExit(
|
|
16
|
+
params: schema.WaitForTerminalExitRequest,
|
|
17
|
+
): Promise<schema.WaitForTerminalExitResponse>;
|
|
18
|
+
kill(params: schema.KillTerminalRequest): Promise<void>;
|
|
19
|
+
release(params: schema.ReleaseTerminalRequest): Promise<void>;
|
|
20
|
+
}
|
|
9
21
|
|
|
10
22
|
export interface AcpTransportOptions {
|
|
11
23
|
/** Full command to spawn: [...execPrefix, ...adapter.command]. */
|
|
@@ -14,7 +26,11 @@ export interface AcpTransportOptions {
|
|
|
14
26
|
cwd?: string;
|
|
15
27
|
env?: Record<string, string>;
|
|
16
28
|
|
|
17
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* A session/update notification arrived, exactly as the agent sent it — the transport
|
|
31
|
+
* takes these off the wire itself rather than going through the SDK. See
|
|
32
|
+
* `interceptUpdates` for why.
|
|
33
|
+
*/
|
|
18
34
|
onUpdate?: (notification: schema.SessionNotification) => void;
|
|
19
35
|
/** The agent asked for permission (blocking — must resolve to an outcome). */
|
|
20
36
|
onPermissionRequest?: (
|
|
@@ -28,8 +44,20 @@ export interface AcpTransportOptions {
|
|
|
28
44
|
onWriteTextFile?: (
|
|
29
45
|
params: schema.WriteTextFileRequest,
|
|
30
46
|
) => Promise<schema.WriteTextFileResponse>;
|
|
47
|
+
/**
|
|
48
|
+
* `terminal/*`. Supplied together or not at all — the SDK answers an unimplemented
|
|
49
|
+
* terminal method with a null result rather than an error, which reads to the agent
|
|
50
|
+
* as a malformed response, so a partial implementation is worse than none.
|
|
51
|
+
*/
|
|
52
|
+
terminals?: TerminalHandlers;
|
|
31
53
|
/** A line of stderr from the process. */
|
|
32
54
|
onStderr?: (line: string) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Every raw line in either direction, for debugging. This is the ONLY view of the
|
|
57
|
+
* traffic that is complete: `onUpdate` sees notifications after mapping, the logger sees
|
|
58
|
+
* our interpretation, and the SDK sees neither the lines we intercept nor what it wrote.
|
|
59
|
+
*/
|
|
60
|
+
onWire?: (entry: WireEntry) => void;
|
|
33
61
|
/** The process exited unexpectedly (not via stop()). */
|
|
34
62
|
onCrash?: (code: number | null) => void;
|
|
35
63
|
}
|
|
@@ -38,6 +66,7 @@ export class AcpTransport {
|
|
|
38
66
|
private proc: ReturnType<typeof Bun.spawn> | null = null;
|
|
39
67
|
private connection: acp.ClientSideConnection | null = null;
|
|
40
68
|
private stopping = false;
|
|
69
|
+
private tap?: (dir: WireEntry["dir"], line: string) => void;
|
|
41
70
|
|
|
42
71
|
constructor(private opts: AcpTransportOptions) {}
|
|
43
72
|
|
|
@@ -57,10 +86,19 @@ export class AcpTransport {
|
|
|
57
86
|
});
|
|
58
87
|
this.proc = proc;
|
|
59
88
|
|
|
89
|
+
const wire = this.opts.onWire;
|
|
90
|
+
const tap = wire ? (dir: WireEntry["dir"], line: string) => wire({ dir, ts: Date.now(), line }) : undefined;
|
|
91
|
+
|
|
60
92
|
const stream = acp.ndJsonStream(
|
|
61
|
-
|
|
62
|
-
|
|
93
|
+
// Outgoing bytes are forwarded untouched; the tap only reads them on the way past.
|
|
94
|
+
tap ? tapOutgoing(stdinTransform.writable, (line) => tap("out", line)) : stdinTransform.writable,
|
|
95
|
+
interceptUpdates(
|
|
96
|
+
proc.stdout as ReadableStream<Uint8Array>,
|
|
97
|
+
(m) => this.opts.onUpdate?.(m.params as schema.SessionNotification),
|
|
98
|
+
tap && ((line) => tap("in", line)),
|
|
99
|
+
),
|
|
63
100
|
);
|
|
101
|
+
this.tap = tap;
|
|
64
102
|
const handler = new ClientHandler(this.opts);
|
|
65
103
|
this.connection = new acp.ClientSideConnection(() => handler, stream);
|
|
66
104
|
|
|
@@ -154,18 +192,137 @@ export class AcpTransport {
|
|
|
154
192
|
while ((i = buf.indexOf("\n")) >= 0) {
|
|
155
193
|
const line = buf.slice(0, i).trim();
|
|
156
194
|
buf = buf.slice(i + 1);
|
|
157
|
-
if (line) this.
|
|
195
|
+
if (line) this.emitStderr(line);
|
|
158
196
|
}
|
|
159
197
|
}
|
|
160
198
|
const tail = buf.trim();
|
|
161
|
-
if (tail) this.
|
|
199
|
+
if (tail) this.emitStderr(tail);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
private emitStderr(line: string): void {
|
|
203
|
+
this.tap?.("err", line);
|
|
204
|
+
this.opts.onStderr?.(line);
|
|
162
205
|
}
|
|
163
206
|
}
|
|
164
207
|
|
|
165
|
-
/**
|
|
208
|
+
/**
|
|
209
|
+
* Wrap a writable so every line written through it is reported, then forwarded BYTE FOR
|
|
210
|
+
* BYTE. The SDK owns serialization; this only looks.
|
|
211
|
+
*/
|
|
212
|
+
function tapOutgoing(
|
|
213
|
+
target: WritableStream<Uint8Array>,
|
|
214
|
+
onLine: (line: string) => void,
|
|
215
|
+
): WritableStream<Uint8Array> {
|
|
216
|
+
const writer = target.getWriter();
|
|
217
|
+
const dec = new TextDecoder();
|
|
218
|
+
let buf = "";
|
|
219
|
+
return new WritableStream<Uint8Array>({
|
|
220
|
+
async write(chunk) {
|
|
221
|
+
buf += dec.decode(chunk, { stream: true });
|
|
222
|
+
let i: number;
|
|
223
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
224
|
+
const line = buf.slice(0, i).trim();
|
|
225
|
+
buf = buf.slice(i + 1);
|
|
226
|
+
if (line) onLine(line);
|
|
227
|
+
}
|
|
228
|
+
await writer.write(chunk);
|
|
229
|
+
},
|
|
230
|
+
async close() {
|
|
231
|
+
await writer.close();
|
|
232
|
+
},
|
|
233
|
+
async abort(reason) {
|
|
234
|
+
await writer.abort(reason);
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Split the agent's ndjson into `session/update` (ours) and everything else (the SDK's).
|
|
241
|
+
*
|
|
242
|
+
* Updates are handed to `onMessage` verbatim and NOT forwarded downstream: the SDK
|
|
243
|
+
* validates them against a zod copy of the update union, so anything newer than the
|
|
244
|
+
* installed SDK is rejected outright with a console.error, and unmodelled fields on
|
|
245
|
+
* known updates are stripped. Notifications carry no response, so intercepting them is
|
|
246
|
+
* invisible to the agent — every request/response line still flows through untouched.
|
|
247
|
+
*/
|
|
248
|
+
function interceptUpdates(
|
|
249
|
+
source: ReadableStream<Uint8Array>,
|
|
250
|
+
onMessage: (message: Record<string, any>) => void,
|
|
251
|
+
onLine?: (line: string) => void,
|
|
252
|
+
): ReadableStream<Uint8Array> {
|
|
253
|
+
const dec = new TextDecoder();
|
|
254
|
+
const enc = new TextEncoder();
|
|
255
|
+
let buf = "";
|
|
256
|
+
|
|
257
|
+
// Re-emits the ORIGINAL line text — reserializing risks mangling numbers we never read.
|
|
258
|
+
const handle = (line: string, controller: TransformStreamDefaultController<Uint8Array>) => {
|
|
259
|
+
if (!line) return;
|
|
260
|
+
// Before the split, so the debug view includes what we take off the wire ourselves.
|
|
261
|
+
onLine?.(line);
|
|
262
|
+
let message: Record<string, any> | undefined;
|
|
263
|
+
try {
|
|
264
|
+
message = JSON.parse(line);
|
|
265
|
+
} catch {
|
|
266
|
+
/* not JSON — let the SDK report it */
|
|
267
|
+
}
|
|
268
|
+
if (message?.method === "session/update" && message.id === undefined) {
|
|
269
|
+
onMessage(message);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
controller.enqueue(enc.encode(`${line}\n`));
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
return source.pipeThrough(
|
|
276
|
+
new TransformStream<Uint8Array, Uint8Array>({
|
|
277
|
+
transform(chunk, controller) {
|
|
278
|
+
buf += dec.decode(chunk, { stream: true });
|
|
279
|
+
let i: number;
|
|
280
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
281
|
+
const line = buf.slice(0, i).trim();
|
|
282
|
+
buf = buf.slice(i + 1);
|
|
283
|
+
handle(line, controller);
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
flush(controller) {
|
|
287
|
+
buf += dec.decode();
|
|
288
|
+
handle(buf.trim(), controller);
|
|
289
|
+
buf = "";
|
|
290
|
+
},
|
|
291
|
+
}),
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Routes SDK client-side callbacks to the transport's option handlers.
|
|
297
|
+
*
|
|
298
|
+
* Methods are attached in the CONSTRUCTOR rather than declared, because the SDK probes
|
|
299
|
+
* `client.method?.()` — a declared-but-stubbed method makes us look capable while
|
|
300
|
+
* answering with nonsense. Absent is the honest signal for "not implemented".
|
|
301
|
+
*/
|
|
166
302
|
class ClientHandler implements acp.Client {
|
|
167
|
-
|
|
303
|
+
createTerminal?: acp.Client["createTerminal"];
|
|
304
|
+
terminalOutput?: acp.Client["terminalOutput"];
|
|
305
|
+
waitForTerminalExit?: acp.Client["waitForTerminalExit"];
|
|
306
|
+
killTerminal?: acp.Client["killTerminal"];
|
|
307
|
+
releaseTerminal?: acp.Client["releaseTerminal"];
|
|
308
|
+
readTextFile?: acp.Client["readTextFile"];
|
|
309
|
+
writeTextFile?: acp.Client["writeTextFile"];
|
|
310
|
+
|
|
311
|
+
constructor(private opts: AcpTransportOptions) {
|
|
312
|
+
if (opts.onReadTextFile) this.readTextFile = (p) => opts.onReadTextFile!(p);
|
|
313
|
+
if (opts.onWriteTextFile) this.writeTextFile = (p) => opts.onWriteTextFile!(p);
|
|
168
314
|
|
|
315
|
+
const terminals = opts.terminals;
|
|
316
|
+
if (terminals) {
|
|
317
|
+
this.createTerminal = (p) => terminals.create(p);
|
|
318
|
+
this.terminalOutput = (p) => terminals.output(p);
|
|
319
|
+
this.waitForTerminalExit = (p) => terminals.waitForExit(p);
|
|
320
|
+
this.killTerminal = (p) => terminals.kill(p);
|
|
321
|
+
this.releaseTerminal = (p) => terminals.release(p);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Safety net: `interceptUpdates` normally takes these before the SDK sees them. */
|
|
169
326
|
async sessionUpdate(params: schema.SessionNotification): Promise<void> {
|
|
170
327
|
this.opts.onUpdate?.(params);
|
|
171
328
|
}
|
|
@@ -176,18 +333,4 @@ class ClientHandler implements acp.Client {
|
|
|
176
333
|
if (this.opts.onPermissionRequest) return this.opts.onPermissionRequest(params);
|
|
177
334
|
return { outcome: { outcome: "cancelled" } };
|
|
178
335
|
}
|
|
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
336
|
}
|