@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/agent-session.ts
CHANGED
|
@@ -9,9 +9,10 @@
|
|
|
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
14
|
import { join } from "node:path";
|
|
15
|
+
import { ActivityAggregator, type ActivitySnapshot, type AggregatedRecord } from "./activity.ts";
|
|
15
16
|
import type { Adapter } from "./adapters.ts";
|
|
16
17
|
import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
|
|
17
18
|
import type { Capabilities } from "./capabilities.ts";
|
|
@@ -19,13 +20,19 @@ import type { ConfigOptions } from "./config-options.ts";
|
|
|
19
20
|
import type { ConnectResult } from "./client.ts";
|
|
20
21
|
import { noopLogger, type Logger } from "./logger.ts";
|
|
21
22
|
import type { SessionManager, MergedSession } from "./session-manager.ts";
|
|
22
|
-
import {
|
|
23
|
+
import {
|
|
24
|
+
appendTranscriptLine,
|
|
25
|
+
type TranscriptActivityLine,
|
|
26
|
+
type TranscriptLine,
|
|
27
|
+
} from "./transcript.ts";
|
|
23
28
|
import type {
|
|
29
|
+
ActivityEvent,
|
|
24
30
|
AgentCommand,
|
|
25
31
|
Attachment,
|
|
26
32
|
PromptHandlers,
|
|
27
33
|
PromptResult,
|
|
28
34
|
SessionListEntry,
|
|
35
|
+
WireEntry,
|
|
29
36
|
} from "./types.ts";
|
|
30
37
|
|
|
31
38
|
interface QueueItem {
|
|
@@ -36,6 +43,48 @@ interface QueueItem {
|
|
|
36
43
|
reject: (e: unknown) => void;
|
|
37
44
|
}
|
|
38
45
|
|
|
46
|
+
/** What to record when `transcriptActivity` is on. */
|
|
47
|
+
export interface TranscriptActivityConfig {
|
|
48
|
+
/**
|
|
49
|
+
* Which record kinds to persist. Default: `tool`, `thinking`, `plan`, `plan_update`,
|
|
50
|
+
* `plan_removed`, `usage`, `mode`, `unknown` — everything except client state
|
|
51
|
+
* (`commands`, `config`, `session_info`) and `user_message`, which duplicates `t:"msg"`.
|
|
52
|
+
*/
|
|
53
|
+
kinds?: Array<ActivityEvent["kind"]>;
|
|
54
|
+
/**
|
|
55
|
+
* Write an extra line the first time a tool call learns its arguments. Default true —
|
|
56
|
+
* agents routinely announce a call long before they know what it will run, so without
|
|
57
|
+
* this a turn that dies mid-call leaves a record naming the tool but not the command.
|
|
58
|
+
*
|
|
59
|
+
* This is an aggregator-level knob, so it also shapes `onRecord`'s `emitted` when no
|
|
60
|
+
* transcript is configured.
|
|
61
|
+
*/
|
|
62
|
+
checkpointOnInput?: boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Persist `rawOutput`. Default false: in practice it is a byte-identical duplicate of
|
|
65
|
+
* `content` (measured on live Kimi), so it doubles the largest field on the line.
|
|
66
|
+
*/
|
|
67
|
+
rawOutput?: boolean;
|
|
68
|
+
/**
|
|
69
|
+
* Cap each individual string field (terminal output, text content, a stringified
|
|
70
|
+
* `rawInput`) at this many bytes, appending `… [truncated N bytes]` and marking the
|
|
71
|
+
* line `truncated: true`. Default off. Per-field on purpose — capping the serialized
|
|
72
|
+
* line would emit unparseable JSON.
|
|
73
|
+
*/
|
|
74
|
+
maxBytes?: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const DEFAULT_ACTIVITY_KINDS: Array<ActivityEvent["kind"]> = [
|
|
78
|
+
"tool",
|
|
79
|
+
"thinking",
|
|
80
|
+
"plan",
|
|
81
|
+
"plan_update",
|
|
82
|
+
"plan_removed",
|
|
83
|
+
"usage",
|
|
84
|
+
"mode",
|
|
85
|
+
"unknown",
|
|
86
|
+
];
|
|
87
|
+
|
|
39
88
|
export interface AgentSessionConfig {
|
|
40
89
|
/** The resolved adapter this conversation talks to. */
|
|
41
90
|
adapter: Adapter;
|
|
@@ -50,13 +99,28 @@ export interface AgentSessionConfig {
|
|
|
50
99
|
mcpServers?: schema.McpServer[];
|
|
51
100
|
defaultPermission?: "approve" | "cancel";
|
|
52
101
|
clientInfo?: { name: string; title?: string; version?: string };
|
|
102
|
+
/** What we let the agent do through us (terminals, filesystem). All on by default. */
|
|
103
|
+
clientCapabilities?: AgentControllerConfig["clientCapabilities"];
|
|
53
104
|
logger?: Logger;
|
|
105
|
+
/** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
|
|
106
|
+
wire?: (entry: WireEntry) => void;
|
|
54
107
|
/** Optional catalog. When present, the session records itself here. */
|
|
55
108
|
sessions?: SessionManager;
|
|
56
109
|
/** Absolute path to an append-only transcript file. Omitted means no transcript. */
|
|
57
110
|
transcriptPath?: string;
|
|
58
111
|
/** Directory for a library-named transcript file: `<agentSessionId>.jsonl`. */
|
|
59
112
|
transcriptDir?: string;
|
|
113
|
+
/**
|
|
114
|
+
* Also record activity (thinking, tool calls and their output, plans) as `t:"activity"`
|
|
115
|
+
* lines. Off by default — it makes transcripts larger, and `readTranscript()` ignores
|
|
116
|
+
* them either way; read them with `readTranscriptLines()`.
|
|
117
|
+
*
|
|
118
|
+
* Lines are SETTLED records, not raw deltas: the session folds the delta stream and
|
|
119
|
+
* writes checkpoints (announced → input → settled), typically 2–3 lines per tool call
|
|
120
|
+
* instead of one per notification. Fold them back with `foldRecords()`, last-wins on
|
|
121
|
+
* `recordId`. `true` selects the defaults below.
|
|
122
|
+
*/
|
|
123
|
+
transcriptActivity?: boolean | TranscriptActivityConfig;
|
|
60
124
|
/** Our stable AgentSession id. Minted if omitted; pass a record's agentSessionId to resume. */
|
|
61
125
|
agentSessionId?: string;
|
|
62
126
|
/** ACP/harness session to load on start (resume an existing provider conversation). */
|
|
@@ -72,6 +136,17 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
72
136
|
private readonly controller: AgentController;
|
|
73
137
|
private readonly sessions?: SessionManager;
|
|
74
138
|
private readonly transcriptPath?: string;
|
|
139
|
+
private readonly transcriptActivity: boolean;
|
|
140
|
+
private readonly activityKinds: Set<string>;
|
|
141
|
+
private readonly activityRawOutput: boolean;
|
|
142
|
+
private readonly activityMaxBytes: number | null;
|
|
143
|
+
/**
|
|
144
|
+
* THE aggregator — one per session for its whole life, never one per turn: `seq` has to
|
|
145
|
+
* keep counting across turns or a subscriber's discard threshold goes stale (see
|
|
146
|
+
* `activitySnapshot`). Runs unconditionally, so a snapshot is truthful and `onRecord`
|
|
147
|
+
* works whether or not a transcript is configured.
|
|
148
|
+
*/
|
|
149
|
+
private readonly aggregator: ActivityAggregator;
|
|
75
150
|
private readonly log: Logger;
|
|
76
151
|
private transcriptWrite: Promise<void> = Promise.resolve();
|
|
77
152
|
private queue: QueueItem[] = [];
|
|
@@ -93,6 +168,14 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
93
168
|
(config.transcriptDir
|
|
94
169
|
? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
|
|
95
170
|
: undefined);
|
|
171
|
+
const activity: TranscriptActivityConfig | null =
|
|
172
|
+
config.transcriptActivity === true ? {} : config.transcriptActivity || null;
|
|
173
|
+
this.transcriptActivity = activity !== null;
|
|
174
|
+
this.activityKinds = new Set(activity?.kinds ?? DEFAULT_ACTIVITY_KINDS);
|
|
175
|
+
this.activityRawOutput = activity?.rawOutput === true;
|
|
176
|
+
this.activityMaxBytes =
|
|
177
|
+
activity?.maxBytes != null && activity.maxBytes > 0 ? activity.maxBytes : null;
|
|
178
|
+
this.aggregator = new ActivityAggregator({ checkpointOnInput: activity?.checkpointOnInput });
|
|
96
179
|
this.log = config.logger ?? noopLogger;
|
|
97
180
|
this._mode = config.mode ?? "normal";
|
|
98
181
|
this._cwd = config.cwd;
|
|
@@ -109,7 +192,9 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
109
192
|
mcpServers: config.mcpServers,
|
|
110
193
|
defaultPermission: config.defaultPermission,
|
|
111
194
|
clientInfo: config.clientInfo,
|
|
195
|
+
clientCapabilities: config.clientCapabilities,
|
|
112
196
|
logger: config.logger,
|
|
197
|
+
wire: config.wire,
|
|
113
198
|
});
|
|
114
199
|
}
|
|
115
200
|
|
|
@@ -186,6 +271,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
186
271
|
}
|
|
187
272
|
|
|
188
273
|
private async runPrompt(item: QueueItem): Promise<PromptResult> {
|
|
274
|
+
this.beginTurn();
|
|
189
275
|
await this.appendTranscript({
|
|
190
276
|
v: 1,
|
|
191
277
|
t: "msg",
|
|
@@ -197,14 +283,28 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
197
283
|
const chunks: string[] = [];
|
|
198
284
|
const wrappedHandlers: PromptHandlers = {
|
|
199
285
|
...item.handlers,
|
|
286
|
+
// Fired from here, from the one aggregator this session owns — nothing below needs
|
|
287
|
+
// to know the handler exists, and two places firing it would be two folds.
|
|
288
|
+
onRecord: undefined,
|
|
200
289
|
onChunk: (chunk) => {
|
|
201
290
|
chunks.push(chunk);
|
|
202
291
|
item.handlers?.onChunk?.(chunk);
|
|
203
292
|
},
|
|
293
|
+
onActivity: (event) => {
|
|
294
|
+
const result = this.aggregator.apply(event);
|
|
295
|
+
if (this.transcriptActivity) {
|
|
296
|
+
for (const record of result.emitted) this.writeActivity(record);
|
|
297
|
+
}
|
|
298
|
+
item.handlers?.onRecord?.(result);
|
|
299
|
+
item.handlers?.onActivity?.(event);
|
|
300
|
+
},
|
|
204
301
|
};
|
|
205
302
|
|
|
206
303
|
try {
|
|
207
304
|
const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
|
|
305
|
+
// Before the assistant msg: `msg` delimits a turn, so anything still open has to
|
|
306
|
+
// land inside those fences.
|
|
307
|
+
this.endTurn(item.handlers);
|
|
208
308
|
if (!this._title && item.text.trim()) {
|
|
209
309
|
this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
|
|
210
310
|
}
|
|
@@ -223,6 +323,9 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
223
323
|
});
|
|
224
324
|
return res;
|
|
225
325
|
} catch (err) {
|
|
326
|
+
// Easy to miss, and the whole point of R4: a turn that died mid-tool still records
|
|
327
|
+
// what it was doing, at its real status.
|
|
328
|
+
this.endTurn(item.handlers);
|
|
226
329
|
await this.appendTranscript({
|
|
227
330
|
v: 1,
|
|
228
331
|
t: "msg",
|
|
@@ -236,6 +339,90 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
236
339
|
}
|
|
237
340
|
}
|
|
238
341
|
|
|
342
|
+
// --- activity ----------------------------------------------------------------
|
|
343
|
+
/**
|
|
344
|
+
* Full state of the turn IN FLIGHT, for a subscriber that joins mid-turn: send these
|
|
345
|
+
* records, then stream frames, discarding any whose `seq` is not greater than
|
|
346
|
+
* `snapshot.seq`. Without that, a thinking delta already folded into the snapshot gets
|
|
347
|
+
* applied twice. The threshold stays valid indefinitely — `seq` never restarts.
|
|
348
|
+
*
|
|
349
|
+
* Between turns this is `{ active: false, records: [] }`. A settled turn belongs to the
|
|
350
|
+
* transcript, not to a replay: handing it to a client connecting mid-idle would put
|
|
351
|
+
* activity in its log before the messages around it had loaded.
|
|
352
|
+
*/
|
|
353
|
+
activitySnapshot(): ActivitySnapshot {
|
|
354
|
+
return this.aggregator.snapshot();
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private beginTurn(): void {
|
|
358
|
+
// A correct caller always gets an empty array back — both exit paths flush. If one
|
|
359
|
+
// ever doesn't, keeping the records (loudly) beats dropping them.
|
|
360
|
+
const leftover = this.aggregator.startTurn(this.mintTurnId());
|
|
361
|
+
if (leftover.length > 0) {
|
|
362
|
+
this.log.warn("activity_turn_not_flushed", { records: leftover.length });
|
|
363
|
+
if (this.transcriptActivity) for (const record of leftover) this.writeActivity(record);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private endTurn(handlers?: PromptHandlers): void {
|
|
368
|
+
const emitted = this.aggregator.flush();
|
|
369
|
+
if (emitted.length === 0) return;
|
|
370
|
+
if (this.transcriptActivity) for (const record of emitted) this.writeActivity(record);
|
|
371
|
+
// Live subscribers need these too: without them, a tool call on a turn that was
|
|
372
|
+
// cancelled or crashed spins forever in the UI. `wireFrames()` handles this shape.
|
|
373
|
+
handlers?.onRecord?.({ current: null, delta: null, emitted });
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Namespace for the record ids the aggregator MINTS (`think-1`, `plan`, `usage`), which
|
|
378
|
+
* are only unique within one turn — the transcript spans many, so unprefixed ids would
|
|
379
|
+
* collapse under last-wins folding.
|
|
380
|
+
*
|
|
381
|
+
* Deliberately not a counter: a resumed session restarts an in-memory counter at 0 and
|
|
382
|
+
* collides with ids already on disk. Timestamp keeps it ordered and restart-stable; the
|
|
383
|
+
* random suffix covers two turns in the same millisecond.
|
|
384
|
+
*/
|
|
385
|
+
private mintTurnId(): string {
|
|
386
|
+
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Persist one settled record. Filtering lives here, not in the aggregator: the
|
|
391
|
+
* aggregator owns semantics, the writer owns policy.
|
|
392
|
+
*
|
|
393
|
+
* Fire and forget — `appendTranscript` serializes writes in call order, so ordering
|
|
394
|
+
* holds without blocking the agent's update stream on disk.
|
|
395
|
+
*/
|
|
396
|
+
private writeActivity(record: AggregatedRecord): void {
|
|
397
|
+
if (!this.transcriptPath) return;
|
|
398
|
+
if (!this.activityKinds.has(record.event.kind)) return;
|
|
399
|
+
void this.appendTranscript(this.toActivityLine(record));
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private toActivityLine(record: AggregatedRecord): TranscriptActivityLine {
|
|
403
|
+
let fields: Record<string, unknown> = { ...record.event };
|
|
404
|
+
if (!this.activityRawOutput) delete fields.rawOutput;
|
|
405
|
+
|
|
406
|
+
let truncated = false;
|
|
407
|
+
if (this.activityMaxBytes != null) {
|
|
408
|
+
const capped = capActivityStrings(fields, this.activityMaxBytes);
|
|
409
|
+
fields = capped.fields;
|
|
410
|
+
truncated = capped.truncated;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const line: TranscriptActivityLine = {
|
|
414
|
+
...fields,
|
|
415
|
+
v: 1,
|
|
416
|
+
t: "activity",
|
|
417
|
+
ts: Date.now(),
|
|
418
|
+
recordId: record.recordId,
|
|
419
|
+
reason: record.reason,
|
|
420
|
+
kind: record.event.kind,
|
|
421
|
+
};
|
|
422
|
+
if (truncated) line.truncated = true;
|
|
423
|
+
return line;
|
|
424
|
+
}
|
|
425
|
+
|
|
239
426
|
interrupt(options?: InterruptOptions): void {
|
|
240
427
|
if (options?.clearQueue) {
|
|
241
428
|
const dropped = this.queue.splice(0);
|
|
@@ -337,3 +524,58 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
337
524
|
await this.transcriptWrite;
|
|
338
525
|
}
|
|
339
526
|
}
|
|
527
|
+
|
|
528
|
+
const encoder = new TextEncoder();
|
|
529
|
+
const decoder = new TextDecoder();
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Cap the fields that can realistically reach megabytes — terminal output, text content,
|
|
533
|
+
* diffs, and a stringified `rawInput` — one field at a time so the JSON structure survives.
|
|
534
|
+
* An oversized `rawInput` object becomes its truncated serialization, which is lossy by
|
|
535
|
+
* design; `truncated: true` on the line says so.
|
|
536
|
+
*/
|
|
537
|
+
function capActivityStrings(
|
|
538
|
+
fields: Record<string, unknown>,
|
|
539
|
+
maxBytes: number,
|
|
540
|
+
): { fields: Record<string, unknown>; truncated: boolean } {
|
|
541
|
+
let truncated = false;
|
|
542
|
+
const cap = (text: string): string => {
|
|
543
|
+
const bytes = encoder.encode(text);
|
|
544
|
+
if (bytes.length <= maxBytes) return text;
|
|
545
|
+
// Back up off a continuation byte (0b10xxxxxx) so a multi-byte character is never
|
|
546
|
+
// split — decoding a partial sequence would yield U+FFFD.
|
|
547
|
+
let end = maxBytes;
|
|
548
|
+
while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
|
|
549
|
+
truncated = true;
|
|
550
|
+
return `${decoder.decode(bytes.subarray(0, end))}… [truncated ${bytes.length - end} bytes]`;
|
|
551
|
+
};
|
|
552
|
+
const capUnknown = (value: unknown): unknown => {
|
|
553
|
+
if (typeof value === "string") return cap(value);
|
|
554
|
+
const text = JSON.stringify(value) ?? "";
|
|
555
|
+
const capped = cap(text);
|
|
556
|
+
return capped === text ? value : capped;
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
const out = { ...fields };
|
|
560
|
+
if (out.rawInput !== undefined) out.rawInput = capUnknown(out.rawInput);
|
|
561
|
+
if (out.rawOutput !== undefined) out.rawOutput = capUnknown(out.rawOutput);
|
|
562
|
+
if (typeof out.text === "string") out.text = cap(out.text);
|
|
563
|
+
if (Array.isArray(out.content)) {
|
|
564
|
+
out.content = (out.content as unknown[]).map((entry) => {
|
|
565
|
+
if (entry === null || typeof entry !== "object") return entry;
|
|
566
|
+
const item = { ...(entry as Record<string, unknown>) };
|
|
567
|
+
if (typeof item.text === "string") item.text = cap(item.text);
|
|
568
|
+
if (typeof item.output === "string") item.output = cap(item.output);
|
|
569
|
+
if (typeof item.oldText === "string") item.oldText = cap(item.oldText);
|
|
570
|
+
if (typeof item.newText === "string") item.newText = cap(item.newText);
|
|
571
|
+
// `text` on a content entry is our convenience copy; the block itself still holds it.
|
|
572
|
+
if (item.content !== null && typeof item.content === "object") {
|
|
573
|
+
const block = { ...(item.content as Record<string, unknown>) };
|
|
574
|
+
if (typeof block.text === "string") block.text = cap(block.text);
|
|
575
|
+
item.content = block;
|
|
576
|
+
}
|
|
577
|
+
return item;
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
return { fields: out, truncated };
|
|
581
|
+
}
|
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/cli/index.ts
CHANGED
|
@@ -6,16 +6,19 @@
|
|
|
6
6
|
// Usage:
|
|
7
7
|
// acp-lib chat [SESSION_ID] [--adapter kimi] [--exec "docker exec -i <ctr>"]
|
|
8
8
|
// [--cwd /workspace] [--approve] [--verbose] [--debug]
|
|
9
|
-
// [--no-activity] [--degraded]
|
|
9
|
+
// [--no-activity] [--degraded] [--wire[=FILE]]
|
|
10
10
|
//
|
|
11
11
|
// activity (thinking/tool markers) shows by DEFAULT; --no-activity disables it.
|
|
12
12
|
// --verbose (-v): lifecycle summaries (connect, session_new, prompt_end)
|
|
13
13
|
// --debug (-d): the above PLUS raw protocol payloads (initialize/prompt/session_update)
|
|
14
|
+
// --wire : dump every raw protocol line, both directions, to stderr
|
|
15
|
+
// --wire=FILE : the same as ndjson in FILE (truncated per run) instead of stderr
|
|
14
16
|
|
|
15
17
|
import {
|
|
16
18
|
AgentController,
|
|
17
19
|
ADAPTERS,
|
|
18
20
|
createConsoleLogger,
|
|
21
|
+
createWireLog,
|
|
19
22
|
type AdapterPreset,
|
|
20
23
|
} from "../index.ts";
|
|
21
24
|
import { createAgentCommands, runRepl } from "../repl/index.ts";
|
|
@@ -32,6 +35,8 @@ interface Args {
|
|
|
32
35
|
verbose: boolean;
|
|
33
36
|
debug: boolean;
|
|
34
37
|
activity: boolean;
|
|
38
|
+
/** undefined = off, "" = stderr, otherwise a file path. */
|
|
39
|
+
wire?: string;
|
|
35
40
|
}
|
|
36
41
|
|
|
37
42
|
function parseArgs(argv: string[]): Args {
|
|
@@ -55,6 +60,8 @@ function parseArgs(argv: string[]): Args {
|
|
|
55
60
|
else if (arg === "--verbose" || arg === "-v") a.verbose = true;
|
|
56
61
|
else if (arg === "--debug" || arg === "-d") a.debug = true;
|
|
57
62
|
else if (arg === "--no-activity" || arg === "--disable-activity") a.activity = false;
|
|
63
|
+
else if (arg === "--wire") a.wire = "";
|
|
64
|
+
else if (arg?.startsWith("--wire=")) a.wire = arg.slice("--wire=".length);
|
|
58
65
|
else if (arg && !arg.startsWith("--")) a.sessionId = arg;
|
|
59
66
|
}
|
|
60
67
|
return a;
|
|
@@ -68,6 +75,16 @@ async function chat(args: Args): Promise<void> {
|
|
|
68
75
|
const minLevel = args.debug ? "debug" : args.verbose ? "info" : "warn";
|
|
69
76
|
const logger = createConsoleLogger({ minLevel });
|
|
70
77
|
|
|
78
|
+
// A wire dump to stderr would fight the spinner's \r and the streamed reply, so the
|
|
79
|
+
// file form is the usable one for a real conversation.
|
|
80
|
+
const wire =
|
|
81
|
+
args.wire === undefined
|
|
82
|
+
? undefined
|
|
83
|
+
: args.wire === ""
|
|
84
|
+
? createWireLog({ console: "stderr" })
|
|
85
|
+
: createWireLog({ path: args.wire });
|
|
86
|
+
if (args.wire) process.stderr.write(`wire log: ${args.wire}\n`);
|
|
87
|
+
|
|
71
88
|
const controller = new AgentController({
|
|
72
89
|
adapter: ADAPTERS[args.adapter],
|
|
73
90
|
adapterId: args.adapter,
|
|
@@ -77,6 +94,7 @@ async function chat(args: Args): Promise<void> {
|
|
|
77
94
|
sessionId: args.sessionId,
|
|
78
95
|
defaultPermission: args.approve ? "approve" : "cancel",
|
|
79
96
|
logger,
|
|
97
|
+
wire,
|
|
80
98
|
});
|
|
81
99
|
|
|
82
100
|
const { sessionId, resumed } = await controller.start();
|
|
@@ -94,8 +112,8 @@ async function chat(args: Args): Promise<void> {
|
|
|
94
112
|
try {
|
|
95
113
|
await runRepl(controller, {
|
|
96
114
|
activity: args.activity,
|
|
97
|
-
// Suppress the spinner
|
|
98
|
-
spinner: !args.debug,
|
|
115
|
+
// Suppress the spinner when raw lines are going to the terminal — they fight its \r.
|
|
116
|
+
spinner: !args.debug && args.wire !== "",
|
|
99
117
|
intro,
|
|
100
118
|
onSlashCommand: commands.onSlashCommand,
|
|
101
119
|
});
|
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,8 @@ import type {
|
|
|
28
33
|
Attachment,
|
|
29
34
|
SessionListPage,
|
|
30
35
|
AgentCommand,
|
|
36
|
+
ToolContent,
|
|
37
|
+
WireEntry,
|
|
31
38
|
} from "./types.ts";
|
|
32
39
|
|
|
33
40
|
export interface AcpClientConfig {
|
|
@@ -45,8 +52,20 @@ export interface AcpClientConfig {
|
|
|
45
52
|
defaultPermission?: "approve" | "cancel";
|
|
46
53
|
/** Identification sent in initialize. */
|
|
47
54
|
clientInfo?: { name: string; title?: string; version?: string };
|
|
55
|
+
/**
|
|
56
|
+
* What we let the agent do through us: filesystem reads/writes and terminals. All
|
|
57
|
+
* enabled by default. Disabling one stops us advertising it, so the agent falls back
|
|
58
|
+
* to its own implementation instead of calling a method we won't answer.
|
|
59
|
+
*/
|
|
60
|
+
clientCapabilities?: ClientCapabilityConfig;
|
|
48
61
|
/** Diagnostics sink. Omit for a silent library. */
|
|
49
62
|
logger?: Logger;
|
|
63
|
+
/**
|
|
64
|
+
* Raw protocol traffic, every line in both directions — the debugging view. Off unless
|
|
65
|
+
* set; a wire log holds everything the agent said, file contents and command output
|
|
66
|
+
* included, so where it goes is the caller's call. `createWireLog()` builds a sink.
|
|
67
|
+
*/
|
|
68
|
+
wire?: (entry: WireEntry) => void;
|
|
50
69
|
}
|
|
51
70
|
|
|
52
71
|
export interface StartSessionOptions {
|
|
@@ -114,10 +133,15 @@ export class AcpClient implements AgentClient {
|
|
|
114
133
|
// caller can show it — auth output almost always arrives on stderr, not the protocol.
|
|
115
134
|
private authStderrSink: ((line: string) => void) | null = null;
|
|
116
135
|
|
|
136
|
+
// Terminals the AGENT is driving through us. Null when the capability is disabled.
|
|
137
|
+
private terminals: TerminalRegistry | null = null;
|
|
138
|
+
|
|
117
139
|
private readonly log: Logger;
|
|
140
|
+
private readonly clientCapabilities: ClientCapabilities;
|
|
118
141
|
|
|
119
142
|
constructor(private config: AcpClientConfig) {
|
|
120
143
|
this.log = config.logger ?? noopLogger;
|
|
144
|
+
this.clientCapabilities = buildClientCapabilities(config.clientCapabilities);
|
|
121
145
|
}
|
|
122
146
|
|
|
123
147
|
// --- introspection (populated by connect) -------------------------------------
|
|
@@ -164,6 +188,15 @@ export class AcpClient implements AgentClient {
|
|
|
164
188
|
|
|
165
189
|
this.log.info("connect", { command, dockerExec: isDockerExec });
|
|
166
190
|
|
|
191
|
+
const caps = this.clientCapabilities;
|
|
192
|
+
this.terminals = caps.terminal
|
|
193
|
+
? new TerminalRegistry({
|
|
194
|
+
cwd: this.config.cwd,
|
|
195
|
+
env: this.config.env,
|
|
196
|
+
logger: this.config.logger,
|
|
197
|
+
})
|
|
198
|
+
: null;
|
|
199
|
+
|
|
167
200
|
const transport = new AcpTransport({
|
|
168
201
|
command,
|
|
169
202
|
// docker exec resolves paths inside the container's namespace — don't pass a host cwd.
|
|
@@ -171,6 +204,17 @@ export class AcpClient implements AgentClient {
|
|
|
171
204
|
env: this.config.env,
|
|
172
205
|
onUpdate: (n) => this.handleUpdate(n),
|
|
173
206
|
onPermissionRequest: (p) => this.handlePermission(p),
|
|
207
|
+
onReadTextFile: caps.fs.readTextFile
|
|
208
|
+
? async (p) => ({ content: await readTextFile(p) })
|
|
209
|
+
: undefined,
|
|
210
|
+
onWriteTextFile: caps.fs.writeTextFile
|
|
211
|
+
? async (p) => {
|
|
212
|
+
await writeTextFile(p);
|
|
213
|
+
return {};
|
|
214
|
+
}
|
|
215
|
+
: undefined,
|
|
216
|
+
terminals: this.terminals ? this.terminalHandlers(this.terminals) : undefined,
|
|
217
|
+
onWire: this.config.wire,
|
|
174
218
|
onStderr: (line) => {
|
|
175
219
|
this.log.debug("agent_stderr", { line });
|
|
176
220
|
this.authStderrSink?.(line);
|
|
@@ -187,7 +231,7 @@ export class AcpClient implements AgentClient {
|
|
|
187
231
|
const init = await transport.raceExit(
|
|
188
232
|
transport.initialize({
|
|
189
233
|
protocolVersion: PROTOCOL_VERSION,
|
|
190
|
-
clientCapabilities:
|
|
234
|
+
clientCapabilities: caps as unknown as schema.ClientCapabilities,
|
|
191
235
|
clientInfo: this.config.clientInfo ?? {
|
|
192
236
|
name: "acp-lib",
|
|
193
237
|
title: "ACP Lib",
|
|
@@ -195,7 +239,7 @@ export class AcpClient implements AgentClient {
|
|
|
195
239
|
},
|
|
196
240
|
} as schema.InitializeRequest),
|
|
197
241
|
);
|
|
198
|
-
this._capabilities = parseCapabilities(init);
|
|
242
|
+
this._capabilities = parseCapabilities(init, caps);
|
|
199
243
|
this.log.info("initialized", {
|
|
200
244
|
agent: this._capabilities.agentInfo?.name,
|
|
201
245
|
protocolVersion: this._capabilities.protocolVersion,
|
|
@@ -422,10 +466,29 @@ export class AcpClient implements AgentClient {
|
|
|
422
466
|
const t = this.transport;
|
|
423
467
|
this.transport = null;
|
|
424
468
|
this._sessionId = null;
|
|
469
|
+
this.terminals?.releaseAll();
|
|
470
|
+
this.terminals = null;
|
|
425
471
|
if (t) await t.stop();
|
|
426
472
|
this.log.info("stopped", {});
|
|
427
473
|
}
|
|
428
474
|
|
|
475
|
+
/** Adapt the registry to the transport's async handler shape. */
|
|
476
|
+
private terminalHandlers(registry: TerminalRegistry) {
|
|
477
|
+
return {
|
|
478
|
+
create: async (p: schema.CreateTerminalRequest) => ({
|
|
479
|
+
terminalId: registry.create(p as Parameters<TerminalRegistry["create"]>[0]),
|
|
480
|
+
}),
|
|
481
|
+
output: async (p: schema.TerminalOutputRequest) => {
|
|
482
|
+
const { output, truncated, exitStatus } = registry.output(p.terminalId);
|
|
483
|
+
return { output, truncated, exitStatus };
|
|
484
|
+
},
|
|
485
|
+
waitForExit: async (p: schema.WaitForTerminalExitRequest) =>
|
|
486
|
+
registry.waitForExit(p.terminalId),
|
|
487
|
+
kill: async (p: schema.KillTerminalRequest) => registry.kill(p.terminalId),
|
|
488
|
+
release: async (p: schema.ReleaseTerminalRequest) => registry.release(p.terminalId),
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
429
492
|
// --- prompting ----------------------------------------------------------------
|
|
430
493
|
|
|
431
494
|
prompt(
|
|
@@ -544,9 +607,7 @@ export class AcpClient implements AgentClient {
|
|
|
544
607
|
this._configOptions = parseConfigOptions((update as Record<string, any>).configOptions);
|
|
545
608
|
}
|
|
546
609
|
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
|
-
);
|
|
610
|
+
this._agentCommands = toAgentCommands((update as Record<string, any>).availableCommands);
|
|
550
611
|
}
|
|
551
612
|
|
|
552
613
|
if (!this.active) {
|
|
@@ -557,13 +618,37 @@ export class AcpClient implements AgentClient {
|
|
|
557
618
|
}
|
|
558
619
|
if (notification.sessionId && notification.sessionId !== this._sessionId) return;
|
|
559
620
|
|
|
621
|
+
this.active.handlers?.onUpdate?.(notification);
|
|
622
|
+
|
|
560
623
|
const text = extractChunkText(update);
|
|
561
624
|
if (text) {
|
|
562
625
|
this.active.chunks.push(text);
|
|
563
626
|
this.active.handlers?.onChunk?.(text);
|
|
564
627
|
}
|
|
565
628
|
const activity = toActivityEvent(update);
|
|
566
|
-
if (activity) this.active.handlers?.onActivity?.(activity);
|
|
629
|
+
if (activity) this.active.handlers?.onActivity?.(this.enrich(activity));
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* Fill in terminal output on tool-call content. The agent only sends a `terminalId`
|
|
634
|
+
* (it's polling us for the bytes), so without this the caller sees a tool call it
|
|
635
|
+
* cannot render — the terminal is OURS, and only we can read it.
|
|
636
|
+
*/
|
|
637
|
+
private enrich(event: ActivityEvent): ActivityEvent {
|
|
638
|
+
if (event.kind !== "tool" && event.kind !== "tool_update") return event;
|
|
639
|
+
const registry = this.terminals;
|
|
640
|
+
if (!registry || !event.content?.some((c) => c.type === "terminal")) return event;
|
|
641
|
+
|
|
642
|
+
const content = event.content.map((c): ToolContent => {
|
|
643
|
+
if (c.type !== "terminal" || !registry.has(c.terminalId)) return c;
|
|
644
|
+
try {
|
|
645
|
+
const snapshot = registry.output(c.terminalId);
|
|
646
|
+
return { ...c, ...snapshot };
|
|
647
|
+
} catch {
|
|
648
|
+
return c; // released between the check and the read
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
return { ...event, content };
|
|
567
652
|
}
|
|
568
653
|
|
|
569
654
|
private async handlePermission(
|