@qlairoslabs/acp-client 0.1.2 → 0.1.5

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 CHANGED
@@ -134,6 +134,31 @@ for (const s of await session.listSessions()) {
134
134
  await session.stop();
135
135
  ```
136
136
 
137
+ ### Optional chat transcript
138
+
139
+ Pass `transcriptPath` or `transcriptDir` to `AgentSession` to append a lightweight JSONL
140
+ chat transcript that can be read later without starting the agent. `transcriptPath` is an
141
+ exact file path chosen by the caller; `transcriptDir` lets the library write
142
+ `<agentSessionId>.jsonl` inside that directory. Supplying both is a config error.
143
+
144
+ The transcript stores user messages and final assistant replies only; tool calls,
145
+ thinking, plans, and raw protocol replay remain in the harness session.
146
+
147
+ ```ts
148
+ import { AgentSession, ADAPTERS, readTranscript } from "@qlairoslabs/acp-client";
149
+
150
+ const session = await AgentSession.create({
151
+ adapter: ADAPTERS.codex,
152
+ adapterId: "codex",
153
+ agentSessionId: "conv-123",
154
+ transcriptDir: "/absolute/path/to/chats",
155
+ });
156
+
157
+ await session.prompt("Summarize the repo.");
158
+
159
+ const messages = await readTranscript("/absolute/path/to/chats/conv-123.jsonl");
160
+ ```
161
+
137
162
  ### Interactive REPL
138
163
 
139
164
  The REPL and its slash-commands (`/help`, `/new`, `/sessions`, `/load`, `/config`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.1.2",
3
+ "version": "0.1.5",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -11,13 +11,15 @@
11
11
 
12
12
  import { AgentController, type AgentMode } from "./controller.ts";
13
13
  import type * as schema from "@agentclientprotocol/sdk";
14
+ import { join } from "node:path";
14
15
  import type { Adapter } from "./adapters.ts";
15
16
  import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
16
17
  import type { Capabilities } from "./capabilities.ts";
17
18
  import type { ConfigOptions } from "./config-options.ts";
18
19
  import type { ConnectResult } from "./client.ts";
19
- import type { Logger } from "./logger.ts";
20
+ import { noopLogger, type Logger } from "./logger.ts";
20
21
  import type { SessionManager, MergedSession } from "./session-manager.ts";
22
+ import { appendTranscriptLine, type TranscriptLine } from "./transcript.ts";
21
23
  import type {
22
24
  AgentCommand,
23
25
  Attachment,
@@ -26,6 +28,14 @@ import type {
26
28
  SessionListEntry,
27
29
  } from "./types.ts";
28
30
 
31
+ interface QueueItem {
32
+ text: string;
33
+ handlers?: PromptHandlers;
34
+ attachments?: Attachment[];
35
+ resolve: (r: PromptResult) => void;
36
+ reject: (e: unknown) => void;
37
+ }
38
+
29
39
  export interface AgentSessionConfig {
30
40
  /** The resolved adapter this conversation talks to. */
31
41
  adapter: Adapter;
@@ -43,6 +53,10 @@ export interface AgentSessionConfig {
43
53
  logger?: Logger;
44
54
  /** Optional catalog. When present, the session records itself here. */
45
55
  sessions?: SessionManager;
56
+ /** Absolute path to an append-only transcript file. Omitted means no transcript. */
57
+ transcriptPath?: string;
58
+ /** Directory for a library-named transcript file: `<agentSessionId>.jsonl`. */
59
+ transcriptDir?: string;
46
60
  /** Our stable AgentSession id. Minted if omitted; pass a record's agentSessionId to resume. */
47
61
  agentSessionId?: string;
48
62
  /** ACP/harness session to load on start (resume an existing provider conversation). */
@@ -57,15 +71,29 @@ export class AgentSession implements AgentClient, Bridgeable {
57
71
 
58
72
  private readonly controller: AgentController;
59
73
  private readonly sessions?: SessionManager;
74
+ private readonly transcriptPath?: string;
75
+ private readonly log: Logger;
76
+ private transcriptWrite: Promise<void> = Promise.resolve();
77
+ private queue: QueueItem[] = [];
78
+ private pumping = false;
60
79
  private _internalSessionId: string | null;
61
80
  private _mode: AgentMode;
62
81
  private _cwd?: string;
63
82
  private _title?: string;
64
83
 
65
84
  private constructor(config: AgentSessionConfig) {
85
+ if (config.transcriptPath && config.transcriptDir) {
86
+ throw new Error("AgentSessionConfig cannot specify both transcriptPath and transcriptDir");
87
+ }
66
88
  this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
67
89
  this.adapterId = config.adapterId;
68
90
  this.sessions = config.sessions;
91
+ this.transcriptPath =
92
+ config.transcriptPath ??
93
+ (config.transcriptDir
94
+ ? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
95
+ : undefined);
96
+ this.log = config.logger ?? noopLogger;
69
97
  this._mode = config.mode ?? "normal";
70
98
  this._cwd = config.cwd;
71
99
  this._title = config.title;
@@ -100,6 +128,14 @@ export class AgentSession implements AgentClient, Bridgeable {
100
128
  const result = await this.controller.start();
101
129
  this._internalSessionId = result.sessionId || this._internalSessionId;
102
130
  await this.persist();
131
+ await this.appendTranscript({
132
+ v: 1,
133
+ t: "meta",
134
+ event: "open",
135
+ ts: Date.now(),
136
+ internalSessionId: this._internalSessionId,
137
+ adapter: this.adapterId,
138
+ });
103
139
  }
104
140
 
105
141
  // --- identity ----------------------------------------------------------------
@@ -126,17 +162,87 @@ export class AgentSession implements AgentClient, Bridgeable {
126
162
  handlers?: PromptHandlers,
127
163
  attachments?: Attachment[],
128
164
  ): Promise<PromptResult> {
129
- const res = await this.controller.prompt(text, handlers, attachments);
130
- if (!this._title && text.trim()) {
131
- this._title = text.trim().replace(/\s+/g, " ").slice(0, 60);
165
+ return new Promise<PromptResult>((resolve, reject) => {
166
+ this.queue.push({ text, handlers, attachments, resolve, reject });
167
+ void this.pump();
168
+ });
169
+ }
170
+
171
+ private async pump(): Promise<void> {
172
+ if (this.pumping) return;
173
+ this.pumping = true;
174
+ try {
175
+ while (this.queue.length > 0) {
176
+ const item = this.queue.shift()!;
177
+ try {
178
+ item.resolve(await this.runPrompt(item));
179
+ } catch (err) {
180
+ item.reject(err);
181
+ }
182
+ }
183
+ } finally {
184
+ this.pumping = false;
185
+ }
186
+ }
187
+
188
+ private async runPrompt(item: QueueItem): Promise<PromptResult> {
189
+ await this.appendTranscript({
190
+ v: 1,
191
+ t: "msg",
192
+ role: "user",
193
+ text: item.text,
194
+ ts: Date.now(),
195
+ });
196
+
197
+ const chunks: string[] = [];
198
+ const wrappedHandlers: PromptHandlers = {
199
+ ...item.handlers,
200
+ onChunk: (chunk) => {
201
+ chunks.push(chunk);
202
+ item.handlers?.onChunk?.(chunk);
203
+ },
204
+ };
205
+
206
+ try {
207
+ const res = await this.controller.prompt(item.text, wrappedHandlers, item.attachments);
208
+ if (!this._title && item.text.trim()) {
209
+ this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
210
+ }
211
+ // A session may have been created lazily on first prompt (degraded has none).
212
+ this._internalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
213
+ await this.persist();
214
+ await this.appendTranscript({
215
+ v: 1,
216
+ t: "msg",
217
+ role: "assistant",
218
+ text: res.text,
219
+ ts: Date.now(),
220
+ usage: res.usage,
221
+ stopReason: res.stopReason,
222
+ status: res.status,
223
+ });
224
+ return res;
225
+ } catch (err) {
226
+ await this.appendTranscript({
227
+ v: 1,
228
+ t: "msg",
229
+ role: "assistant",
230
+ text: chunks.join(""),
231
+ ts: Date.now(),
232
+ stopReason: "error",
233
+ status: "error",
234
+ });
235
+ throw err;
132
236
  }
133
- // A session may have been created lazily on first prompt (degraded has none).
134
- this._internalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
135
- await this.persist();
136
- return res;
137
237
  }
138
238
 
139
239
  interrupt(options?: InterruptOptions): void {
240
+ if (options?.clearQueue) {
241
+ const dropped = this.queue.splice(0);
242
+ for (const item of dropped) {
243
+ item.resolve({ text: "", stopReason: "cancelled", status: "cancelled", usage: null });
244
+ }
245
+ }
140
246
  this.controller.interrupt(options);
141
247
  }
142
248
 
@@ -213,4 +319,21 @@ export class AgentSession implements AgentClient, Bridgeable {
213
319
  title: this._title,
214
320
  });
215
321
  }
322
+
323
+ private async appendTranscript(line: TranscriptLine): Promise<void> {
324
+ if (!this.transcriptPath) return;
325
+ this.transcriptWrite = this.transcriptWrite
326
+ .catch(() => {})
327
+ .then(async () => {
328
+ try {
329
+ await appendTranscriptLine(this.transcriptPath!, line);
330
+ } catch (err) {
331
+ this.log.warn("transcript_write_failed", {
332
+ path: this.transcriptPath,
333
+ error: String(err),
334
+ });
335
+ }
336
+ });
337
+ await this.transcriptWrite;
338
+ }
216
339
  }
package/src/index.ts CHANGED
@@ -61,6 +61,23 @@ export type { SessionStore, SessionRecord } from "./session-store.ts";
61
61
  export { SessionManager, mergeSessions } from "./session-manager.ts";
62
62
  export type { MergedSession, SessionInput } from "./session-manager.ts";
63
63
 
64
+ export {
65
+ appendTranscriptLine,
66
+ readTranscript,
67
+ readTranscriptLines,
68
+ } from "./transcript.ts";
69
+ export type {
70
+ ReadTranscriptOptions,
71
+ TranscriptActivityLine,
72
+ TranscriptEntry,
73
+ TranscriptLine,
74
+ TranscriptMessageLine,
75
+ TranscriptMetaLine,
76
+ TranscriptPermissionLine,
77
+ TranscriptRawLine,
78
+ TranscriptRole,
79
+ } from "./transcript.ts";
80
+
64
81
  export { ProcessCrashError, NotConnectedError, TimeoutError } from "./errors.ts";
65
82
 
66
83
  export { noopLogger, createConsoleLogger } from "./logger.ts";
@@ -0,0 +1,151 @@
1
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import type { PromptResult, Usage } from "./types.ts";
4
+
5
+ export type TranscriptRole = "user" | "assistant";
6
+
7
+ export interface TranscriptMetaLine {
8
+ v: 1;
9
+ t: "meta";
10
+ event: "open";
11
+ ts: number;
12
+ internalSessionId?: string | null;
13
+ adapter?: string;
14
+ }
15
+
16
+ export interface TranscriptMessageLine {
17
+ v: 1;
18
+ t: "msg";
19
+ role: TranscriptRole;
20
+ text: string;
21
+ ts: number;
22
+ usage?: Usage | null;
23
+ stopReason?: string;
24
+ status?: PromptResult["status"];
25
+ }
26
+
27
+ export interface TranscriptActivityLine {
28
+ v: 1;
29
+ t: "activity";
30
+ ts: number;
31
+ kind: string;
32
+ [key: string]: unknown;
33
+ }
34
+
35
+ export interface TranscriptPermissionLine {
36
+ v: 1;
37
+ t: "permission";
38
+ ts: number;
39
+ toolCallId?: string;
40
+ title?: string;
41
+ request?: unknown;
42
+ outcome?: unknown;
43
+ }
44
+
45
+ export interface TranscriptRawLine {
46
+ v: 1;
47
+ t: "raw";
48
+ ts: number;
49
+ protocol: "acp" | string;
50
+ event: string;
51
+ data: unknown;
52
+ }
53
+
54
+ export type TranscriptLine =
55
+ | TranscriptMetaLine
56
+ | TranscriptMessageLine
57
+ | TranscriptActivityLine
58
+ | TranscriptPermissionLine
59
+ | TranscriptRawLine;
60
+
61
+ export type TranscriptEntry = TranscriptMessageLine;
62
+
63
+ export interface ReadTranscriptOptions {
64
+ /** Return entries with `ts` lower than this cursor. */
65
+ before?: number;
66
+ /** Return at most this many entries. Keeps the newest matching entries. */
67
+ limit?: number;
68
+ }
69
+
70
+ export async function appendTranscriptLine(
71
+ path: string,
72
+ line: TranscriptLine,
73
+ ): Promise<void> {
74
+ await mkdir(dirname(path), { recursive: true });
75
+ await appendFile(path, `${JSON.stringify(line)}\n`, "utf8");
76
+ }
77
+
78
+ /** Read the message projection of a transcript. Meta/activity/raw lines are skipped. */
79
+ export async function readTranscript(
80
+ path: string,
81
+ options: ReadTranscriptOptions = {},
82
+ ): Promise<TranscriptEntry[]> {
83
+ const lines = await readTranscriptLines(path, options);
84
+ return lines.filter(isTranscriptMessageLine);
85
+ }
86
+
87
+ /** Read all recognized transcript lines, preserving oldest-first order. */
88
+ export async function readTranscriptLines(
89
+ path: string,
90
+ options: ReadTranscriptOptions = {},
91
+ ): Promise<TranscriptLine[]> {
92
+ let content: string;
93
+ try {
94
+ content = await readFile(path, "utf8");
95
+ } catch {
96
+ return [];
97
+ }
98
+
99
+ const out: TranscriptLine[] = [];
100
+ for (const raw of content.split(/\r?\n/)) {
101
+ if (!raw.trim()) continue;
102
+ try {
103
+ const line = JSON.parse(raw) as unknown;
104
+ if (!isTranscriptLine(line)) continue;
105
+ if (options.before != null && line.ts >= options.before) continue;
106
+ out.push(line);
107
+ } catch {
108
+ /* skip malformed lines */
109
+ }
110
+ }
111
+
112
+ if (options.limit != null && options.limit >= 0 && out.length > options.limit) {
113
+ return out.slice(out.length - options.limit);
114
+ }
115
+ return out;
116
+ }
117
+
118
+ function isTranscriptLine(value: unknown): value is TranscriptLine {
119
+ if (!isRecord(value)) return false;
120
+ if (value.v !== 1 || typeof value.t !== "string" || !isFiniteNumber(value.ts)) return false;
121
+
122
+ switch (value.t) {
123
+ case "meta":
124
+ return value.event === "open";
125
+ case "msg":
126
+ return (
127
+ (value.role === "user" || value.role === "assistant") &&
128
+ typeof value.text === "string"
129
+ );
130
+ case "activity":
131
+ return typeof value.kind === "string";
132
+ case "permission":
133
+ return true;
134
+ case "raw":
135
+ return typeof value.protocol === "string" && typeof value.event === "string";
136
+ default:
137
+ return false;
138
+ }
139
+ }
140
+
141
+ function isTranscriptMessageLine(value: TranscriptLine): value is TranscriptMessageLine {
142
+ return value.t === "msg";
143
+ }
144
+
145
+ function isRecord(value: unknown): value is Record<string, unknown> {
146
+ return typeof value === "object" && value !== null && !Array.isArray(value);
147
+ }
148
+
149
+ function isFiniteNumber(value: unknown): value is number {
150
+ return typeof value === "number" && Number.isFinite(value);
151
+ }