@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,304 @@
1
+ // PtyClient — degraded-mode AgentClient. Drives an agent's INTERACTIVE CLI inside a pty
2
+ // (via PtyTransport) and scrapes the screen back into the same prompt()/onChunk contract
3
+ // AcpClient exposes, so the REPL and controller work against it unchanged.
4
+ //
5
+ // It has almost no INPUT surface: no capabilities, no sessions, no permission gating —
6
+ // those genuinely don't exist when you're screen-scraping. See SPEC.md "Degraded mode".
7
+ //
8
+ // Pipeline (SPEC.md "The parsing pipeline"):
9
+ // raw pty bytes → EmulatorScreen (vt grid) → settle on idle → extractReply → PromptResult
10
+ // `extractReply` is the deterministic default; an injected `parser` (ScreenParser/SML)
11
+ // can replace it for messier TUIs without touching the transport/turn machinery.
12
+
13
+ import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "../agent-client.ts";
14
+ import type { Adapter } from "../adapters.ts";
15
+ import { buildPtyCommand } from "../adapters.ts";
16
+ import type { ScreenParser } from "../parser/types.ts";
17
+ import type { PromptResult, PromptHandlers, Attachment } from "../types.ts";
18
+ import { noopLogger, type Logger } from "../logger.ts";
19
+ import { NotConnectedError } from "../errors.ts";
20
+ import { PtyTransport } from "./pty-transport.ts";
21
+ import { EmulatorScreen, compactLines } from "./emulator.ts";
22
+ import { extractReply } from "./extract.ts";
23
+
24
+ const ETX = "\x03"; // Ctrl-C
25
+ const ESC = "\x1b";
26
+
27
+ export interface PtyClientOptions {
28
+ adapter: Adapter;
29
+ execPrefix?: string[];
30
+ env?: Record<string, string>;
31
+ cwd?: string;
32
+ /** Optional smart parser (SML/heuristic). Absent → deterministic extractReply. */
33
+ parser?: ScreenParser;
34
+ /** ms of screen stability that counts as "settled" / turn complete. Default 800. */
35
+ settleMs?: number;
36
+ /**
37
+ * ms to wait after typing the prompt before sending Enter. TUIs (e.g. codex) treat a
38
+ * single `text+Enter` write as a paste and DON'T submit — Enter must be a separate
39
+ * keypress after the text registers. Default 150.
40
+ */
41
+ submitDelayMs?: number;
42
+ cols?: number;
43
+ rows?: number;
44
+ logger?: Logger;
45
+ }
46
+
47
+ interface Turn {
48
+ sent: string;
49
+ preLines: string[];
50
+ handlers?: PromptHandlers;
51
+ cancelled: boolean;
52
+ resolve: (r: PromptResult) => void;
53
+ settle: ReturnType<typeof setTimeout> | null;
54
+ }
55
+
56
+ export class PtyClient implements AgentClient, Bridgeable {
57
+ private transport: PtyTransport | null = null;
58
+ private screen: EmulatorScreen | null = null;
59
+ private turn: Turn | null = null;
60
+ // Raw pty-output subscribers (used by bridge() to mirror the pty to the user's screen).
61
+ private rawListeners = new Set<(data: string) => void>();
62
+ private readonly settleMs: number;
63
+ private readonly submitDelayMs: number;
64
+ private readonly cols: number;
65
+ private readonly rows: number;
66
+ private readonly log: Logger;
67
+
68
+ constructor(private opts: PtyClientOptions) {
69
+ this.settleMs = opts.settleMs ?? 800;
70
+ this.submitDelayMs = opts.submitDelayMs ?? 150;
71
+ this.cols = opts.cols ?? 100;
72
+ this.rows = opts.rows ?? 30;
73
+ this.log = opts.logger ?? noopLogger;
74
+ }
75
+
76
+ get isConnected(): boolean {
77
+ return this.transport !== null;
78
+ }
79
+
80
+ /** Spawn the interactive CLI and wait for its banner/prompt to settle. */
81
+ async start(): Promise<void> {
82
+ if (this.transport) return;
83
+ const command = buildPtyCommand(this.opts.adapter, this.opts.execPrefix);
84
+ this.log.info("pty_connect", { command });
85
+
86
+ this.screen = new EmulatorScreen({ cols: this.cols, rows: this.rows });
87
+ const transport = new PtyTransport({
88
+ command,
89
+ cwd: this.opts.cwd,
90
+ env: this.opts.env,
91
+ cols: this.cols,
92
+ rows: this.rows,
93
+ onData: (data) => this.onData(data),
94
+ onExit: (code) => {
95
+ this.transport = null;
96
+ this.log.warn("pty_exit", { code });
97
+ void this.finishTurn("end_turn");
98
+ },
99
+ });
100
+ await transport.start();
101
+ this.transport = transport;
102
+
103
+ // Drain the startup banner so the first prompt's response isn't polluted by it.
104
+ await this.waitIdle();
105
+ this.log.debug("pty_ready", {});
106
+ }
107
+
108
+ prompt(
109
+ text: string,
110
+ handlers?: PromptHandlers,
111
+ _attachments?: Attachment[],
112
+ ): Promise<PromptResult> {
113
+ if (!this.transport || !this.screen) throw new NotConnectedError("PtyClient is not started");
114
+ if (this.turn) throw new Error("PtyClient is busy with another turn");
115
+
116
+ return new Promise<PromptResult>((resolve) => {
117
+ void (async () => {
118
+ const preLines = compactLines(await this.screen!.snapshot());
119
+ this.turn = { sent: text, preLines, handlers, cancelled: false, resolve, settle: null };
120
+ this.log.debug("pty_prompt", { chars: text.length });
121
+ // Type the text, then send Enter as a SEPARATE keypress after a short delay —
122
+ // a single text+Enter write looks like a paste to TUIs and won't submit.
123
+ this.transport!.write(text);
124
+ this.armSettle();
125
+ setTimeout(() => {
126
+ if (this.turn) {
127
+ this.transport?.write("\r");
128
+ this.armSettle();
129
+ }
130
+ }, this.submitDelayMs);
131
+ })();
132
+ });
133
+ }
134
+
135
+ interrupt(_options?: InterruptOptions): void {
136
+ if (!this.turn) return;
137
+ this.turn.cancelled = true;
138
+ // ESC first (most TUIs treat it as cancel), then Ctrl-C as a fallback.
139
+ this.transport?.write(ESC);
140
+ this.transport?.write(ETX);
141
+ this.log.debug("pty_interrupt", {});
142
+ }
143
+
144
+ async stop(): Promise<void> {
145
+ const t = this.transport;
146
+ this.transport = null;
147
+ await this.finishTurn("cancelled");
148
+ if (t) await t.stop();
149
+ this.screen?.dispose();
150
+ this.screen = null;
151
+ this.log.info("pty_stopped", {});
152
+ }
153
+
154
+ // --- PTY-only surface (not on AgentClient) ------------------------------------
155
+
156
+ /** The current emulated screen as text (what a human would see). */
157
+ async readScreen(): Promise<string> {
158
+ if (!this.screen) return "";
159
+ return compactLines(await this.screen.snapshot()).join("\n");
160
+ }
161
+
162
+ /** Escape hatch: send raw keys (ESC, arrows, slash commands) into the pty. */
163
+ sendKeys(raw: string): void {
164
+ this.transport?.write(raw);
165
+ }
166
+
167
+ /** Resize the pty window — TUIs redraw to fit, which reduces scrape garbage. */
168
+ resize(cols: number, rows: number): void {
169
+ this.transport?.resize(cols, rows);
170
+ this.screen?.resize(cols, rows);
171
+ }
172
+
173
+ // --- internals ----------------------------------------------------------------
174
+
175
+ private onData(data: string): void {
176
+ this.screen?.write(data);
177
+ for (const listener of this.rawListeners) listener(data);
178
+ if (this.turn) this.armSettle();
179
+ }
180
+
181
+ /**
182
+ * Hand the pty directly to the user: mirror its output to `output` and forward
183
+ * keystrokes from `input` until the exit byte (default Ctrl-], 0x1d). For tty-auth
184
+ * (login) and as an escape hatch when scraping can't read a TUI (e.g. codex modals).
185
+ */
186
+ async bridge(options: BridgeOptions = {}): Promise<void> {
187
+ if (!this.transport) throw new NotConnectedError("PtyClient is not started");
188
+ if (this.turn) throw new Error("cannot bridge while a turn is in flight");
189
+
190
+ const input = (options.input ?? process.stdin) as NodeJS.ReadStream & {
191
+ setRawMode?: (raw: boolean) => void;
192
+ isRaw?: boolean;
193
+ };
194
+ const output = options.output ?? process.stdout;
195
+ const exitBytes = new Set(options.exitBytes ?? [0x1d, 0x03]); // Ctrl-], Ctrl-C
196
+ const status = options.onStatus ?? ((m: string) => void process.stderr.write(m));
197
+ const label = this.opts.adapter.displayName ?? "agent";
198
+
199
+ // Size the pty to the user's REAL terminal so the TUI renders aligned (a fixed
200
+ // 100×30 pty mis-wraps in a different terminal), then the SIGWINCH triggers a clean
201
+ // full repaint. We do NOT dump the emulated screen — for full TUIs that overlaps the
202
+ // live repaint and garbles it (Claude Code).
203
+ const term = output as unknown as {
204
+ columns?: number;
205
+ rows?: number;
206
+ on?: (ev: string, cb: () => void) => void;
207
+ off?: (ev: string, cb: () => void) => void;
208
+ };
209
+ output.write("\x1b[2J\x1b[H"); // clear; the repaint below redraws the TUI fresh
210
+ this.resize(term.columns ?? this.cols, term.rows ?? this.rows);
211
+ status(`— bridge: driving ${label} directly · Ctrl-] or Ctrl-C to return —\r\n`);
212
+
213
+ const mirror = (d: string) => void output.write(d);
214
+ this.rawListeners.add(mirror);
215
+ // Keep the TUI fitting if the user resizes the terminal while bridged.
216
+ const onResize = () => this.resize(term.columns ?? this.cols, term.rows ?? this.rows);
217
+ term.on?.("resize", onResize);
218
+
219
+ const wasRaw = Boolean(input.isRaw);
220
+ try {
221
+ input.setRawMode?.(true);
222
+ } catch {
223
+ /* not a tty */
224
+ }
225
+ input.resume();
226
+
227
+ await new Promise<void>((resolve) => {
228
+ const onInput = (buf: Buffer) => {
229
+ // Forward everything up to (but not including) the first exit byte, then stop.
230
+ let i = 0;
231
+ for (; i < buf.length; i++) if (exitBytes.has(buf[i]!)) break;
232
+ if (i > 0) this.transport?.writeBytes(new Uint8Array(buf.subarray(0, i)));
233
+ if (i < buf.length) {
234
+ input.off("data", onInput);
235
+ resolve();
236
+ return;
237
+ }
238
+ };
239
+ input.on("data", onInput);
240
+ });
241
+
242
+ term.off?.("resize", onResize);
243
+ this.rawListeners.delete(mirror);
244
+ try {
245
+ if (!wasRaw) input.setRawMode?.(false);
246
+ } catch {
247
+ /* ignore */
248
+ }
249
+ input.pause();
250
+ // Clear the agent's TUI so the REPL returns to a clean screen.
251
+ output.write("\x1b[2J\x1b[H");
252
+ status(`— bridge closed —\r\n`);
253
+ }
254
+
255
+ private armSettle(): void {
256
+ const turn = this.turn;
257
+ if (!turn) return;
258
+ if (turn.settle) clearTimeout(turn.settle);
259
+ turn.settle = setTimeout(() => void this.finishTurn("end_turn"), this.settleMs);
260
+ }
261
+
262
+ private async finishTurn(stopReason: string): Promise<void> {
263
+ const turn = this.turn;
264
+ if (!turn) return;
265
+ this.turn = null;
266
+ if (turn.settle) clearTimeout(turn.settle);
267
+
268
+ let text = "";
269
+ if (this.screen) {
270
+ const post = compactLines(await this.screen.snapshot());
271
+ if (this.opts.parser) {
272
+ const parsed = await this.opts.parser.parse(post.join("\n"), "result");
273
+ text = parsed && "text" in parsed ? String(parsed.text ?? "") : "";
274
+ } else {
275
+ text = extractReply(post, turn.sent, turn.preLines);
276
+ }
277
+ }
278
+
279
+ const status = turn.cancelled ? "cancelled" : "completed";
280
+ if (text) turn.handlers?.onChunk?.(text);
281
+ this.log[text.length === 0 && !turn.cancelled ? "warn" : "info"]("pty_turn_end", {
282
+ status,
283
+ chars: text.length,
284
+ });
285
+ turn.resolve({ text, stopReason, status, usage: null });
286
+ }
287
+
288
+ /** Resolve once the screen has been idle for settleMs (used to drain the banner). */
289
+ private waitIdle(): Promise<void> {
290
+ return new Promise((resolve) => {
291
+ let lastLen = -1;
292
+ const tick = async () => {
293
+ const len = this.screen ? (await this.screen.snapshot()).join("").length : 0;
294
+ if (len === lastLen) {
295
+ resolve();
296
+ return;
297
+ }
298
+ lastLen = len;
299
+ setTimeout(tick, this.settleMs);
300
+ };
301
+ setTimeout(tick, this.settleMs);
302
+ });
303
+ }
304
+ }
@@ -0,0 +1,130 @@
1
+ /// <reference types="bun" />
2
+ // The ONLY module in degraded mode that spawns a process. Uses Bun's NATIVE pseudo-
3
+ // terminal API (Bun.spawn({ terminal }), Bun ≥ 1.3.5) — no node-pty (broken under Bun)
4
+ // and no external `script` binary. The agent's interactive CLI runs in a real pty, and
5
+ // `terminal.write/resize` drive it. See .res/test.md "degraded mode PTY".
6
+ //
7
+ // Layout mirrors transport/acp-transport.ts: one class, start/stop, a write path, and
8
+ // event callbacks. Everything above stays pty-plumbing-agnostic.
9
+
10
+ import { ProcessCrashError } from "../errors.ts";
11
+
12
+ export interface PtyTransportOptions {
13
+ /** The interactive command (argv) to run inside the pty, e.g. ["codex"] (exec-prefixed). */
14
+ command: string[];
15
+ cwd?: string;
16
+ env?: Record<string, string>;
17
+ cols?: number;
18
+ rows?: number;
19
+
20
+ /** A chunk of raw terminal bytes (decoded to string, ANSI still embedded) arrived. */
21
+ onData?: (data: string) => void;
22
+ /** The pty process exited. */
23
+ onExit?: (code: number | null) => void;
24
+ }
25
+
26
+ /** Minimal shape of Bun's native terminal handle (not yet in @types/bun). */
27
+ interface BunTerminal {
28
+ write(data: string | Uint8Array): void;
29
+ resize(cols: number, rows: number): void;
30
+ close(): void;
31
+ unref(): void;
32
+ }
33
+
34
+ export class PtyTransport {
35
+ private proc: ReturnType<typeof Bun.spawn> | null = null;
36
+ private terminal: BunTerminal | null = null;
37
+ private stopping = false;
38
+
39
+ constructor(private opts: PtyTransportOptions) {}
40
+
41
+ async start(): Promise<void> {
42
+ if (this.proc) return;
43
+ const dec = new TextDecoder();
44
+
45
+ const proc = Bun.spawn(this.opts.command, {
46
+ cwd: this.opts.cwd,
47
+ env: {
48
+ ...process.env,
49
+ ...(this.opts.env ?? {}),
50
+ TERM: this.opts.env?.TERM ?? "xterm-color",
51
+ },
52
+ terminal: {
53
+ cols: this.opts.cols ?? 80,
54
+ rows: this.opts.rows ?? 24,
55
+ data: (_term: unknown, data: Uint8Array) => {
56
+ const text = dec.decode(data, { stream: true });
57
+ if (text) this.opts.onData?.(text);
58
+ },
59
+ },
60
+ } as Parameters<typeof Bun.spawn>[1]);
61
+
62
+ this.proc = proc;
63
+ this.terminal = (proc as unknown as { terminal: BunTerminal }).terminal ?? null;
64
+
65
+ proc.exited
66
+ .then((code) => {
67
+ if (this.proc === proc && !this.stopping) {
68
+ this.proc = null;
69
+ this.terminal = null;
70
+ this.opts.onExit?.(code ?? null);
71
+ }
72
+ })
73
+ .catch(() => {});
74
+ }
75
+
76
+ /** Write to the pty (keystrokes, prompt text, control chars). */
77
+ write(data: string): void {
78
+ if (!this.terminal) throw new ProcessCrashError(null, "pty transport not started");
79
+ this.terminal.write(data);
80
+ }
81
+
82
+ /** Write raw bytes verbatim — used by the bridge to forward keystrokes unmangled. */
83
+ writeBytes(data: Uint8Array): void {
84
+ if (!this.terminal) throw new ProcessCrashError(null, "pty transport not started");
85
+ this.terminal.write(data);
86
+ }
87
+
88
+ /** Resize the pty window (TUIs redraw to fit; correct dims reduce scrape garbage). */
89
+ resize(cols: number, rows: number): void {
90
+ this.terminal?.resize(cols, rows);
91
+ }
92
+
93
+ async stop(): Promise<void> {
94
+ this.stopping = true;
95
+ const proc = this.proc;
96
+ const terminal = this.terminal;
97
+ this.proc = null;
98
+ this.terminal = null;
99
+ try {
100
+ proc?.kill("SIGTERM");
101
+ } catch {
102
+ /* already exited */
103
+ }
104
+ // The native pty handle keeps Bun's event loop alive until closed — without this the
105
+ // process hangs after the child is killed. close() also releases the pty master fd.
106
+ try {
107
+ terminal?.close();
108
+ } catch {
109
+ /* already closed */
110
+ }
111
+ // SIGKILL after a short grace in case the child ignores SIGTERM (TUIs in raw mode).
112
+ if (proc) {
113
+ const killed = await Promise.race([
114
+ proc.exited.then(() => true),
115
+ new Promise<boolean>((r) => setTimeout(() => r(false), 500)),
116
+ ]);
117
+ if (!killed) {
118
+ try {
119
+ proc.kill("SIGKILL");
120
+ } catch {
121
+ /* gone */
122
+ }
123
+ }
124
+ }
125
+ }
126
+
127
+ get running(): boolean {
128
+ return this.proc !== null;
129
+ }
130
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,28 @@
1
+ // Library error types. Kept minimal — surface protocol facts, don't over-classify.
2
+
3
+ /** The agent process exited unexpectedly (not via stop()). */
4
+ export class ProcessCrashError extends Error {
5
+ constructor(
6
+ public readonly code: number | null,
7
+ message?: string,
8
+ ) {
9
+ super(message ?? `ACP process exited unexpectedly (${code ?? "killed"})`);
10
+ this.name = "ProcessCrashError";
11
+ }
12
+ }
13
+
14
+ /** A method was used before connect() established the connection. */
15
+ export class NotConnectedError extends Error {
16
+ constructor(message = "AcpClient is not connected — call connect() first") {
17
+ super(message);
18
+ this.name = "NotConnectedError";
19
+ }
20
+ }
21
+
22
+ /** An operation timed out. */
23
+ export class TimeoutError extends Error {
24
+ constructor(label: string, ms: number) {
25
+ super(`${label} timed out after ${Math.round(ms / 1000)}s`);
26
+ this.name = "TimeoutError";
27
+ }
28
+ }
package/src/index.ts ADDED
@@ -0,0 +1,81 @@
1
+ // PUBLIC SURFACE of the core ACP library — re-exports only.
2
+ // NOTE: this barrel must NOT reference ./degraded or ./parser. Those are separate
3
+ // subpath exports (acp-lib/degraded, acp-lib/parser) so importing the core never pulls
4
+ // in node-pty / ollama. See SPEC.md "opt-in by design".
5
+
6
+ export { AcpClient } from "./client.ts";
7
+ export type {
8
+ AcpClientConfig,
9
+ StartSessionOptions,
10
+ ListSessionsOptions,
11
+ SwitchSessionOptions,
12
+ ConnectResult,
13
+ } from "./client.ts";
14
+
15
+ export {
16
+ AgentController,
17
+ parseConfigValue,
18
+ parseBoolean,
19
+ parseJsonOrString,
20
+ formatConfigValue,
21
+ } from "./controller.ts";
22
+ export type {
23
+ AgentControllerConfig,
24
+ AgentMode,
25
+ ControllerCommand,
26
+ ControllerCommandId,
27
+ ConfigValueParseResult,
28
+ SetConfigFromStringResult,
29
+ } from "./controller.ts";
30
+
31
+ export { AgentSession } from "./agent-session.ts";
32
+ export type { AgentSessionConfig } from "./agent-session.ts";
33
+
34
+ export type {
35
+ AgentClient,
36
+ InterruptOptions,
37
+ Bridgeable,
38
+ BridgeOptions,
39
+ } from "./agent-client.ts";
40
+
41
+ export { ADAPTERS, buildSpawnCommand } from "./adapters.ts";
42
+ export type { Adapter, AdapterPreset } from "./adapters.ts";
43
+
44
+ export type {
45
+ Capabilities,
46
+ ClientCapabilities,
47
+ AgentCapabilities,
48
+ AuthMethod,
49
+ } from "./capabilities.ts";
50
+ export type {
51
+ ConfigOption,
52
+ ConfigOptions,
53
+ ConfigOptionChoice,
54
+ } from "./config-options.ts";
55
+
56
+ export {
57
+ FileSessionStore,
58
+ defaultSessionsDir,
59
+ } from "./session-store.ts";
60
+ export type { SessionStore, SessionRecord } from "./session-store.ts";
61
+ export { SessionManager, mergeSessions } from "./session-manager.ts";
62
+ export type { MergedSession, SessionInput } from "./session-manager.ts";
63
+
64
+ export { ProcessCrashError, NotConnectedError, TimeoutError } from "./errors.ts";
65
+
66
+ export { noopLogger, createConsoleLogger } from "./logger.ts";
67
+ export type { Logger, LogLevel, ConsoleLoggerOptions } from "./logger.ts";
68
+
69
+ export type {
70
+ PromptResult,
71
+ PromptHandlers,
72
+ ActivityEvent,
73
+ PlanEntry,
74
+ PermissionRequest,
75
+ PermissionOutcome,
76
+ Usage,
77
+ Attachment,
78
+ SessionListEntry,
79
+ SessionListPage,
80
+ AgentCommand,
81
+ } from "./types.ts";
package/src/logger.ts ADDED
@@ -0,0 +1,65 @@
1
+ // Logger — an injected diagnostics sink. The library NEVER calls console.* directly;
2
+ // it logs through whatever the caller provides (or stays silent). This keeps the core
3
+ // quiet by default, which matters when it's embedded — e.g. recursed into an
4
+ // agent-as-tool. See SPEC.md "Core principles" (clean & embeddable).
5
+ //
6
+ // Structured by design: an `event` name + a `meta` bag, so callers can route to pino,
7
+ // JSON logs, etc. instead of parsing prose.
8
+
9
+ export type LogLevel = "debug" | "info" | "warn" | "error";
10
+
11
+ export interface Logger {
12
+ debug(event: string, meta?: Record<string, unknown>): void;
13
+ info(event: string, meta?: Record<string, unknown>): void;
14
+ warn(event: string, meta?: Record<string, unknown>): void;
15
+ error(event: string, meta?: Record<string, unknown>): void;
16
+ }
17
+
18
+ /** Default sink — the library is silent unless given a real logger. */
19
+ export const noopLogger: Logger = {
20
+ debug() {},
21
+ info() {},
22
+ warn() {},
23
+ error() {},
24
+ };
25
+
26
+ const LEVEL_ORDER: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 };
27
+
28
+ const COLOR: Record<LogLevel, string> = {
29
+ debug: "\x1b[90m", // grey
30
+ info: "\x1b[36m", // cyan
31
+ warn: "\x1b[33m", // yellow
32
+ error: "\x1b[31m", // red
33
+ };
34
+ const RESET = "\x1b[0m";
35
+
36
+ export interface ConsoleLoggerOptions {
37
+ /** Minimum level to emit. Default "info". */
38
+ minLevel?: LogLevel;
39
+ /** Colorize output. Default: true when stderr is a TTY. */
40
+ color?: boolean;
41
+ }
42
+
43
+ /**
44
+ * A convenience console logger that writes diagnostics to STDERR (so stdout stays
45
+ * reserved for real data, e.g. response text). Opt-in — the library never installs it.
46
+ */
47
+ export function createConsoleLogger(options: ConsoleLoggerOptions = {}): Logger {
48
+ const min = LEVEL_ORDER[options.minLevel ?? "info"];
49
+ const color = options.color ?? Boolean((process.stderr as any)?.isTTY);
50
+
51
+ const emit = (level: LogLevel) => (event: string, meta?: Record<string, unknown>) => {
52
+ if (LEVEL_ORDER[level] < min) return;
53
+ const tag = color ? `${COLOR[level]}${level}${RESET}` : level;
54
+ const rest = meta && Object.keys(meta).length ? ` ${fmtMeta(meta)}` : "";
55
+ process.stderr.write(`${tag} ${event}${rest}\n`);
56
+ };
57
+
58
+ return { debug: emit("debug"), info: emit("info"), warn: emit("warn"), error: emit("error") };
59
+ }
60
+
61
+ function fmtMeta(meta: Record<string, unknown>): string {
62
+ return Object.entries(meta)
63
+ .map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`)
64
+ .join(" ");
65
+ }
@@ -0,0 +1,4 @@
1
+ // Subpath barrel: acp-lib/parser. The SML backend, isolated from the core.
2
+ export type { ScreenParser, ParseTarget } from "./types.ts";
3
+ export { OllamaParser } from "./ollama.ts";
4
+ export type { OllamaParserOptions } from "./ollama.ts";
@@ -0,0 +1,26 @@
1
+ // OllamaParser — a ScreenParser backed by a local ollama-served small model.
2
+ // DEFERRED / skeleton. Isolated here so degraded mode depends only on the ScreenParser
3
+ // interface, never on ollama directly. See SPEC.md "The SML".
4
+
5
+ import type { ScreenParser, ParseTarget } from "./types.ts";
6
+ import type { ActivityEvent, PromptResult } from "../types.ts";
7
+
8
+ export interface OllamaParserOptions {
9
+ /** ollama model tag, e.g. "qwen2.5:0.5b". */
10
+ model: string;
11
+ /** ollama HTTP endpoint. Default http://127.0.0.1:11434. */
12
+ host?: string;
13
+ }
14
+
15
+ export class OllamaParser implements ScreenParser {
16
+ constructor(private opts: OllamaParserOptions) {}
17
+
18
+ async parse(
19
+ _cleanText: string,
20
+ _target: ParseTarget,
21
+ ): Promise<ActivityEvent | PromptResult | null> {
22
+ // TODO: POST to `${host}/api/chat` with a schema-constrained ("format": <json schema>)
23
+ // request so the small model can only emit a valid ActivityEvent / PromptResult.
24
+ throw new Error("OllamaParser.parse is not implemented yet (deferred)");
25
+ }
26
+ }
@@ -0,0 +1,20 @@
1
+ // ScreenParser — the abstraction degraded mode depends on. Pure, ZERO deps.
2
+ // Degraded mode never hardcodes ollama; it takes a ScreenParser by injection. ollama is
3
+ // just one implementation (./ollama.ts). See SPEC.md "The SML — isolate it".
4
+
5
+ import type { ActivityEvent, PromptResult } from "../types.ts";
6
+
7
+ /** What we want extracted from a settled block of clean terminal text. */
8
+ export type ParseTarget = "activity" | "result";
9
+
10
+ export interface ScreenParser {
11
+ /**
12
+ * Turn clean (de-duped, ANSI-free) terminal text into structured output. The parser
13
+ * does NOT interpret or summarize — only parses — so a very small model suffices.
14
+ * Implementations SHOULD constrain decoding to a schema so only valid output is emitted.
15
+ */
16
+ parse(
17
+ cleanText: string,
18
+ target: ParseTarget,
19
+ ): Promise<ActivityEvent | PromptResult | null>;
20
+ }
@@ -0,0 +1,15 @@
1
+ // Minimal ANSI helpers shared by the reusable terminal UI and CLI wiring.
2
+ export const DIM = "\x1b[90m";
3
+ export const BOLD = "\x1b[1m";
4
+ export const CYAN = "\x1b[36m";
5
+ export const RESET = "\x1b[0m";
6
+
7
+ /** Whether to emit color for a stream: a TTY and NO_COLOR not set (https://no-color.org). */
8
+ export function colorEnabled(stream: { isTTY?: boolean }): boolean {
9
+ return Boolean(stream.isTTY) && process.env.NO_COLOR === undefined;
10
+ }
11
+
12
+ /** Wrap text in an ANSI code when enabled; otherwise return it untouched. */
13
+ export function paint(enabled: boolean, code: string, text: string): string {
14
+ return enabled ? `${code}${text}${RESET}` : text;
15
+ }