@qlairoslabs/acp-client 0.1.1 → 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
@@ -128,12 +128,37 @@ await session.prompt("Start working on the auth module.");
128
128
 
129
129
  // later. List everything we know about, catalog ∪ the agent's live list
130
130
  for (const s of await session.listSessions()) {
131
- console.log(s.source, s.id, s.title); // source: "catalog" | "agent" | "both"
131
+ console.log(s.source, s.agentSessionId, s.title); // source: "catalog" | "agent" | "both"
132
132
  }
133
133
 
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.1",
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",
@@ -2,7 +2,7 @@
2
2
  // consumer (the orchestration hub, the CLI) holds: a conversation with a stable identity
3
3
  // that persists across reconnects/mode-swaps, backed by a SessionManager catalog.
4
4
  //
5
- // It owns identity (our `id`, adapter, mode, agentSessionId, title) and persistence, and
5
+ // It owns identity (our `agentSessionId`, adapter, mode, internalSessionId, title) and persistence, and
6
6
  // HOLDS an AgentController for the live connection (the control plane). It implements
7
7
  // AgentClient, so the REPL and any caller can prompt it directly.
8
8
  //
@@ -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,33 +53,51 @@ export interface AgentSessionConfig {
43
53
  logger?: Logger;
44
54
  /** Optional catalog. When present, the session records itself here. */
45
55
  sessions?: SessionManager;
46
- /** Our stable catalog id. Minted if omitted (a fresh conversation); pass a record's id to resume. */
47
- id?: string;
48
- /** Agent session to load on start (resume an existing agent conversation). */
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;
60
+ /** Our stable AgentSession id. Minted if omitted; pass a record's agentSessionId to resume. */
49
61
  agentSessionId?: string;
62
+ /** ACP/harness session to load on start (resume an existing provider conversation). */
63
+ internalSessionId?: string;
50
64
  title?: string;
51
65
  }
52
66
 
53
67
  export class AgentSession implements AgentClient, Bridgeable {
54
- /** Our stable catalog id — decoupled from the agent's (mutable) session id. */
55
- readonly id: string;
68
+ /** Our stable AgentSession id — decoupled from the ACP/harness session id. */
69
+ readonly agentSessionId: string;
56
70
  readonly adapterId: string;
57
71
 
58
72
  private readonly controller: AgentController;
59
73
  private readonly sessions?: SessionManager;
60
- private _agentSessionId: string | null;
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;
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) {
66
- this.id = config.id ?? crypto.randomUUID();
85
+ if (config.transcriptPath && config.transcriptDir) {
86
+ throw new Error("AgentSessionConfig cannot specify both transcriptPath and transcriptDir");
87
+ }
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;
72
- this._agentSessionId = config.agentSessionId ?? null;
100
+ this._internalSessionId = config.internalSessionId ?? null;
73
101
  this.controller = new AgentController({
74
102
  adapter: config.adapter,
75
103
  adapterId: config.adapterId,
@@ -77,7 +105,7 @@ export class AgentSession implements AgentClient, Bridgeable {
77
105
  execPrefix: config.execPrefix,
78
106
  env: config.env,
79
107
  cwd: config.cwd,
80
- sessionId: config.agentSessionId,
108
+ sessionId: config.internalSessionId,
81
109
  mcpServers: config.mcpServers,
82
110
  defaultPermission: config.defaultPermission,
83
111
  clientInfo: config.clientInfo,
@@ -86,8 +114,8 @@ export class AgentSession implements AgentClient, Bridgeable {
86
114
  }
87
115
 
88
116
  /**
89
- * Start a conversation. A FRESH one if no `id`/`agentSessionId`; a RESUMED one if
90
- * `agentSessionId` is given (the controller loads it). To resume from the catalog, the
117
+ * Start a conversation. A FRESH one if no `agentSessionId`/`internalSessionId`; a RESUMED one if
118
+ * `internalSessionId` is given (the controller loads it). To resume from the catalog, the
91
119
  * caller resolves the record's adapter and passes the record's fields here.
92
120
  */
93
121
  static async create(config: AgentSessionConfig): Promise<AgentSession> {
@@ -98,13 +126,21 @@ export class AgentSession implements AgentClient, Bridgeable {
98
126
 
99
127
  private async start(): Promise<void> {
100
128
  const result = await this.controller.start();
101
- this._agentSessionId = result.sessionId || this._agentSessionId;
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 ----------------------------------------------------------------
106
- get agentSessionId(): string | null {
107
- return this._agentSessionId;
142
+ get internalSessionId(): string | null {
143
+ return this._internalSessionId;
108
144
  }
109
145
  get mode(): AgentMode {
110
146
  return this._mode;
@@ -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._agentSessionId = this.controller.currentSessionId ?? this._agentSessionId;
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
 
@@ -148,7 +254,7 @@ export class AgentSession implements AgentClient, Bridgeable {
148
254
  async setMode(mode: AgentMode): Promise<ConnectResult> {
149
255
  const result = await this.controller.setMode(mode);
150
256
  this._mode = this.controller.currentMode;
151
- this._agentSessionId = result.sessionId || null; // the agent session changes on swap
257
+ this._internalSessionId = result.sessionId || null; // the ACP/harness session changes on swap
152
258
  await this.persist();
153
259
  return result;
154
260
  }
@@ -192,8 +298,8 @@ export class AgentSession implements AgentClient, Bridgeable {
192
298
  }
193
299
  if (this.sessions) return this.sessions.listMerged(agentEntries, this.adapterId);
194
300
  return agentEntries.map((e) => ({
195
- id: e.sessionId,
196
301
  agentSessionId: e.sessionId,
302
+ internalSessionId: e.sessionId,
197
303
  adapter: this.adapterId,
198
304
  cwd: e.cwd,
199
305
  title: e.title,
@@ -205,12 +311,29 @@ export class AgentSession implements AgentClient, Bridgeable {
205
311
  private async persist(): Promise<void> {
206
312
  if (!this.sessions) return;
207
313
  await this.sessions.record({
208
- id: this.id,
209
- agentSessionId: this._agentSessionId,
314
+ agentSessionId: this.agentSessionId,
315
+ internalSessionId: this._internalSessionId,
210
316
  adapter: this.adapterId,
211
317
  mode: this._mode,
212
318
  cwd: this._cwd,
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";
@@ -29,8 +29,8 @@ import type { SessionManager, MergedSession } from "../session-manager.ts";
29
29
 
30
30
  /** The control-plane surface required by the reusable slash commands. */
31
31
  export interface InteractiveAgentClient extends AgentClient, Bridgeable {
32
- /** Optional durable catalog identity, when the client is session-backed. */
33
- readonly id?: string;
32
+ /** Optional durable AgentSession identity, when the client is session-backed. */
33
+ readonly agentSessionId?: string;
34
34
  readonly currentAdapterId: string;
35
35
  readonly currentMode: AgentMode;
36
36
  readonly currentSessionId: string | null;
@@ -96,12 +96,12 @@ export interface AgentCommands {
96
96
  export function createAgentCommands(deps: CommandHandlerDeps): AgentCommands {
97
97
  const { client, note, color = false, sessionManager, adapterId } = deps;
98
98
 
99
- const recordSession = async (agentSessionId: string | null): Promise<void> => {
100
- if (!sessionManager || !adapterId || !client.id) return;
99
+ const recordSession = async (internalSessionId: string | null): Promise<void> => {
100
+ if (!sessionManager || !adapterId || !client.agentSessionId) return;
101
101
  try {
102
102
  await sessionManager.record({
103
- id: client.id,
104
- agentSessionId,
103
+ agentSessionId: client.agentSessionId,
104
+ internalSessionId,
105
105
  adapter: adapterId,
106
106
  mode: client.currentMode,
107
107
  cwd: client.currentCwd,
@@ -253,7 +253,7 @@ export function createAgentCommands(deps: CommandHandlerDeps): AgentCommands {
253
253
  const merged = s as MergedSession;
254
254
  const plain = s as SessionListEntry;
255
255
  const source = isMerged ? ` [${merged.source}]` : "";
256
- note(`${isMerged ? merged.id : plain.sessionId} ${s.title ?? ""} ${s.updatedAt ?? ""}${source}`);
256
+ note(`${isMerged ? merged.agentSessionId : plain.sessionId} ${s.title ?? ""} ${s.updatedAt ?? ""}${source}`);
257
257
  }
258
258
  }
259
259
  } catch (e) {
@@ -10,9 +10,10 @@ import type { SessionListEntry } from "./types.ts";
10
10
 
11
11
  /** A row in the merged session view. `source` says where it was seen. */
12
12
  export interface MergedSession {
13
- /** Our catalog id when cataloged, else the agent's sessionId. */
14
- id: string;
15
- agentSessionId: string | null;
13
+ /** Our AgentSession id when cataloged, else the ACP/harness sessionId. */
14
+ agentSessionId: string;
15
+ /** The ACP/harness protocol sessionId used by lower-level session operations. */
16
+ internalSessionId: string | null;
16
17
  adapter: string;
17
18
  mode?: "normal" | "degraded";
18
19
  cwd?: string;
@@ -30,7 +31,7 @@ export class SessionManager {
30
31
  /** Upsert a record: preserves createdAt, bumps updatedAt. Returns the stored record. */
31
32
  async record(input: SessionInput): Promise<SessionRecord> {
32
33
  const now = new Date().toISOString();
33
- const existing = await this.store.get(input.id);
34
+ const existing = await this.store.get(input.agentSessionId);
34
35
  const record: SessionRecord = {
35
36
  ...input,
36
37
  createdAt: existing?.createdAt ?? now,
@@ -40,12 +41,12 @@ export class SessionManager {
40
41
  return record;
41
42
  }
42
43
 
43
- get(id: string): Promise<SessionRecord | null> {
44
- return this.store.get(id);
44
+ get(agentSessionId: string): Promise<SessionRecord | null> {
45
+ return this.store.get(agentSessionId);
45
46
  }
46
47
 
47
- delete(id: string): Promise<void> {
48
- return this.store.delete(id);
48
+ delete(agentSessionId: string): Promise<void> {
49
+ return this.store.delete(agentSessionId);
49
50
  }
50
51
 
51
52
  /** Catalog records, newest first. */
@@ -73,19 +74,19 @@ export function mergeSessions(
73
74
  agentEntries: SessionListEntry[],
74
75
  adapter: string,
75
76
  ): MergedSession[] {
76
- const byAgentId = new Map<string, SessionRecord>();
77
- for (const r of catalog) if (r.agentSessionId) byAgentId.set(r.agentSessionId, r);
77
+ const byInternalId = new Map<string, SessionRecord>();
78
+ for (const r of catalog) if (r.internalSessionId) byInternalId.set(r.internalSessionId, r);
78
79
 
79
80
  const out: MergedSession[] = [];
80
- const claimed = new Set<string>(); // catalog ids already emitted via the agent list
81
+ const claimed = new Set<string>(); // AgentSession ids already emitted via the agent list
81
82
 
82
83
  for (const e of agentEntries) {
83
- const rec = byAgentId.get(e.sessionId);
84
+ const rec = byInternalId.get(e.sessionId);
84
85
  if (rec) {
85
- claimed.add(rec.id);
86
+ claimed.add(rec.agentSessionId);
86
87
  out.push({
87
- id: rec.id,
88
- agentSessionId: e.sessionId,
88
+ agentSessionId: rec.agentSessionId,
89
+ internalSessionId: e.sessionId,
89
90
  adapter: rec.adapter,
90
91
  mode: rec.mode,
91
92
  cwd: e.cwd ?? rec.cwd,
@@ -96,8 +97,8 @@ export function mergeSessions(
96
97
  } else {
97
98
  // Reported by the agent but not in our catalog (made via native CLI/bridge).
98
99
  out.push({
99
- id: e.sessionId,
100
100
  agentSessionId: e.sessionId,
101
+ internalSessionId: e.sessionId,
101
102
  adapter,
102
103
  cwd: e.cwd,
103
104
  title: e.title,
@@ -108,10 +109,10 @@ export function mergeSessions(
108
109
  }
109
110
 
110
111
  for (const r of catalog) {
111
- if (claimed.has(r.id)) continue; // already emitted as "both"
112
+ if (claimed.has(r.agentSessionId)) continue; // already emitted as "both"
112
113
  out.push({
113
- id: r.id,
114
114
  agentSessionId: r.agentSessionId,
115
+ internalSessionId: r.internalSessionId,
115
116
  adapter: r.adapter,
116
117
  mode: r.mode,
117
118
  cwd: r.cwd,
@@ -1,6 +1,6 @@
1
1
  // Session catalog storage. The library is NOT the source of truth for conversation
2
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
3
+ // which adapter/mode/cwd a session belongs to, keyed by OUR stable agent session id. That's the part
4
4
  // the agent can't tell us, and it survives a broken agent `session/list` (e.g. kimi).
5
5
  //
6
6
  // `SessionStore` is an interface so consumers (the orchestration hub) can back it with
@@ -12,14 +12,14 @@ import { homedir } from "node:os";
12
12
  import { join } from "node:path";
13
13
 
14
14
  export interface SessionRecord {
15
- /** OUR stable catalog id (a uuid). Decoupled from the agent's sessionId on purpose. */
16
- id: string;
15
+ /** OUR stable AgentSession id (a uuid). Decoupled from the ACP sessionId on purpose. */
16
+ agentSessionId: string;
17
17
  /**
18
- * The agent's protocol sessionId. Null in degraded mode (no protocol session), and it
18
+ * The ACP/harness protocol sessionId. Null in degraded mode (no protocol session), and it
19
19
  * CHANGES on mode-swap (the pty session ≠ the ACP session). Kept as a mutable field so
20
20
  * a future portable conversation can span several agent sessions without re-keying.
21
21
  */
22
- agentSessionId: string | null;
22
+ internalSessionId: string | null;
23
23
  /** Which adapter this session belongs to — the routing the agent's own list can't give. */
24
24
  adapter: string;
25
25
  mode: "normal" | "degraded";
@@ -32,9 +32,9 @@ export interface SessionRecord {
32
32
 
33
33
  export interface SessionStore {
34
34
  save(record: SessionRecord): Promise<void>;
35
- get(id: string): Promise<SessionRecord | null>;
35
+ get(agentSessionId: string): Promise<SessionRecord | null>;
36
36
  list(): Promise<SessionRecord[]>;
37
- delete(id: string): Promise<void>;
37
+ delete(agentSessionId: string): Promise<void>;
38
38
  }
39
39
 
40
40
  /** Default location for the file store. Overridable; the hub injects its own store. */
@@ -52,12 +52,12 @@ export class FileSessionStore implements SessionStore {
52
52
 
53
53
  async save(record: SessionRecord): Promise<void> {
54
54
  await mkdir(this.dir, { recursive: true });
55
- await writeFile(this.path(record.id), JSON.stringify(record, null, 2), "utf8");
55
+ await writeFile(this.path(record.agentSessionId), JSON.stringify(record, null, 2), "utf8");
56
56
  }
57
57
 
58
- async get(id: string): Promise<SessionRecord | null> {
58
+ async get(agentSessionId: string): Promise<SessionRecord | null> {
59
59
  try {
60
- return JSON.parse(await readFile(this.path(id), "utf8")) as SessionRecord;
60
+ return JSON.parse(await readFile(this.path(agentSessionId), "utf8")) as SessionRecord;
61
61
  } catch {
62
62
  return null;
63
63
  }
@@ -82,15 +82,15 @@ export class FileSessionStore implements SessionStore {
82
82
  return records;
83
83
  }
84
84
 
85
- async delete(id: string): Promise<void> {
85
+ async delete(agentSessionId: string): Promise<void> {
86
86
  try {
87
- await unlink(this.path(id));
87
+ await unlink(this.path(agentSessionId));
88
88
  } catch {
89
89
  /* already gone */
90
90
  }
91
91
  }
92
92
 
93
- private path(id: string): string {
94
- return join(this.dir, `${encodeURIComponent(id)}.json`);
93
+ private path(agentSessionId: string): string {
94
+ return join(this.dir, `${encodeURIComponent(agentSessionId)}.json`);
95
95
  }
96
96
  }
@@ -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
+ }