@qlairoslabs/acp-client 0.1.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.
@@ -0,0 +1,312 @@
1
+ // Interactive REPL — reusable presentation/UI over the AgentClient output contract.
2
+ // Depends ONLY on AgentClient (prompt + interrupt), so it works against AcpClient today
3
+ // and PtyClient (degraded mode) later, unchanged. The caller owns the client lifecycle
4
+ // (connect/stop); the REPL just drives the interaction.
5
+ //
6
+ // Keys: ESC interrupts the in-flight turn · Ctrl-C interrupts a turn, or (when idle)
7
+ // exits after a confirmation press.
8
+ //
9
+ // I/O convention: agent RESPONSE TEXT → stdout; chrome (prompts, labels, markers,
10
+ // spinner, status) → stderr. So `repl ... > transcript` captures just the conversation,
11
+ // and color is only emitted to a TTY (respecting NO_COLOR).
12
+ //
13
+ // Two input paths:
14
+ // - interactive (TTY): a FRESH readline per line. readline is never alive while a turn
15
+ // streams, so its cursor model can't desync and erase our output (it does:
16
+ // _refreshLine → clearScreenDown with a stale row count). During a turn we read raw
17
+ // stdin ourselves for ESC/Ctrl-C.
18
+ // - piped (non-TTY): one flowing readline + queue. No erase risk (no cursor escapes),
19
+ // and a fresh-per-line interface there would drop buffered lines.
20
+
21
+ import * as readline from "node:readline";
22
+ import type { AgentClient, ActivityEvent } from "../index.ts";
23
+ import { BOLD, CYAN, DIM, colorEnabled, paint } from "./colors.ts";
24
+
25
+ const ESC = 0x1b;
26
+ const ETX = 0x03; // Ctrl-C
27
+ const EXIT_CONFIRM_MS = 3000;
28
+
29
+ export interface ReplOptions {
30
+ /** Show activity (thinking/tool) markers on stderr. Default true. */
31
+ activity?: boolean;
32
+ /** Show the "working…" spinner while waiting. Default true. */
33
+ spinner?: boolean;
34
+ /** Optional line printed (stderr) before the loop starts. Styled by the REPL. */
35
+ intro?: string;
36
+ /**
37
+ * Handle a `/slash` command. Return true if handled (the loop continues without
38
+ * prompting the agent); return false to treat the line as a normal prompt.
39
+ * `/exit` and `/quit` are always handled by the REPL itself.
40
+ *
41
+ * Extension seam for consumers (e.g. the orchestration hub's direct mode): add
42
+ * `/new`, `/model`, `/switch`, etc. without forking the REPL.
43
+ */
44
+ onSlashCommand?: (command: string, args: string[]) => boolean | Promise<boolean>;
45
+ }
46
+
47
+ export async function runRepl(
48
+ client: AgentClient,
49
+ options: ReplOptions = {},
50
+ ): Promise<void> {
51
+ const color = colorEnabled(process.stderr);
52
+ const interactive = Boolean(process.stdin.isTTY && process.stderr.isTTY);
53
+ const err = (s: string) => process.stderr.write(s);
54
+ // Response text: stdout when piped (clean transcript), but the SAME stream as chrome
55
+ // (stderr) when interactive — mixing stdout+stderr on one TTY reorders under Bun's
56
+ // independent buffering and scrambles the cursor (erasing output). Interactive callers
57
+ // who redirect stdout fall to the piped path (isTTY false), so this never hides output.
58
+ const out = (s: string) => (interactive ? process.stderr : process.stdout).write(s);
59
+ const prompt = paint(color, `${BOLD}${CYAN}`, "you ›") + " ";
60
+
61
+ if (options.intro) err(paint(color, DIM, options.intro) + "\n");
62
+
63
+ let busy = false;
64
+
65
+ // ---- handle one accepted line; returns true to keep looping, false to exit ----
66
+ const handleLine = async (line: string): Promise<boolean> => {
67
+ if (line === "/exit" || line === "/quit") return false;
68
+ // `//foo` = verbatim passthrough: send `/foo` to the AGENT as a prompt (its own slash
69
+ // command), bypassing our handlers. The escape hatch for name clashes like /sessions.
70
+ if (line.startsWith("//")) {
71
+ await runTurn(line.slice(1));
72
+ return true;
73
+ }
74
+ if (line.startsWith("/") && options.onSlashCommand) {
75
+ const [command = "", ...rest] = line.slice(1).split(/\s+/);
76
+ try {
77
+ if (await options.onSlashCommand(command, rest)) return true;
78
+ } catch (e) {
79
+ // A failing command (e.g. /load on a session with no rollout) must not crash the REPL.
80
+ err(paint(color, DIM, `(/${command} failed: ${String(e)})`) + "\n");
81
+ return true;
82
+ }
83
+ // not handled → fall through and send it as a normal prompt
84
+ }
85
+ await runTurn(line);
86
+ return true;
87
+ };
88
+
89
+ try {
90
+ if (interactive) await runInteractive(prompt, handleLine);
91
+ else await runPiped(prompt, handleLine);
92
+ } finally {
93
+ if (interactive && process.stdin.isTTY) {
94
+ try {
95
+ process.stdin.setRawMode(false);
96
+ } catch {
97
+ /* not a settable tty */
98
+ }
99
+ }
100
+ err("\n"); // leave the shell on a clean line (avoids zsh's reverse %/# marker)
101
+ }
102
+
103
+ // ---- interactive: fresh readline per line + raw input during the turn ----------
104
+ async function runInteractive(
105
+ promptStr: string,
106
+ onLine: (line: string) => Promise<boolean>,
107
+ ): Promise<void> {
108
+ let exitArmed = false;
109
+ let exitTimer: ReturnType<typeof setTimeout> | null = null;
110
+ const disarm = () => {
111
+ exitArmed = false;
112
+ if (exitTimer) {
113
+ clearTimeout(exitTimer);
114
+ exitTimer = null;
115
+ }
116
+ };
117
+
118
+ for (;;) {
119
+ const ev = await readOneLine(promptStr);
120
+ if (ev.type === "eof") break;
121
+ if (ev.type === "sigint") {
122
+ if (exitArmed) break; // confirmed → exit
123
+ exitArmed = true;
124
+ err(paint(color, DIM, "(press Ctrl-C again to exit, or type /exit)") + "\n");
125
+ exitTimer = setTimeout(() => (exitArmed = false), EXIT_CONFIRM_MS);
126
+ continue;
127
+ }
128
+ disarm();
129
+ const line = ev.value.trim();
130
+ if (!line) continue;
131
+ if (!(await onLine(line))) break;
132
+ }
133
+ }
134
+
135
+ // ---- piped: one flowing readline + queue (no TTY, no spinner, no raw) -----------
136
+ async function runPiped(
137
+ promptStr: string,
138
+ onLine: (line: string) => Promise<boolean>,
139
+ ): Promise<void> {
140
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
141
+ rl.setPrompt(promptStr);
142
+ const lines: string[] = [];
143
+ let waiter: (() => void) | null = null;
144
+ let closed = false;
145
+ const wake = () => {
146
+ waiter?.();
147
+ waiter = null;
148
+ };
149
+ rl.on("line", (l) => {
150
+ lines.push(l);
151
+ wake();
152
+ });
153
+ rl.on("close", () => {
154
+ closed = true;
155
+ wake();
156
+ });
157
+
158
+ rl.prompt();
159
+ try {
160
+ for (;;) {
161
+ while (lines.length === 0 && !closed) await new Promise<void>((r) => (waiter = r));
162
+ if (lines.length === 0 && closed) break;
163
+ const line = lines.shift()!.trim();
164
+ if (!line) {
165
+ rl.prompt();
166
+ continue;
167
+ }
168
+ if (!(await onLine(line))) break;
169
+ rl.prompt();
170
+ }
171
+ } finally {
172
+ rl.close();
173
+ }
174
+ }
175
+
176
+ // ---- one turn ------------------------------------------------------------------
177
+ async function runTurn(text: string): Promise<void> {
178
+ let wroteLabel = false;
179
+ let lastMarker = "";
180
+ let sawActivity = false;
181
+ const spinner =
182
+ interactive && options.spinner !== false ? startSpinner(color) : null;
183
+
184
+ // Take over raw stdin for ESC/Ctrl-C while the turn streams (interactive only).
185
+ let onData: ((d: Buffer) => void) | null = null;
186
+ if (interactive) {
187
+ try {
188
+ process.stdin.setRawMode(true);
189
+ } catch {
190
+ /* ignore */
191
+ }
192
+ onData = (d: Buffer) => {
193
+ for (const b of d) if (b === ESC || b === ETX) client.interrupt();
194
+ };
195
+ process.stdin.on("data", onData);
196
+ process.stdin.resume();
197
+ }
198
+
199
+ const onChunk = (t: string) => {
200
+ if (!wroteLabel) {
201
+ spinner?.stop();
202
+ if (sawActivity) err("\n");
203
+ err(paint(color, BOLD, "agent ›") + " ");
204
+ wroteLabel = true;
205
+ }
206
+ out(t); // response text (no color)
207
+ };
208
+
209
+ const onActivity =
210
+ options.activity !== false
211
+ ? (e: ActivityEvent) => {
212
+ const marker = activityMarker(e);
213
+ if (!marker || marker === lastMarker) return; // collapse consecutive repeats
214
+ lastMarker = marker;
215
+ if (!sawActivity) spinner?.stop(); // first activity replaces the spinner
216
+ sawActivity = true;
217
+ err(paint(color, DIM, `[${marker}]`) + " ");
218
+ }
219
+ : undefined;
220
+
221
+ busy = true;
222
+ try {
223
+ const result = await client.prompt(text, { onChunk, onActivity });
224
+ spinner?.stop();
225
+
226
+ if (wroteLabel) {
227
+ if (!result.text.endsWith("\n")) out("\n");
228
+ } else {
229
+ if (sawActivity) err("\n");
230
+ if (result.status === "completed") {
231
+ err(paint(color, DIM, "(no response — if this persists, the agent may need auth: try /login)") + "\n");
232
+ }
233
+ }
234
+ if (result.status !== "completed") {
235
+ err(paint(color, DIM, `(${result.status}: ${result.stopReason})`) + "\n");
236
+ }
237
+ } catch (e) {
238
+ spinner?.stop();
239
+ if (wroteLabel) out("\n");
240
+ err(paint(color, DIM, `(error: ${String(e)})`) + "\n");
241
+ } finally {
242
+ busy = false;
243
+ if (onData) {
244
+ process.stdin.removeListener("data", onData);
245
+ try {
246
+ process.stdin.setRawMode(false);
247
+ } catch {
248
+ /* ignore */
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }
254
+
255
+ // One line via a throwaway readline interface (interactive path).
256
+ type LineEvent = { type: "line"; value: string } | { type: "sigint" } | { type: "eof" };
257
+ function readOneLine(promptStr: string): Promise<LineEvent> {
258
+ return new Promise((resolve) => {
259
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
260
+ let done = false;
261
+ const finish = (ev: LineEvent) => {
262
+ if (done) return;
263
+ done = true;
264
+ rl.close();
265
+ resolve(ev);
266
+ };
267
+ rl.on("line", (l) => finish({ type: "line", value: l }));
268
+ rl.on("SIGINT", () => finish({ type: "sigint" }));
269
+ rl.on("close", () => finish({ type: "eof" }));
270
+ rl.setPrompt(promptStr);
271
+ rl.prompt();
272
+ });
273
+ }
274
+
275
+ interface Spinner {
276
+ stop(): void;
277
+ }
278
+
279
+ function startSpinner(color: boolean): Spinner {
280
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
281
+ let i = 0;
282
+ let stopped = false;
283
+ const render = () =>
284
+ process.stderr.write(
285
+ "\r" + paint(color, DIM, `${frames[i++ % frames.length]} working… (ESC to interrupt)`),
286
+ );
287
+ render();
288
+ const id = setInterval(render, 90);
289
+ return {
290
+ stop() {
291
+ // Idempotent: a second stop() must NOT re-emit the clear, or it would erase the
292
+ // response that was already written on this line after the first stop().
293
+ if (stopped) return;
294
+ stopped = true;
295
+ clearInterval(id);
296
+ process.stderr.write("\r\x1b[K"); // carriage return + clear spinner line
297
+ },
298
+ };
299
+ }
300
+
301
+ function activityMarker(e: ActivityEvent): string | null {
302
+ switch (e.kind) {
303
+ case "thinking":
304
+ return "thinking";
305
+ case "tool":
306
+ return `tool:${e.title ?? e.toolKind}`;
307
+ case "plan":
308
+ return "plan";
309
+ default:
310
+ return null; // tool_update is too noisy to surface
311
+ }
312
+ }
@@ -0,0 +1,125 @@
1
+ // SessionManager — catalog logic over a SessionStore. Owns the record lifecycle (upsert
2
+ // with timestamps) and merges OUR catalog with an agent's live `session/list` so the
3
+ // caller sees both: sessions we recorded (across adapters, surviving a broken agent list)
4
+ // AND sessions the agent reports (incl. ones created via the native CLI/bridge).
5
+ //
6
+ // It stores routing metadata only — never conversation content. See session-store.ts.
7
+
8
+ import type { SessionRecord, SessionStore } from "./session-store.ts";
9
+ import type { SessionListEntry } from "./types.ts";
10
+
11
+ /** A row in the merged session view. `source` says where it was seen. */
12
+ export interface MergedSession {
13
+ /** Our catalog id when cataloged, else the agent's sessionId. */
14
+ id: string;
15
+ agentSessionId: string | null;
16
+ adapter: string;
17
+ mode?: "normal" | "degraded";
18
+ cwd?: string;
19
+ title?: string;
20
+ updatedAt?: string;
21
+ source: "catalog" | "agent" | "both";
22
+ }
23
+
24
+ /** What `record()` accepts — timestamps are managed by the manager. */
25
+ export type SessionInput = Omit<SessionRecord, "createdAt" | "updatedAt">;
26
+
27
+ export class SessionManager {
28
+ constructor(private readonly store: SessionStore) {}
29
+
30
+ /** Upsert a record: preserves createdAt, bumps updatedAt. Returns the stored record. */
31
+ async record(input: SessionInput): Promise<SessionRecord> {
32
+ const now = new Date().toISOString();
33
+ const existing = await this.store.get(input.id);
34
+ const record: SessionRecord = {
35
+ ...input,
36
+ createdAt: existing?.createdAt ?? now,
37
+ updatedAt: now,
38
+ };
39
+ await this.store.save(record);
40
+ return record;
41
+ }
42
+
43
+ get(id: string): Promise<SessionRecord | null> {
44
+ return this.store.get(id);
45
+ }
46
+
47
+ delete(id: string): Promise<void> {
48
+ return this.store.delete(id);
49
+ }
50
+
51
+ /** Catalog records, newest first. */
52
+ async list(): Promise<SessionRecord[]> {
53
+ const records = await this.store.list();
54
+ return records.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
55
+ }
56
+
57
+ /**
58
+ * Merge the catalog with an agent's live list for `adapter`. The agent list only covers
59
+ * the connected adapter; catalog records span all adapters and are kept even when the
60
+ * agent omits them (other adapter, or a broken/empty list).
61
+ */
62
+ async listMerged(
63
+ agentEntries: SessionListEntry[],
64
+ adapter: string,
65
+ ): Promise<MergedSession[]> {
66
+ return mergeSessions(await this.store.list(), agentEntries, adapter);
67
+ }
68
+ }
69
+
70
+ /** Pure merge — exported for testing. */
71
+ export function mergeSessions(
72
+ catalog: SessionRecord[],
73
+ agentEntries: SessionListEntry[],
74
+ adapter: string,
75
+ ): MergedSession[] {
76
+ const byAgentId = new Map<string, SessionRecord>();
77
+ for (const r of catalog) if (r.agentSessionId) byAgentId.set(r.agentSessionId, r);
78
+
79
+ const out: MergedSession[] = [];
80
+ const claimed = new Set<string>(); // catalog ids already emitted via the agent list
81
+
82
+ for (const e of agentEntries) {
83
+ const rec = byAgentId.get(e.sessionId);
84
+ if (rec) {
85
+ claimed.add(rec.id);
86
+ out.push({
87
+ id: rec.id,
88
+ agentSessionId: e.sessionId,
89
+ adapter: rec.adapter,
90
+ mode: rec.mode,
91
+ cwd: e.cwd ?? rec.cwd,
92
+ title: e.title ?? rec.title,
93
+ updatedAt: e.updatedAt ?? rec.updatedAt,
94
+ source: "both",
95
+ });
96
+ } else {
97
+ // Reported by the agent but not in our catalog (made via native CLI/bridge).
98
+ out.push({
99
+ id: e.sessionId,
100
+ agentSessionId: e.sessionId,
101
+ adapter,
102
+ cwd: e.cwd,
103
+ title: e.title,
104
+ updatedAt: e.updatedAt,
105
+ source: "agent",
106
+ });
107
+ }
108
+ }
109
+
110
+ for (const r of catalog) {
111
+ if (claimed.has(r.id)) continue; // already emitted as "both"
112
+ out.push({
113
+ id: r.id,
114
+ agentSessionId: r.agentSessionId,
115
+ adapter: r.adapter,
116
+ mode: r.mode,
117
+ cwd: r.cwd,
118
+ title: r.title,
119
+ updatedAt: r.updatedAt,
120
+ source: "catalog",
121
+ });
122
+ }
123
+
124
+ return out.sort((a, b) => ((a.updatedAt ?? "") < (b.updatedAt ?? "") ? 1 : -1));
125
+ }
@@ -0,0 +1,96 @@
1
+ // Session catalog storage. The library is NOT the source of truth for conversation
2
+ // CONTENT (the agent persists that; loadSession replays it) — this is a routing catalog:
3
+ // which adapter/mode/cwd a session belongs to, keyed by OUR stable id. That's the part
4
+ // the agent can't tell us, and it survives a broken agent `session/list` (e.g. kimi).
5
+ //
6
+ // `SessionStore` is an interface so consumers (the orchestration hub) can back it with
7
+ // their own database instead of files — same injection pattern as Logger. The library
8
+ // ships FileSessionStore as the default. See SPEC.md "Sessions".
9
+
10
+ import { readdir, readFile, writeFile, unlink, mkdir } from "node:fs/promises";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
13
+
14
+ export interface SessionRecord {
15
+ /** OUR stable catalog id (a uuid). Decoupled from the agent's sessionId on purpose. */
16
+ id: string;
17
+ /**
18
+ * The agent's protocol sessionId. Null in degraded mode (no protocol session), and it
19
+ * CHANGES on mode-swap (the pty session ≠ the ACP session). Kept as a mutable field so
20
+ * a future portable conversation can span several agent sessions without re-keying.
21
+ */
22
+ agentSessionId: string | null;
23
+ /** Which adapter this session belongs to — the routing the agent's own list can't give. */
24
+ adapter: string;
25
+ mode: "normal" | "degraded";
26
+ cwd?: string;
27
+ title?: string;
28
+ createdAt: string;
29
+ updatedAt: string;
30
+ // (transcript storage slots in here later without breaking the schema.)
31
+ }
32
+
33
+ export interface SessionStore {
34
+ save(record: SessionRecord): Promise<void>;
35
+ get(id: string): Promise<SessionRecord | null>;
36
+ list(): Promise<SessionRecord[]>;
37
+ delete(id: string): Promise<void>;
38
+ }
39
+
40
+ /** Default location for the file store. Overridable; the hub injects its own store. */
41
+ export function defaultSessionsDir(): string {
42
+ return join(homedir(), ".acp-lib", "sessions");
43
+ }
44
+
45
+ /** File-per-session catalog under a directory. One `<id>.json` per record. */
46
+ export class FileSessionStore implements SessionStore {
47
+ private readonly dir: string;
48
+
49
+ constructor(dir: string = defaultSessionsDir()) {
50
+ this.dir = dir;
51
+ }
52
+
53
+ async save(record: SessionRecord): Promise<void> {
54
+ await mkdir(this.dir, { recursive: true });
55
+ await writeFile(this.path(record.id), JSON.stringify(record, null, 2), "utf8");
56
+ }
57
+
58
+ async get(id: string): Promise<SessionRecord | null> {
59
+ try {
60
+ return JSON.parse(await readFile(this.path(id), "utf8")) as SessionRecord;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ async list(): Promise<SessionRecord[]> {
67
+ let names: string[];
68
+ try {
69
+ names = await readdir(this.dir);
70
+ } catch {
71
+ return [];
72
+ }
73
+ const records: SessionRecord[] = [];
74
+ for (const name of names) {
75
+ if (!name.endsWith(".json")) continue;
76
+ try {
77
+ records.push(JSON.parse(await readFile(join(this.dir, name), "utf8")) as SessionRecord);
78
+ } catch {
79
+ /* skip malformed */
80
+ }
81
+ }
82
+ return records;
83
+ }
84
+
85
+ async delete(id: string): Promise<void> {
86
+ try {
87
+ await unlink(this.path(id));
88
+ } catch {
89
+ /* already gone */
90
+ }
91
+ }
92
+
93
+ private path(id: string): string {
94
+ return join(this.dir, `${encodeURIComponent(id)}.json`);
95
+ }
96
+ }