@qlairoslabs/acp-client 0.11.1 → 0.12.1

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.
Files changed (80) hide show
  1. package/CHANGELOG-consumer-fixes.md +62 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +288 -12
  4. package/MIGRATION-0.10-to-0.12.md +189 -0
  5. package/README.md +6 -3
  6. package/package.json +5 -2
  7. package/src/adapters.ts +8 -1
  8. package/src/agent/adoption/replay.ts +1 -0
  9. package/src/agent/config.ts +4 -0
  10. package/src/agent/conversation-manager.ts +178 -150
  11. package/src/agent/error-record-writer.ts +77 -0
  12. package/src/agent/persisted-lifecycle.ts +152 -35
  13. package/src/agent/record-capture.ts +18 -18
  14. package/src/agent-adapter-registry.ts +2 -0
  15. package/src/agent-client.ts +9 -3
  16. package/src/agent-conversation-contracts.ts +6 -0
  17. package/src/agent-conversation-owner.ts +31 -6
  18. package/src/agent-conversation-presentation.ts +12 -1
  19. package/src/agent-conversation-queue.ts +3 -2
  20. package/src/agent-session.ts +535 -94
  21. package/src/agent.ts +46 -23
  22. package/src/audit/config.ts +4 -0
  23. package/src/audit/projection.ts +3 -0
  24. package/src/checkpointing/recovery.ts +12 -0
  25. package/src/checkpointing/strategy.ts +2 -0
  26. package/src/client.ts +132 -30
  27. package/src/controller.ts +116 -7
  28. package/src/degraded/pty-client.ts +25 -1
  29. package/src/index.ts +17 -0
  30. package/src/internal-inference/config.ts +7 -0
  31. package/src/internal-inference/contracts.ts +3 -0
  32. package/src/internal-inference/coordination/handles.ts +11 -2
  33. package/src/internal-inference/coordination/manager.ts +20 -3
  34. package/src/internal-inference/index.ts +2 -0
  35. package/src/internal-inference/persistence/records.ts +3 -1
  36. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  37. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  38. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  39. package/src/media/acp.ts +118 -0
  40. package/src/media/capture.ts +15 -0
  41. package/src/media/content.ts +142 -0
  42. package/src/media/files.ts +28 -0
  43. package/src/media/parts.ts +145 -0
  44. package/src/media/pending.ts +51 -0
  45. package/src/media/redact.ts +14 -0
  46. package/src/media/store.ts +127 -0
  47. package/src/metering/provider.ts +8 -1
  48. package/src/operations/activity-tracker.ts +31 -0
  49. package/src/operations/contracts.ts +63 -0
  50. package/src/operations/errors.ts +31 -0
  51. package/src/operations/index.ts +6 -0
  52. package/src/operations/stale-policy.ts +51 -0
  53. package/src/operations/supervisor.ts +209 -0
  54. package/src/operations/timers.ts +12 -0
  55. package/src/out-of-band-messages.ts +49 -32
  56. package/src/persistence/audit-runtime.ts +14 -2
  57. package/src/persistence/backend.ts +108 -12
  58. package/src/persistence/error-records.ts +27 -0
  59. package/src/persistence/index.ts +8 -0
  60. package/src/persistence/presentation.ts +9 -1
  61. package/src/persistence/projection.ts +20 -0
  62. package/src/persistence/records.ts +45 -6
  63. package/src/persistence/sqlite-backend.ts +207 -16
  64. package/src/persistence/sqlite-conversation-records.ts +31 -4
  65. package/src/persistence/sqlite-files.ts +95 -0
  66. package/src/persistence/sqlite-media-store.ts +67 -0
  67. package/src/persistence/sqlite-schema.ts +86 -10
  68. package/src/persistence/state-runtime.ts +2 -0
  69. package/src/persistence/timeline-reconcile.ts +21 -4
  70. package/src/persistence/transcript-reader.ts +11 -4
  71. package/src/persistence/transcript-runtime.ts +105 -12
  72. package/src/repl/repl.ts +1 -1
  73. package/src/response.ts +40 -8
  74. package/src/steering/combine.ts +11 -4
  75. package/src/steering/contracts.ts +14 -4
  76. package/src/steering/controller.ts +96 -21
  77. package/src/steering/index.ts +1 -0
  78. package/src/transport/acp-transport.ts +18 -7
  79. package/src/types.ts +7 -0
  80. package/src/updates.ts +4 -4
@@ -5,10 +5,13 @@ import type {
5
5
  PersistenceBackend,
6
6
  PersistenceJsonValue,
7
7
  } from "./persistence/backend.ts";
8
+ import { contentText } from "./media/content.ts";
9
+ import { isMediaPart, type MessagePart, type ResolvedPart } from "./media/parts.ts";
8
10
 
9
11
  /** Input for an assistant message a consumer appends without running a provider turn. */
10
12
  export interface AppendAssistantMessageInput {
11
- readonly text: string;
13
+ readonly text?: string;
14
+ readonly parts?: readonly MessagePart[];
12
15
  /** Opaque JSON stored on the record for the consumer's own use. */
13
16
  readonly consumerMetadata?: PersistenceJsonValue;
14
17
  }
@@ -42,6 +45,7 @@ export async function pendingOutOfBandMessages(
42
45
  ): Promise<readonly MessageRecord[]> {
43
46
  const watermark = Math.max(
44
47
  await recoveredThroughSequence(persistence, conversationId, targetProviderContextId),
48
+ await persistence.outOfBandDelivery?.get(conversationId, targetProviderContextId ?? "") ?? 0,
45
49
  await lastCompletedTurnUserSequence(persistence, conversationId, currentUserSequence),
46
50
  );
47
51
  if (watermark >= currentUserSequence - 1) return [];
@@ -55,7 +59,7 @@ export async function pendingOutOfBandMessages(
55
59
  ...(cursor ? { cursor } : {}),
56
60
  });
57
61
  for (const message of page.messages) {
58
- if (message.role === "assistant" && isOutOfBandMessage(message) && textOf(message)) {
62
+ if (message.role === "assistant" && isOutOfBandMessage(message)) {
59
63
  pending.push(message);
60
64
  }
61
65
  }
@@ -64,27 +68,13 @@ export async function pendingOutOfBandMessages(
64
68
  return pending;
65
69
  }
66
70
 
67
- /**
68
- * Provider text for one turn: identity preamble, then out-of-band messages, then the user's
69
- * own text. Only the user's text is persisted; everything else reaches the provider alone.
70
- */
71
- export function composeProviderPrompt(
72
- prompt: string,
73
- identityPreamble: string | undefined,
74
- outOfBand: readonly MessageRecord[],
75
- ): string {
76
- const sections = [identityPreamble?.trim(), formatOutOfBandBlock(outOfBand)]
77
- .filter((section): section is string => Boolean(section));
78
- if (sections.length === 0) return prompt;
79
- return `${sections.join("\n\n")}\n\n<current-message>\n${prompt}\n</current-message>`;
80
- }
71
+ const OUT_OF_BAND_HEADER = "Messages you sent in this conversation through another channel since your last turn."
72
+ + " The user has seen them; you have not.";
81
73
 
82
- function formatOutOfBandBlock(messages: readonly MessageRecord[]): string | undefined {
83
- if (messages.length === 0) return undefined;
84
- const header = "Messages you sent in this conversation through another channel since your last turn."
85
- + " The user has seen them; you have not.";
74
+ /** The newest messages that fit the block's text budget, in order, and how many older ones were left out. */
75
+ function selectOutOfBandMessages(messages: readonly MessageRecord[]) {
86
76
  const entries = messages.map((message) => `[${message.timestamp}] ${textOf(message)}`);
87
- let budget = OUT_OF_BAND_PROMPT_MAX_CHARS - header.length;
77
+ let budget = OUT_OF_BAND_PROMPT_MAX_CHARS - OUT_OF_BAND_HEADER.length;
88
78
  let kept = 0;
89
79
  for (let index = entries.length - 1; index >= 0; index -= 1) {
90
80
  const cost = entries[index]!.length + 1;
@@ -92,12 +82,43 @@ function formatOutOfBandBlock(messages: readonly MessageRecord[]): string | unde
92
82
  budget -= cost;
93
83
  kept += 1;
94
84
  }
95
- const omitted = entries.length - kept;
96
- const body = [
97
- ...(omitted > 0 ? [`(${omitted} earlier message${omitted === 1 ? "" : "s"} omitted)`] : []),
98
- ...entries.slice(omitted),
99
- ];
100
- return `<messages-you-sent>\n${header}\n${body.join("\n")}\n</messages-you-sent>`;
85
+ return { omitted: entries.length - kept, selected: messages.slice(messages.length - kept) };
86
+ }
87
+
88
+ /**
89
+ * The parts sent for one turn: identity preamble, then out-of-band messages, then the user's own
90
+ * parts. Everything but the user's parts is provider-only (`record: false`). An out-of-band message
91
+ * with media is wrapped in `<message id>`, so its media blocks are tied to it.
92
+ */
93
+ export async function composeProviderParts(
94
+ current: readonly ResolvedPart[],
95
+ identityPreamble: string | undefined,
96
+ outOfBand: readonly MessageRecord[],
97
+ load: (message: MessageRecord) => Promise<readonly ResolvedPart[]>,
98
+ ): Promise<readonly ResolvedPart[]> {
99
+ if (!identityPreamble?.trim() && outOfBand.length === 0) return current;
100
+ const result: ResolvedPart[] = [];
101
+ const text = (value: string) => result.push({ kind: "text", text: value, record: false });
102
+ if (identityPreamble?.trim()) text(`${identityPreamble.trim()}\n\n`);
103
+ if (outOfBand.length > 0) {
104
+ const { selected, omitted } = selectOutOfBandMessages(outOfBand);
105
+ text(`<messages-you-sent>\n${OUT_OF_BAND_HEADER}\n`);
106
+ if (omitted > 0) text(`(${omitted} earlier message${omitted === 1 ? "" : "s"} omitted)\n`);
107
+ for (const [index, message] of selected.entries()) {
108
+ const parts = await load(message);
109
+ const hasMedia = parts.some(isMediaPart);
110
+ if (hasMedia) text(`<message id="${message.recordId}">\n`);
111
+ text(`[${message.timestamp}] `);
112
+ result.push(...parts);
113
+ if (hasMedia) text("\n</message>");
114
+ if (index < selected.length - 1) text("\n");
115
+ }
116
+ text("\n</messages-you-sent>\n\n");
117
+ }
118
+ text("<current-message>\n");
119
+ result.push(...current);
120
+ text("\n</current-message>");
121
+ return result;
101
122
  }
102
123
 
103
124
  async function recoveredThroughSequence(
@@ -169,11 +190,7 @@ async function completedTurnUserSequence(
169
190
  }
170
191
 
171
192
  function textOf(message: MessageRecord): string {
172
- if (typeof message.content === "string") return message.content.trim();
173
- return message.content
174
- .map((block) => block.type === "text" ? block.text : "")
175
- .join("")
176
- .trim();
193
+ return contentText(message.content).trim();
177
194
  }
178
195
 
179
196
  function parseMetadata(metadata: string | undefined): Record<string, unknown> {
@@ -18,6 +18,7 @@ export interface AuditLogIdentity {
18
18
 
19
19
  export class AuditPersistenceRuntime {
20
20
  private failed = false;
21
+ private serial: Promise<unknown> = Promise.resolve();
21
22
 
22
23
  private constructor(
23
24
  private readonly writer: FileSessionLogWriter<"audit">,
@@ -68,7 +69,14 @@ export class AuditPersistenceRuntime {
68
69
 
69
70
  get healthy(): boolean { return !this.failed; }
70
71
 
71
- async append(event: NormalizedPersistenceEvent, durable = false, ts = Date.now()): Promise<boolean> {
72
+ /** One write at a time: each takes its sequence number from the writer when it runs. */
73
+ append(event: NormalizedPersistenceEvent, durable = false, ts = Date.now()): Promise<boolean> {
74
+ const run = this.serial.then(() => this.appendNow(event, durable, ts));
75
+ this.serial = run.catch(() => undefined);
76
+ return run;
77
+ }
78
+
79
+ private async appendNow(event: NormalizedPersistenceEvent, durable: boolean, ts: number): Promise<boolean> {
72
80
  const record = projectAuditEvent(event, {
73
81
  auditLogId: this.identity.auditLogId,
74
82
  generation: this.identity.generation,
@@ -88,7 +96,7 @@ export class AuditPersistenceRuntime {
88
96
  }
89
97
 
90
98
  async sync(): Promise<void> { await this.writer.sync(); }
91
- async close(): Promise<void> { await this.writer.close(); }
99
+ async close(): Promise<void> { await this.serial; await this.writer.close(); }
92
100
  }
93
101
 
94
102
  /** Apply one normalized event stream to continuation state and its separate audit sink. */
@@ -134,6 +142,10 @@ export class AuditedPersistenceRuntime implements PersistenceStateRuntime {
134
142
  return primary;
135
143
  }
136
144
 
145
+ presentationStartedAt(presentationId: string): number | undefined {
146
+ return this.primary.presentationStartedAt?.(presentationId);
147
+ }
148
+
137
149
  async appendTransitionEvent(event: Omit<TransitionEvent, "event"> & { readonly event: Exclude<TransitionEvent["event"], "target_activated"> }, options: { readonly durable?: boolean; readonly ts?: number } = {}): Promise<void> {
138
150
  const ts = options.ts ?? Date.now();
139
151
  await this.primary.appendTransitionEvent(event, options);
@@ -1,8 +1,15 @@
1
1
  import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
2
+ import type { CancelOutcome, CancelReason } from "../operations/contracts.ts";
2
3
  import type { OperationMeteringRecord } from "../metering/record.ts";
3
4
  import type { AgentSessionMeteringState } from "../metering/state.ts";
4
5
  import type { InternalInferenceRepository } from "../internal-inference/persistence/repository.ts";
5
6
  import type { ConversationRecoveryCheckpointRepository } from "../checkpointing/contracts.ts";
7
+ import type { ConversationTimelineItem } from "./timeline-reconcile.ts";
8
+ import type { SharedFilesPersistence } from "../media/files.ts";
9
+ import type { MediaCaptureLevel } from "../media/capture.ts";
10
+ import type { MediaStore } from "../media/store.ts";
11
+ import type { MediaKind } from "../media/parts.ts";
12
+ import { contentText } from "../media/content.ts";
6
13
 
7
14
  export type PersistenceJsonPrimitive = string | number | boolean | null;
8
15
  export type PersistenceJsonValue =
@@ -34,6 +41,7 @@ export const CONVERSATION_RECORD_KINDS = [
34
41
  "activity",
35
42
  "metering",
36
43
  "error",
44
+ "cancellation",
37
45
  ] as const;
38
46
 
39
47
  export type ConversationRecordKind = (typeof CONVERSATION_RECORD_KINDS)[number];
@@ -47,11 +55,31 @@ export interface ConversationRecordEnvelope<K extends ConversationRecordKind = C
47
55
  readonly kind: K;
48
56
  /** ISO-8601 instant supplied by the producer and preserved verbatim. */
49
57
  readonly timestamp: string;
50
- /** Legacy envelope metadata; Agent-created records use it for internal operation correlation. */
58
+ /**
59
+ * The library operation the record was written in: a turn, an internal inference or recap, a
60
+ * setting change, a mode change, a handoff. Every record of one operation shares it. Absent on
61
+ * records written outside an operation (for example protocol lines while connecting).
62
+ */
63
+ readonly operationId?: string;
64
+ /** Legacy envelope metadata. Older records carried the operation id here (`{"operationId": …}`). */
51
65
  readonly metadata?: string;
52
66
  }
53
67
 
68
+ export interface PersistedMediaBlock {
69
+ readonly type: "media";
70
+ readonly kind: MediaKind;
71
+ readonly mode: "copy" | "link";
72
+ readonly ref?: string;
73
+ readonly uri?: string;
74
+ readonly name?: string;
75
+ readonly mimeType: string;
76
+ readonly size?: number;
77
+ readonly sha256?: string;
78
+ }
79
+
54
80
  export type PersistedContentBlock =
81
+ | PersistedMediaBlock
82
+ | { readonly type: "pasted"; readonly text: string; readonly name?: string }
55
83
  | { readonly type: "text"; readonly text: string }
56
84
  | {
57
85
  readonly type: "image";
@@ -167,9 +195,12 @@ export type ConversationErrorRecoverability =
167
195
 
168
196
  /** Allow-listed provider detail, retained only at raw capture. */
169
197
  export interface ConversationErrorDetails {
198
+ readonly phase?: "no_response" | "incomplete_response";
170
199
  readonly providerCode?: string | number;
171
200
  readonly rpcCode?: number;
172
201
  readonly service?: string;
202
+ /** The provider's name for the error class (OpenCode: `APIError`). A label, not a message. */
203
+ readonly errorName?: string;
173
204
  readonly exitCode?: number;
174
205
  readonly signal?: string;
175
206
  readonly transportState?: string;
@@ -189,6 +220,21 @@ export interface ErrorRecord extends ConversationRecordEnvelope<"error"> {
189
220
  readonly details?: ConversationErrorDetails;
190
221
  }
191
222
 
223
+ /**
224
+ * A running operation was cancelled, whatever the mechanism (an ACP `session/cancel`, killing a
225
+ * screen-scraped harness). One cancellation has two revisions under its `cancellationId`:
226
+ * `requested` (when, and why) and `resolved` (how it ended). Its `operationId` is the cancelled
227
+ * operation's.
228
+ */
229
+ export interface CancellationRecord extends ConversationRecordEnvelope<"cancellation"> {
230
+ readonly cancellationId: string;
231
+ readonly state: "requested" | "resolved";
232
+ /** `steer`: a message sent mid-turn; `interrupt`: Stop; `stalled`: the stale policy; `stop`: shutdown. */
233
+ readonly reason: CancelReason;
234
+ /** On `resolved` only. `too_late`: the operation finished on its own before the cancel took effect. */
235
+ readonly outcome?: CancelOutcome;
236
+ }
237
+
192
238
  export type ConversationRecord =
193
239
  | MessageRecord
194
240
  | ToolCallRecord
@@ -200,7 +246,8 @@ export type ConversationRecord =
200
246
  | ThinkingRecord
201
247
  | ActivityRecord
202
248
  | MeteringReferenceRecord
203
- | ErrorRecord;
249
+ | ErrorRecord
250
+ | CancellationRecord;
204
251
 
205
252
  type WithoutSequence<T> = T extends ConversationRecord ? Omit<T, "sequence"> : never;
206
253
  export type NewConversationRecord = WithoutSequence<ConversationRecord>;
@@ -219,6 +266,7 @@ type NonProtocolRecordKind = Exclude<ConversationRecordKind, "protocol">;
219
266
  export type ConversationRecordCaptureConfig = Readonly<
220
267
  Partial<Record<NonProtocolRecordKind, RecordCaptureLevel>> & {
221
268
  readonly protocol?: ProtocolRecordCapture;
269
+ readonly media?: MediaCaptureLevel;
222
270
  }
223
271
  >;
224
272
  export type ResolvedProtocolRecordCapturePolicy = Readonly<{
@@ -229,6 +277,7 @@ export type ResolvedProtocolRecordCapturePolicy = Readonly<{
229
277
  export type ConversationRecordCapturePolicy = Readonly<
230
278
  Record<NonProtocolRecordKind, RecordCaptureLevel> & {
231
279
  readonly protocol: ResolvedProtocolRecordCapturePolicy;
280
+ readonly media: MediaCaptureLevel;
232
281
  }
233
282
  >;
234
283
 
@@ -240,6 +289,7 @@ const DEFAULT_PROTOCOL_RECORD_CAPTURE: ResolvedProtocolRecordCapturePolicy = Obj
240
289
 
241
290
  export const DEFAULT_CONVERSATION_RECORD_CAPTURE: ConversationRecordCapturePolicy = Object.freeze({
242
291
  message: "content",
292
+ media: "content",
243
293
  tool_call: "metadata",
244
294
  permission: "metadata",
245
295
  configuration: "metadata",
@@ -250,6 +300,7 @@ export const DEFAULT_CONVERSATION_RECORD_CAPTURE: ConversationRecordCapturePolic
250
300
  activity: "metadata",
251
301
  metering: "metadata",
252
302
  error: "content",
303
+ cancellation: "metadata",
253
304
  });
254
305
 
255
306
  export interface AgentPersistenceIdentity {
@@ -320,6 +371,8 @@ export interface ConversationPreviewPage {
320
371
 
321
372
  export interface RecordListOptions {
322
373
  readonly kinds?: readonly ConversationRecordKind[];
374
+ /** Only the records of this operation (a turn's `operationId`, for example). */
375
+ readonly operationId?: string;
323
376
  readonly afterSequence?: number;
324
377
  readonly throughSequence?: number;
325
378
  readonly limit?: number;
@@ -334,14 +387,47 @@ export interface ConversationRecordPage {
334
387
  /** Newest matching records at a fixed conversation-sequence snapshot, oldest-first within each page. */
335
388
  export interface RecentRecordPageOptions {
336
389
  readonly kinds?: readonly ConversationRecordKind[];
390
+ /**
391
+ * Without `agentMessages`, the records per page (default 50, at most 500). With it, the most a
392
+ * page holds (records, or items when folded; default 2000, at most 10000): a page that reaches it
393
+ * ends early with `truncated`.
394
+ */
337
395
  readonly limit?: number;
338
396
  readonly olderCursor?: string;
397
+ /**
398
+ * Page by agent messages: each page holds this many agent messages and the activity that led to
399
+ * each. A record goes to the page where its item's first revision falls, so a page holds every
400
+ * revision of its items and none of another page's.
401
+ */
402
+ readonly agentMessages?: number;
403
+ /** `summary` leaves out tool calls' input and output; `records.get(recordId)` returns them. */
404
+ readonly detail?: "full" | "summary";
405
+ /** `true` returns timeline items instead of records. */
406
+ readonly fold?: false;
407
+ }
408
+
409
+ export interface RecentItemPageOptions extends Omit<RecentRecordPageOptions, "fold"> {
410
+ readonly fold: true;
339
411
  }
340
412
 
341
413
  export interface RecentRecordPage {
342
414
  readonly records: readonly ConversationRecord[];
343
415
  readonly snapshotSequence: number;
344
416
  readonly olderCursor?: string;
417
+ /** The page reached `limit` before its last agent message; the next page continues from there. */
418
+ readonly truncated?: true;
419
+ }
420
+
421
+ /**
422
+ * Recent history as timeline items, merged as `reconcileConversationTimeline` does. With
423
+ * `detail: "summary"` an item keeps two revisions, its first and its merged current, so it still
424
+ * reconciles with later records.
425
+ */
426
+ export interface RecentItemPage {
427
+ readonly items: readonly ConversationTimelineItem[];
428
+ readonly snapshotSequence: number;
429
+ readonly olderCursor?: string;
430
+ readonly truncated?: true;
345
431
  }
346
432
 
347
433
  export interface MessageListOptions {
@@ -524,6 +610,10 @@ export interface ConversationRecordPersistence {
524
610
  */
525
611
  deleteForConversation?(agentConversationId: AgentConversationId): Promise<number>;
526
612
  /** Optional efficient newest-first history API. Use list(afterSequence) for live catch-up. */
613
+ listRecent?(
614
+ agentConversationId: AgentConversationId,
615
+ options: RecentItemPageOptions,
616
+ ): Promise<RecentItemPage>;
527
617
  listRecent?(
528
618
  agentConversationId: AgentConversationId,
529
619
  options?: RecentRecordPageOptions,
@@ -681,7 +771,15 @@ export interface PersistenceCapabilities {
681
771
  readonly metering: boolean;
682
772
  }
683
773
 
774
+ export interface OutOfBandDeliveryPersistence {
775
+ get(owner: AgentConversationId, providerContext: string): Promise<number>;
776
+ advance(owner: AgentConversationId, providerContext: string, throughSequence: number): Promise<void>;
777
+ }
778
+
684
779
  export interface PersistenceScope {
780
+ readonly files?: SharedFilesPersistence;
781
+ readonly outOfBandDelivery?: OutOfBandDeliveryPersistence;
782
+ readonly media?: MediaStore;
685
783
  readonly conversations: ConversationPersistence;
686
784
  readonly records: ConversationRecordPersistence;
687
785
  readonly messages: ConversationMessagePersistence;
@@ -783,6 +881,13 @@ export function resolveConversationRecordCapture(
783
881
  ): ConversationRecordCapturePolicy {
784
882
  const resolved: Record<string, unknown> = { ...DEFAULT_CONVERSATION_RECORD_CAPTURE };
785
883
  for (const [kind, value] of Object.entries(override)) {
884
+ if (kind === "media") {
885
+ if (!["none", "metadata", "content"].includes(String(value))) {
886
+ throw new Error(`invalid media capture level: ${String(value)}`);
887
+ }
888
+ resolved.media = value;
889
+ continue;
890
+ }
786
891
  if (!isConversationRecordKind(kind)) throw new Error(`unknown record capture kind: ${kind}`);
787
892
  if (kind === "protocol") {
788
893
  resolved.protocol = resolveProtocolRecordCapture(value as ProtocolRecordCapture);
@@ -883,20 +988,11 @@ export function searchableText(record: ConversationRecord): string {
883
988
  case "error":
884
989
  // Errors are operational history, not searchable conversation content; v1 keeps them
885
990
  // out of full-text search.
991
+ case "cancellation":
886
992
  return "";
887
993
  }
888
994
  }
889
995
 
890
- function contentText(content: PersistedContent | undefined): string {
891
- if (typeof content === "string") return content;
892
- if (!content) return "";
893
- return content.map((block) => {
894
- if (block.type === "text") return block.text;
895
- if (block.type === "image") return block.alt ?? "";
896
- if (block.type === "resource") return [block.title, block.text, block.uri].filter(Boolean).join("\n");
897
- return jsonText(block.value);
898
- }).filter(Boolean).join("\n");
899
- }
900
996
 
901
997
  function jsonText(value: PersistenceJsonValue | undefined): string {
902
998
  return value === undefined ? "" : JSON.stringify(value);
@@ -13,6 +13,7 @@ export const CONVERSATION_ERROR_CODES = Object.freeze([
13
13
  "connection_lost",
14
14
  "prompt_interrupted",
15
15
  "recovery_failed",
16
+ "stalled",
16
17
  "unknown",
17
18
  ] as const);
18
19
 
@@ -52,9 +53,11 @@ export function sanitizeConversationErrorMessage(value: unknown): string | undef
52
53
  }
53
54
 
54
55
  export interface ConversationErrorDetailInput {
56
+ readonly phase?: unknown;
55
57
  readonly providerCode?: unknown;
56
58
  readonly rpcCode?: unknown;
57
59
  readonly service?: unknown;
60
+ readonly errorName?: unknown;
58
61
  readonly exitCode?: unknown;
59
62
  readonly signal?: unknown;
60
63
  readonly transportState?: unknown;
@@ -73,13 +76,16 @@ export function buildConversationErrorDetails(
73
76
  const providerCode = allowCode(input.providerCode);
74
77
  const rpcCode = allowInteger(input.rpcCode);
75
78
  const service = allowLabel(input.service);
79
+ const errorName = allowLabel(input.errorName);
76
80
  const exitCode = allowInteger(input.exitCode);
77
81
  const signal = allowLabel(input.signal);
78
82
  const transportState = allowLabel(input.transportState);
79
83
  const details: ConversationErrorDetails = Object.freeze({
84
+ ...(input.phase === "no_response" || input.phase === "incomplete_response" ? { phase: input.phase } : {}),
80
85
  ...(providerCode === undefined ? {} : { providerCode }),
81
86
  ...(rpcCode === undefined ? {} : { rpcCode }),
82
87
  ...(service === undefined ? {} : { service }),
88
+ ...(errorName === undefined ? {} : { errorName }),
83
89
  ...(exitCode === undefined ? {} : { exitCode }),
84
90
  ...(signal === undefined ? {} : { signal }),
85
91
  ...(transportState === undefined ? {} : { transportState }),
@@ -102,3 +108,24 @@ function allowLabel(value: unknown): string | undefined {
102
108
  if (!trimmed) return undefined;
103
109
  return trimmed.slice(0, MAX_ERROR_DETAIL_CHARS);
104
110
  }
111
+
112
+ /**
113
+ * Allow-listed machine-readable detail from a thrown ACP error, when it exposes any: the JSON-RPC code
114
+ * (standard, so the same for every harness, if coarse) and, from `data`, the labels harnesses are known to
115
+ * send. `data` itself is never copied; see `buildConversationErrorDetails`.
116
+ */
117
+ export function conversationErrorDetailsFromError(error: unknown): ConversationErrorDetails | undefined {
118
+ const value = typeof error === "object" && error !== null
119
+ ? error as { code?: unknown; data?: unknown }
120
+ : null;
121
+ const data = typeof value?.data === "object" && value.data !== null
122
+ ? value.data as Record<string, unknown>
123
+ : undefined;
124
+ return buildConversationErrorDetails({
125
+ rpcCode: typeof value?.code === "number" ? value.code : undefined,
126
+ phase: data?.phase,
127
+ service: data?.service,
128
+ errorName: data?.errorName,
129
+ providerCode: data?.providerCode,
130
+ });
131
+ }
@@ -73,6 +73,8 @@ export type {
73
73
  ParticipantRef,
74
74
  PersistedContent,
75
75
  PersistedContentBlock,
76
+ PersistedMediaBlock,
77
+ OutOfBandDeliveryPersistence,
76
78
  PersistedIdentitySnapshot,
77
79
  PersistedAgentMeteringState,
78
80
  PersistedConversationMeteringState,
@@ -91,6 +93,8 @@ export type {
91
93
  ProviderSessionRecord,
92
94
  RecordCaptureLevel,
93
95
  RecordListOptions,
96
+ RecentItemPage,
97
+ RecentItemPageOptions,
94
98
  RecentRecordPage,
95
99
  RecentRecordPageOptions,
96
100
  SearchMatch,
@@ -111,3 +115,7 @@ export {
111
115
  } from "./sqlite-backend.ts";
112
116
  export type { SqliteAgentPersistenceConfig } from "./sqlite-backend.ts";
113
117
  export { SQLITE_AGENT_SCHEMA_VERSION } from "./sqlite-schema.ts";
118
+
119
+ export type { MediaStore, MediaInfo, StoredMedia } from "../media/store.ts";
120
+
121
+ export type { SharedFile, SharedFilePage, SharedFileQuery, SharedFilesPersistence } from "../media/files.ts";
@@ -19,7 +19,11 @@ interface TranscriptPresentationItemBase {
19
19
  readonly revision: number;
20
20
  /** Physical transcript sequence containing this revision. */
21
21
  readonly recordSequence: number;
22
- /** Unix epoch milliseconds from the persisted record envelope. */
22
+ /** Unix epoch milliseconds when the item's first revision was written: when it began. */
23
+ readonly startedAt: number;
24
+ /** Unix epoch milliseconds when this revision, the item's latest, was written. */
25
+ readonly updatedAt: number;
26
+ /** @deprecated The same value as `updatedAt`; show `startedAt` as the item's time. */
23
27
  readonly timestamp: number;
24
28
  readonly operationId: string;
25
29
  readonly transcriptId: string;
@@ -56,8 +60,10 @@ export type TranscriptPresentationItem =
56
60
  | TranscriptPresentationReasoning
57
61
  | TranscriptPresentationActivity;
58
62
 
63
+ /** `startedAt` is the first revision's time; it defaults to this record's, right for a first revision. */
59
64
  export function presentationItemFromRecord(
60
65
  record: TranscriptPresentationRecord,
66
+ startedAt: number = record.ts,
61
67
  ): TranscriptPresentationItem | null {
62
68
  const presentation = record.presentation;
63
69
  if (!presentation) return null;
@@ -66,6 +72,8 @@ export function presentationItemFromRecord(
66
72
  position: presentation.position,
67
73
  revision: presentation.revision,
68
74
  recordSequence: record.seq,
75
+ startedAt,
76
+ updatedAt: record.ts,
69
77
  timestamp: record.ts,
70
78
  operationId: record.operationId,
71
79
  transcriptId: record.transcriptId,
@@ -21,6 +21,7 @@ import type {
21
21
  TranscriptEnvelope,
22
22
  TranscriptLifecycleRecord,
23
23
  TranscriptTransitionRecord,
24
+ TranscriptCancellationRecord,
24
25
  TranscriptPresentationMetadata,
25
26
  InternalSessionDescriptor,
26
27
  InternalSessionHistoryEntry,
@@ -124,6 +125,14 @@ export type NormalizedPersistenceEvent =
124
125
  readonly outcome?: string;
125
126
  readonly fullDetails?: JsonValue;
126
127
  }
128
+ | {
129
+ readonly kind: "cancellation";
130
+ readonly operationId: string;
131
+ readonly cancellationId: string;
132
+ readonly event: "requested" | "resolved";
133
+ readonly reason: TranscriptCancellationRecord["reason"];
134
+ readonly outcome?: TranscriptCancellationRecord["outcome"];
135
+ }
127
136
  | {
128
137
  readonly kind: "transition";
129
138
  readonly transitionId: string;
@@ -205,6 +214,11 @@ export function projectTranscriptEvent(
205
214
  const projected = configurationData(event, context.policy.configuration);
206
215
  return projected ? { ...base, t: "configuration", ...projected } : null;
207
216
  }
217
+ case "cancellation":
218
+ return {
219
+ ...base, t: "cancellation", operationId: event.operationId, cancellationId: event.cancellationId,
220
+ event: event.event, reason: event.reason, ...(event.outcome === undefined ? {} : { outcome: event.outcome }),
221
+ };
208
222
  case "permission": {
209
223
  if (context.policy.permissions === "none") return null;
210
224
  return {
@@ -259,6 +273,12 @@ export function projectAuditEvent(
259
273
  case "protocol_metadata":
260
274
  case "raw_protocol":
261
275
  return null;
276
+ case "cancellation":
277
+ return {
278
+ ...base, t: "cancellation", operationId: event.operationId, cancellationId: event.cancellationId,
279
+ event: event.event, reason: event.reason,
280
+ ...(event.outcome === undefined ? {} : { outcome: event.outcome }),
281
+ };
262
282
  case "reasoning":
263
283
  if (context.policy.reasoning === "none") return null;
264
284
  return { ...base, t: "reasoning", reasoningId: event.reasoningId, reasoningRevision: event.reasoningRevision, operationId: event.operationId, text: event.text, status: event.status };