@qlairoslabs/acp-client 0.11.0 → 0.12.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.
Files changed (85) hide show
  1. package/CHANGELOG-consumer-fixes.md +55 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +311 -17
  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 +3 -1
  8. package/src/agent/adoption/checkpoint-floor.ts +47 -0
  9. package/src/agent/adoption/index.ts +3 -1
  10. package/src/agent/adoption/replay.ts +15 -0
  11. package/src/agent/config.ts +4 -0
  12. package/src/agent/conversation-manager.ts +223 -153
  13. package/src/agent/error-record-writer.ts +77 -0
  14. package/src/agent/persisted-lifecycle.ts +152 -35
  15. package/src/agent/record-capture.ts +18 -18
  16. package/src/agent-adapter-registry.ts +2 -0
  17. package/src/agent-client.ts +9 -3
  18. package/src/agent-conversation-contracts.ts +6 -0
  19. package/src/agent-conversation-owner.ts +31 -6
  20. package/src/agent-conversation-presentation.ts +12 -1
  21. package/src/agent-conversation-queue.ts +3 -2
  22. package/src/agent-session.ts +537 -96
  23. package/src/agent.ts +46 -23
  24. package/src/audit/config.ts +4 -0
  25. package/src/audit/projection.ts +3 -0
  26. package/src/checkpointing/contracts.ts +28 -3
  27. package/src/checkpointing/persistence/sqlite-repository.ts +36 -8
  28. package/src/checkpointing/recovery.ts +9 -2
  29. package/src/checkpointing/strategy.ts +27 -2
  30. package/src/client.ts +120 -30
  31. package/src/controller.ts +116 -7
  32. package/src/degraded/pty-client.ts +25 -1
  33. package/src/identity/checkpoint-backed.ts +2 -2
  34. package/src/index.ts +17 -0
  35. package/src/internal-inference/config.ts +7 -0
  36. package/src/internal-inference/contracts.ts +3 -0
  37. package/src/internal-inference/coordination/handles.ts +11 -2
  38. package/src/internal-inference/coordination/manager.ts +20 -3
  39. package/src/internal-inference/index.ts +2 -0
  40. package/src/internal-inference/persistence/records.ts +3 -1
  41. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  42. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  43. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  44. package/src/media/acp.ts +118 -0
  45. package/src/media/capture.ts +15 -0
  46. package/src/media/content.ts +142 -0
  47. package/src/media/files.ts +28 -0
  48. package/src/media/parts.ts +145 -0
  49. package/src/media/pending.ts +51 -0
  50. package/src/media/redact.ts +14 -0
  51. package/src/media/store.ts +127 -0
  52. package/src/metering/provider.ts +8 -1
  53. package/src/operations/activity-tracker.ts +31 -0
  54. package/src/operations/contracts.ts +63 -0
  55. package/src/operations/errors.ts +31 -0
  56. package/src/operations/index.ts +6 -0
  57. package/src/operations/stale-policy.ts +51 -0
  58. package/src/operations/supervisor.ts +209 -0
  59. package/src/operations/timers.ts +12 -0
  60. package/src/out-of-band-messages.ts +49 -32
  61. package/src/persistence/audit-runtime.ts +14 -2
  62. package/src/persistence/backend.ts +108 -12
  63. package/src/persistence/error-records.ts +27 -0
  64. package/src/persistence/index.ts +8 -0
  65. package/src/persistence/presentation.ts +9 -1
  66. package/src/persistence/projection.ts +20 -0
  67. package/src/persistence/records.ts +45 -6
  68. package/src/persistence/sqlite-backend.ts +207 -16
  69. package/src/persistence/sqlite-conversation-records.ts +31 -4
  70. package/src/persistence/sqlite-files.ts +95 -0
  71. package/src/persistence/sqlite-media-store.ts +67 -0
  72. package/src/persistence/sqlite-schema.ts +146 -13
  73. package/src/persistence/state-runtime.ts +2 -0
  74. package/src/persistence/timeline-reconcile.ts +21 -4
  75. package/src/persistence/transcript-reader.ts +11 -4
  76. package/src/persistence/transcript-runtime.ts +105 -12
  77. package/src/repl/repl.ts +1 -1
  78. package/src/response.ts +40 -8
  79. package/src/steering/combine.ts +11 -4
  80. package/src/steering/contracts.ts +14 -4
  81. package/src/steering/controller.ts +96 -21
  82. package/src/steering/index.ts +1 -0
  83. package/src/transport/acp-transport.ts +18 -7
  84. package/src/types.ts +7 -0
  85. package/src/updates.ts +4 -4
@@ -1,8 +1,29 @@
1
1
  import type { Database } from "bun:sqlite";
2
+ import { contentText } from "../media/content.ts";
3
+ import type { PersistedContent } from "./backend.ts";
2
4
 
3
- export const SQLITE_AGENT_SCHEMA_VERSION = 13;
5
+ export const SQLITE_AGENT_SCHEMA_VERSION = 16;
4
6
 
5
7
  const BASE_SCHEMA = `
8
+ CREATE TABLE IF NOT EXISTS out_of_band_delivery (
9
+ owner TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
10
+ provider_context TEXT NOT NULL,
11
+ through_sequence INTEGER NOT NULL,
12
+ PRIMARY KEY(owner, provider_context)
13
+ );
14
+
15
+ CREATE TABLE IF NOT EXISTS conversation_media (
16
+ ref TEXT PRIMARY KEY,
17
+ owner TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
18
+ kind TEXT NOT NULL CHECK (kind IN ('image', 'audio', 'file')),
19
+ mime_type TEXT NOT NULL,
20
+ name TEXT,
21
+ size INTEGER NOT NULL CHECK (size >= 0),
22
+ sha256 TEXT NOT NULL,
23
+ data BLOB NOT NULL
24
+ );
25
+ CREATE INDEX IF NOT EXISTS conversation_media_owner_idx ON conversation_media(owner);
26
+
6
27
  CREATE TABLE IF NOT EXISTS schema_migrations (
7
28
  version INTEGER PRIMARY KEY,
8
29
  applied_at TEXT NOT NULL
@@ -68,7 +89,8 @@ CREATE TABLE IF NOT EXISTS conversation_records (
68
89
  'thinking',
69
90
  'activity',
70
91
  'metering',
71
- 'error'
92
+ 'error',
93
+ 'cancellation'
72
94
  )),
73
95
  timestamp TEXT NOT NULL,
74
96
  operation_id TEXT,
@@ -231,6 +253,14 @@ CREATE TABLE IF NOT EXISTS conversation_error_records (
231
253
  CREATE INDEX IF NOT EXISTS conversation_error_source_code_idx
232
254
  ON conversation_error_records(source, code, record_row_id);
233
255
 
256
+ CREATE TABLE IF NOT EXISTS conversation_cancellation_events (
257
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
258
+ cancellation_id TEXT NOT NULL,
259
+ state TEXT NOT NULL CHECK (state IN ('requested', 'resolved')),
260
+ reason TEXT NOT NULL CHECK (reason IN ('interrupt', 'steer', 'stalled', 'stop', 'abort')),
261
+ outcome TEXT CHECK (outcome IS NULL OR outcome IN ('acknowledged', 'forced', 'too_late', 'failed'))
262
+ );
263
+
234
264
  CREATE TABLE IF NOT EXISTS conversation_checkpoints (
235
265
  agent_conversation_id TEXT PRIMARY KEY REFERENCES conversations(agent_conversation_id),
236
266
  revision INTEGER NOT NULL CHECK (revision >= 0),
@@ -376,12 +406,20 @@ CREATE TABLE IF NOT EXISTS conversation_recovery_checkpoints (
376
406
  revision INTEGER NOT NULL CHECK (revision >= 1),
377
407
  covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 1),
378
408
  previous_checkpoint_id TEXT REFERENCES conversation_recovery_checkpoints(checkpoint_id),
379
- generator_internal_inference_id TEXT NOT NULL UNIQUE REFERENCES internal_inferences(internal_inference_id),
380
- summary TEXT NOT NULL CHECK (length(summary) > 0),
409
+ generator_internal_inference_id TEXT UNIQUE REFERENCES internal_inferences(internal_inference_id),
410
+ source TEXT NOT NULL DEFAULT 'internal_inference'
411
+ CHECK (source IN ('internal_inference', 'adoption_recap', 'adoption_baseline')),
412
+ summary TEXT NOT NULL,
413
+ responses_counted_after_sequence INTEGER CHECK (responses_counted_after_sequence IS NULL OR responses_counted_after_sequence >= 0),
381
414
  created_at TEXT NOT NULL,
382
415
  metadata TEXT,
383
416
  UNIQUE (agent_conversation_id, revision),
384
- UNIQUE (agent_conversation_id, covered_sequence)
417
+ UNIQUE (agent_conversation_id, covered_sequence),
418
+ CHECK (
419
+ (source = 'internal_inference' AND generator_internal_inference_id IS NOT NULL AND length(summary) > 0)
420
+ OR (source = 'adoption_recap' AND generator_internal_inference_id IS NULL AND length(summary) > 0)
421
+ OR (source = 'adoption_baseline' AND generator_internal_inference_id IS NULL AND summary = '')
422
+ )
385
423
  );
386
424
 
387
425
  CREATE INDEX IF NOT EXISTS recovery_checkpoints_latest_idx
@@ -540,6 +578,31 @@ AFTER DELETE ON conversation_activity_events BEGIN
540
578
  END;
541
579
  `;
542
580
 
581
+ /**
582
+ * Version 15: records written before every write site passed its operation id recover it where it
583
+ * is still known. Runtime, permission and configuration record ids begin with it; native actions
584
+ * keep it as their transition id. Anything else stays without one.
585
+ */
586
+ function backfillRecordOperationIds(database: Database): void {
587
+ for (const [separator, kinds] of [
588
+ [":runtime:", "'tool_call', 'thinking', 'activity'"],
589
+ [":permission:", "'permission'"],
590
+ [":configuration:", "'configuration'"],
591
+ ] as const) {
592
+ database.query<unknown, [string, string]>(
593
+ `UPDATE conversation_records SET operation_id = substr(record_id, 1, instr(record_id, ?) - 1)
594
+ WHERE operation_id IS NULL AND kind IN (${kinds}) AND instr(record_id, ?) > 1`,
595
+ ).run(separator, separator);
596
+ }
597
+ database.exec(`UPDATE conversation_records SET operation_id = (
598
+ SELECT n.transition_id FROM conversation_native_action_events n WHERE n.record_row_id = conversation_records.row_id
599
+ )
600
+ WHERE operation_id IS NULL AND kind = 'native_action' AND EXISTS (
601
+ SELECT 1 FROM conversation_native_action_events n
602
+ WHERE n.record_row_id = conversation_records.row_id AND n.transition_id IS NOT NULL
603
+ )`);
604
+ }
605
+
543
606
  export function migrateSqliteAgentSchema(database: Database): void {
544
607
  const hasMigrations = database.query<{ present: number }, []>(
545
608
  "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
@@ -549,15 +612,15 @@ export function migrateSqliteAgentSchema(database: Database): void {
549
612
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
550
613
  ).get()?.version ?? 0)
551
614
  : 0;
552
- if (existing !== 0 && ![8, 9, 10, 11, 12, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
615
+ if (existing !== 0 && ![8, 9, 10, 11, 12, 13, 14, 15, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
553
616
  throw new Error(
554
617
  `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
555
618
  );
556
619
  }
557
- // Admitting the `error` kind means rebuilding conversation_records: its kind CHECK is a
620
+ // Admitting a new record kind means rebuilding conversation_records: its kind CHECK is a
558
621
  // closed list SQLite cannot alter in place. Foreign keys must be off for that drop, or
559
622
  // the implicit delete would cascade into every detail table.
560
- const rebuildRecords = existing > 0 && existing < 12;
623
+ const rebuildRecords = existing > 0 && existing < 15;
561
624
  if (rebuildRecords) database.exec("PRAGMA foreign_keys = OFF");
562
625
  try {
563
626
  database.exec("BEGIN IMMEDIATE");
@@ -586,11 +649,12 @@ export function migrateSqliteAgentSchema(database: Database): void {
586
649
  database.exec(`CREATE INDEX IF NOT EXISTS conversation_messages_logical_idx
587
650
  ON conversation_messages(logical_message_id, record_row_id)
588
651
  WHERE logical_message_id IS NOT NULL`);
589
- if (version > 0 && version < 12) {
590
- rebuildConversationRecordsForErrorKind(database);
652
+ if (version > 0 && version < 15) {
653
+ // Version 12 admitted `error`, version 15 `cancellation`: one rebuild admits every kind.
654
+ rebuildConversationRecordsForKinds(database);
591
655
  const violations = database.query<Record<string, unknown>, []>("PRAGMA foreign_key_check").all();
592
656
  if (violations.length > 0) {
593
- throw new Error("SQLite schema migration to version 12 left foreign key violations");
657
+ throw new Error("SQLite schema migration to version 15 left foreign key violations");
594
658
  }
595
659
  }
596
660
  if (version > 0 && version < 13) {
@@ -599,6 +663,31 @@ export function migrateSqliteAgentSchema(database: Database): void {
599
663
  database.exec("ALTER TABLE conversations ADD COLUMN adopted INTEGER NOT NULL DEFAULT 0 CHECK (adopted IN (0, 1))");
600
664
  database.exec("ALTER TABLE conversations ADD COLUMN adopt_provider_session_id TEXT");
601
665
  }
666
+ if (version > 0 && version < 14) {
667
+ rebuildRecoveryCheckpointsForAdoption(database);
668
+ const violations = database.query<Record<string, unknown>, []>("PRAGMA foreign_key_check").all();
669
+ if (violations.length > 0) {
670
+ throw new Error("SQLite schema migration to version 14 left foreign key violations");
671
+ }
672
+ }
673
+ if (version > 0 && version < 15) backfillRecordOperationIds(database);
674
+ if (version < 16) {
675
+ // Old structured search rows could contain inline base64 and media refs. Updating the
676
+ // source search text requires rebuilding an existing append-only FTS index as well.
677
+ const structured = database.query<{ record_row_id: number; content_json: string }, []>(
678
+ "SELECT record_row_id, content_json FROM conversation_messages WHERE content_json IS NOT NULL",
679
+ ).iterate();
680
+ const update = database.query("UPDATE conversation_messages SET search_text = ? WHERE record_row_id = ?");
681
+ for (const row of structured) {
682
+ update.run(contentText(JSON.parse(row.content_json) as PersistedContent), row.record_row_id);
683
+ }
684
+ const fts = database.query(
685
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'conversation_messages_fts'",
686
+ ).get();
687
+ if (fts) {
688
+ database.exec("INSERT INTO conversation_messages_fts(conversation_messages_fts) VALUES ('rebuild')");
689
+ }
690
+ }
602
691
  if (version < SQLITE_AGENT_SCHEMA_VERSION) {
603
692
  database.query<unknown, [number, string]>(
604
693
  "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
@@ -614,6 +703,48 @@ export function migrateSqliteAgentSchema(database: Database): void {
614
703
  }
615
704
  }
616
705
 
706
+ /**
707
+ * Rebuild `conversation_recovery_checkpoints` so a checkpoint may have no generator and an empty summary
708
+ * (adoption checkpoints), with a `source` and the adoption response-count base. SQLite cannot relax a
709
+ * NOT NULL or a CHECK in place. Foreign keys are off (see the caller). The old table's index goes with it and
710
+ * is recreated on the new one.
711
+ */
712
+ function rebuildRecoveryCheckpointsForAdoption(database: Database): void {
713
+ database.exec("ALTER TABLE conversation_recovery_checkpoints RENAME TO conversation_recovery_checkpoints_v13");
714
+ database.exec("DROP INDEX IF EXISTS recovery_checkpoints_latest_idx");
715
+ database.exec(`
716
+ CREATE TABLE conversation_recovery_checkpoints (
717
+ checkpoint_id TEXT PRIMARY KEY,
718
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
719
+ revision INTEGER NOT NULL CHECK (revision >= 1),
720
+ covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 1),
721
+ previous_checkpoint_id TEXT REFERENCES conversation_recovery_checkpoints(checkpoint_id),
722
+ generator_internal_inference_id TEXT UNIQUE REFERENCES internal_inferences(internal_inference_id),
723
+ source TEXT NOT NULL DEFAULT 'internal_inference'
724
+ CHECK (source IN ('internal_inference', 'adoption_recap', 'adoption_baseline')),
725
+ summary TEXT NOT NULL,
726
+ responses_counted_after_sequence INTEGER CHECK (responses_counted_after_sequence IS NULL OR responses_counted_after_sequence >= 0),
727
+ created_at TEXT NOT NULL,
728
+ metadata TEXT,
729
+ UNIQUE (agent_conversation_id, revision),
730
+ UNIQUE (agent_conversation_id, covered_sequence),
731
+ CHECK (
732
+ (source = 'internal_inference' AND generator_internal_inference_id IS NOT NULL AND length(summary) > 0)
733
+ OR (source = 'adoption_recap' AND generator_internal_inference_id IS NULL AND length(summary) > 0)
734
+ OR (source = 'adoption_baseline' AND generator_internal_inference_id IS NULL AND summary = '')
735
+ )
736
+ )`);
737
+ database.exec(`INSERT INTO conversation_recovery_checkpoints(
738
+ checkpoint_id, agent_conversation_id, revision, covered_sequence, previous_checkpoint_id,
739
+ generator_internal_inference_id, source, summary, created_at, metadata
740
+ ) SELECT checkpoint_id, agent_conversation_id, revision, covered_sequence, previous_checkpoint_id,
741
+ generator_internal_inference_id, 'internal_inference', summary, created_at, metadata
742
+ FROM conversation_recovery_checkpoints_v13`);
743
+ database.exec("DROP TABLE conversation_recovery_checkpoints_v13");
744
+ database.exec(`CREATE INDEX IF NOT EXISTS recovery_checkpoints_latest_idx
745
+ ON conversation_recovery_checkpoints(agent_conversation_id, revision DESC)`);
746
+ }
747
+
617
748
  /**
618
749
  * Rebuild `conversation_records` so its `kind` CHECK admits `error`.
619
750
  *
@@ -621,7 +752,8 @@ export function migrateSqliteAgentSchema(database: Database): void {
621
752
  * the swap. The caller runs this with foreign keys disabled and verifies with
622
753
  * `PRAGMA foreign_key_check` afterward.
623
754
  */
624
- function rebuildConversationRecordsForErrorKind(database: Database): void {
755
+ /** Recreate conversation_records with the current kind CHECK, keeping every row and its row id. */
756
+ function rebuildConversationRecordsForKinds(database: Database): void {
625
757
  database.exec(`CREATE TABLE conversation_records_v12 (
626
758
  row_id INTEGER PRIMARY KEY,
627
759
  record_id TEXT NOT NULL UNIQUE,
@@ -639,7 +771,8 @@ function rebuildConversationRecordsForErrorKind(database: Database): void {
639
771
  'thinking',
640
772
  'activity',
641
773
  'metering',
642
- 'error'
774
+ 'error',
775
+ 'cancellation'
643
776
  )),
644
777
  timestamp TEXT NOT NULL,
645
778
  operation_id TEXT,
@@ -29,6 +29,8 @@ export interface PersistenceStateRuntime {
29
29
  event: PresentationPersistenceEvent,
30
30
  ts?: number,
31
31
  ): Promise<TranscriptPresentationRecord | null>;
32
+ /** When a presentation item of the running operation was first written; forgotten when it ends. */
33
+ presentationStartedAt?(presentationId: string): number | undefined;
32
34
  appendTransitionEvent(event: Omit<TransitionEvent, "event"> & { readonly event: Exclude<TransitionEvent["event"], "target_activated"> }, options?: { readonly durable?: boolean; readonly ts?: number }): Promise<void>;
33
35
  publishCheckpoint(changes: TranscriptTerminalCheckpointChanges, ts?: number): Promise<AgentSessionCheckpoint>;
34
36
  activateTransition(event: Omit<TransitionEvent, "event"> & { readonly event: "target_activated" }, ts?: number): Promise<AgentSessionCheckpoint>;
@@ -6,6 +6,10 @@ export interface ConversationTimelineItem {
6
6
  readonly kind: ConversationRecordKind;
7
7
  readonly firstSequence: number;
8
8
  readonly lastSequence: number;
9
+ /** When the first revision was written: the item's own time, e.g. when a message began. */
10
+ readonly startedAt: string;
11
+ /** When the latest revision was written (also `current.timestamp`). */
12
+ readonly updatedAt: string;
9
13
  /** Records in canonical order; retain these when rendering lifecycle details. */
10
14
  readonly revisions: readonly ConversationRecord[];
11
15
  /** Later fields override earlier ones, while omitted fields are retained. */
@@ -39,6 +43,8 @@ export function reconcileConversationTimeline(
39
43
  kind: revisions[0]!.kind,
40
44
  firstSequence: revisions[0]!.sequence,
41
45
  lastSequence: revisions.at(-1)!.sequence,
46
+ startedAt: revisions[0]!.timestamp,
47
+ updatedAt: revisions.at(-1)!.timestamp,
42
48
  revisions: Object.freeze(revisions),
43
49
  current: Object.freeze(Object.assign({}, ...revisions)) as ConversationRecord,
44
50
  }));
@@ -58,16 +64,27 @@ export function conversationTimelineItemId(record: ConversationRecord): string {
58
64
  case "thinking": return `${prefix}${JSON.stringify([scope, record.thinkingId])}`;
59
65
  case "activity": return `${prefix}${JSON.stringify([scope, record.activityId])}`;
60
66
  case "native_action": return `${prefix}${JSON.stringify([record.transitionId ?? record.recordId])}`;
67
+ case "cancellation": return `${prefix}${JSON.stringify([record.cancellationId])}`;
61
68
  default: return `${prefix}${JSON.stringify([record.recordId])}`;
62
69
  }
63
70
  }
64
71
 
72
+ /**
73
+ * The operation an item's provider-local id (a tool call id, a permission id) is unique within, so
74
+ * two turns that reuse an id stay two items. The metadata's operation id comes first: items whose
75
+ * records carried it there keep the ids they had before records carried `operationId`.
76
+ */
65
77
  function operationScope(record: ConversationRecord): string {
66
- if (!record.metadata) return "";
78
+ const operationId = metadataOperationId(record.metadata) ?? record.operationId;
79
+ return operationId ? `${operationId}:` : "";
80
+ }
81
+
82
+ function metadataOperationId(metadata: string | undefined): string | undefined {
83
+ if (!metadata) return undefined;
67
84
  try {
68
- const parsed = JSON.parse(record.metadata) as { operationId?: unknown };
69
- return typeof parsed.operationId === "string" ? `${parsed.operationId}:` : "";
85
+ const parsed = JSON.parse(metadata) as { operationId?: unknown };
86
+ return typeof parsed.operationId === "string" ? parsed.operationId : undefined;
70
87
  } catch {
71
- return "";
88
+ return undefined;
72
89
  }
73
90
  }
@@ -18,6 +18,7 @@ import {
18
18
  type TranscriptMessageRecord,
19
19
  type TranscriptMeteringReferenceRecord,
20
20
  type TranscriptPermissionRecord,
21
+ type TranscriptCancellationRecord,
21
22
  type TranscriptProtocolMetadataRecord,
22
23
  type TranscriptReasoningRecord,
23
24
  type TranscriptRecordType,
@@ -41,12 +42,12 @@ const UTF8 = new TextDecoder("utf-8", { fatal: true });
41
42
  const RECORD_TYPE_ORDER: readonly TranscriptRecordType[] = Object.freeze([
42
43
  "header", "checkpoint", "operation", "message", "reasoning", "activity",
43
44
  "configuration", "permission", "transition", "metering_reference", "lifecycle",
44
- "protocol", "raw",
45
+ "protocol", "raw", "cancellation",
45
46
  ]);
46
47
  const RECORD_TYPES = new Set(RECORD_TYPE_ORDER);
47
48
  const TIMELINE_TYPES = new Set<TranscriptRecordType>([
48
49
  "message", "reasoning", "activity", "configuration", "permission", "transition",
49
- "metering_reference", "lifecycle", "protocol",
50
+ "metering_reference", "lifecycle", "protocol", "cancellation",
50
51
  ]);
51
52
 
52
53
  export type TranscriptView = "conversation" | "timeline" | "records";
@@ -92,6 +93,7 @@ export type TranscriptTimelineItem =
92
93
  | TranscriptActivityRecord
93
94
  | TranscriptConfigurationRecord
94
95
  | TranscriptPermissionRecord
96
+ | TranscriptCancellationRecord
95
97
  | TranscriptTransitionRecord
96
98
  | TranscriptMeteringReferenceRecord
97
99
  | TranscriptLifecycleRecord
@@ -309,6 +311,7 @@ export class TranscriptReader {
309
311
  // position === physical seq, so candidates can be selected while scanning and
310
312
  // later revisions can update only the bounded candidate set.
311
313
  const latest = new Map<string, TranscriptPresentationRecord>();
314
+ const startedAt = new Map<string, number>();
312
315
  const candidateIds: string[] = [];
313
316
  let boundaryFound = navigation === null;
314
317
  let expectedSequence = 1;
@@ -350,13 +353,17 @@ export class TranscriptReader {
350
353
  : metadata.position > navigation.boundaryPosition);
351
354
  if (!eligible) continue;
352
355
  latest.set(metadata.id, record);
356
+ startedAt.set(metadata.id, record.ts);
353
357
  candidateIds.push(metadata.id);
354
358
  if (candidateIds.length > limit + 1) {
355
359
  const removeIndex = navigation?.direction === "newer"
356
360
  ? candidateIds.length - 1
357
361
  : 0;
358
362
  const [removed] = candidateIds.splice(removeIndex, 1);
359
- if (removed) latest.delete(removed);
363
+ if (removed) {
364
+ latest.delete(removed);
365
+ startedAt.delete(removed);
366
+ }
360
367
  }
361
368
  }
362
369
  if (!boundaryFound) {
@@ -367,7 +374,7 @@ export class TranscriptReader {
367
374
  const pageIds = navigation?.direction === "newer"
368
375
  ? candidateIds.slice(0, limit)
369
376
  : candidateIds.slice(Math.max(0, candidateIds.length - limit));
370
- const selected = pageIds.map((id) => presentationItemFromRecord(latest.get(id)!)!);
377
+ const selected = pageIds.map((id) => presentationItemFromRecord(latest.get(id)!, startedAt.get(id))!);
371
378
  const hasOlder = navigation?.direction === "newer" ? true : hasExtra;
372
379
  const hasNewer = navigation?.direction === "older" ? true : navigation?.direction === "newer" ? hasExtra : false;
373
380
  const first = selected[0];
@@ -104,13 +104,24 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
104
104
  started: TranscriptOperationRecord;
105
105
  } | null = null;
106
106
  private failure: Error | null = null;
107
+ /**
108
+ * Writes run one at a time: each picks its sequence number from the writer when it runs, so two
109
+ * overlapping callers would otherwise claim the same number and the second would fail the transcript.
110
+ */
111
+ private serial: Promise<unknown> = Promise.resolve();
107
112
  private closed = false;
108
113
  private checkpointPublisher: ((
109
114
  checkpoint: AgentSessionCheckpoint,
110
115
  history: readonly InternalSessionHistoryEntry[],
111
116
  ) => Promise<void>) | null = null;
117
+ /**
118
+ * Each presentation item's first position and time. An item's id names its operation and a
119
+ * revision from another operation is refused, so an item never outlives its operation: entries
120
+ * are dropped when it ends.
121
+ */
112
122
  private readonly presentationStates = new Map<string, {
113
123
  readonly position: number;
124
+ readonly startedAt: number;
114
125
  readonly revision: number;
115
126
  readonly kind: PresentationPersistenceEvent["kind"];
116
127
  readonly operationId: string;
@@ -256,7 +267,11 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
256
267
  this.checkpointPublisher = publisher;
257
268
  }
258
269
 
259
- async beginOperation(operationId: string, kind: OperationKind, ts = Date.now()): Promise<void> {
270
+ beginOperation(operationId: string, kind: OperationKind, ts = Date.now()): Promise<void> {
271
+ return this.exclusive(() => this.beginOperationNow(operationId, kind, ts));
272
+ }
273
+
274
+ private async beginOperationNow(operationId: string, kind: OperationKind, ts = Date.now()): Promise<void> {
260
275
  this.assertUsable();
261
276
  if (this._recovery.kind !== "clean") throw new TranscriptRuntimeStateError("uncertain transcript recovery must be resolved before dispatch");
262
277
  if (this.activeOperation) throw new TranscriptRuntimeStateError("another transcript operation is already active");
@@ -278,12 +293,16 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
278
293
  } catch (error) {
279
294
  // Registry publication is part of the managed pre-dispatch boundary. Close the
280
295
  // transcript operation truthfully before reporting failure to the caller.
281
- await this.abortOperation("pre_dispatch_persistence_failure").catch(() => undefined);
296
+ await this.abortOperationNow("pre_dispatch_persistence_failure").catch(() => undefined);
282
297
  throw error;
283
298
  }
284
299
  }
285
300
 
286
- async appendEvent(event: NormalizedPersistenceEvent, ts = Date.now()): Promise<boolean> {
301
+ appendEvent(event: NormalizedPersistenceEvent, ts = Date.now()): Promise<boolean> {
302
+ return this.exclusive(() => this.appendEventNow(event, ts));
303
+ }
304
+
305
+ private async appendEventNow(event: NormalizedPersistenceEvent, ts = Date.now()): Promise<boolean> {
287
306
  this.assertUsable();
288
307
  if (event.kind === "transition") {
289
308
  throw new TranscriptRuntimeStateError("transitions require the dedicated transition boundary API");
@@ -306,7 +325,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
306
325
  }
307
326
  }
308
327
 
309
- async appendPresentationEvent(
328
+ appendPresentationEvent(
329
+ event: PresentationPersistenceEvent,
330
+ ts = Date.now(),
331
+ ): Promise<TranscriptPresentationRecord | null> {
332
+ return this.exclusive(() => this.appendPresentationEventNow(event, ts));
333
+ }
334
+
335
+ private async appendPresentationEventNow(
310
336
  event: PresentationPersistenceEvent,
311
337
  ts = Date.now(),
312
338
  ): Promise<TranscriptPresentationRecord | null> {
@@ -341,6 +367,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
341
367
  await this.writer.append(record);
342
368
  this.presentationStates.set(event.presentation.id, {
343
369
  position,
370
+ startedAt: existing?.startedAt ?? ts,
344
371
  revision: event.presentation.revision,
345
372
  kind: event.kind,
346
373
  operationId: presentationOperationId(event),
@@ -352,7 +379,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
352
379
  }
353
380
  }
354
381
 
355
- async appendTransitionEvent(
382
+ appendTransitionEvent(
383
+ event: NonActivationTransitionEvent,
384
+ options: { readonly durable?: boolean; readonly ts?: number } = {},
385
+ ): Promise<void> {
386
+ return this.exclusive(() => this.appendTransitionEventNow(event, options));
387
+ }
388
+
389
+ private async appendTransitionEventNow(
356
390
  event: NonActivationTransitionEvent,
357
391
  options: { readonly durable?: boolean; readonly ts?: number } = {},
358
392
  ): Promise<void> {
@@ -376,7 +410,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
376
410
  }
377
411
 
378
412
  /** Publish resumable non-routing state when no provider operation is active. */
379
- async publishCheckpoint(
413
+ publishCheckpoint(
414
+ changes: TranscriptTerminalCheckpointChanges,
415
+ ts = Date.now(),
416
+ ): Promise<AgentSessionCheckpoint> {
417
+ return this.exclusive(() => this.publishCheckpointNow(changes, ts));
418
+ }
419
+
420
+ private async publishCheckpointNow(
380
421
  changes: TranscriptTerminalCheckpointChanges,
381
422
  ts = Date.now(),
382
423
  ): Promise<AgentSessionCheckpoint> {
@@ -411,7 +452,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
411
452
  }
412
453
  }
413
454
 
414
- async activateTransition(
455
+ activateTransition(
456
+ event: TargetActivationEvent,
457
+ ts = Date.now(),
458
+ ): Promise<AgentSessionCheckpoint> {
459
+ return this.exclusive(() => this.activateTransitionNow(event, ts));
460
+ }
461
+
462
+ private async activateTransitionNow(
415
463
  event: TargetActivationEvent,
416
464
  ts = Date.now(),
417
465
  ): Promise<AgentSessionCheckpoint> {
@@ -450,13 +498,26 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
450
498
  }
451
499
 
452
500
  /** Flush policy-projected input appended after beginOperation before provider dispatch. */
453
- async syncBeforeDispatch(): Promise<void> {
501
+ syncBeforeDispatch(): Promise<void> {
502
+ return this.exclusive(() => this.syncBeforeDispatchNow());
503
+ }
504
+
505
+ private async syncBeforeDispatchNow(): Promise<void> {
454
506
  this.assertUsable();
455
507
  this.requireActive();
456
508
  await this.writer.sync();
457
509
  }
458
510
 
459
- async finishOperation(
511
+ finishOperation(
512
+ event: "settled" | "failed" | "cancelled" | "interrupted",
513
+ changes: TranscriptTerminalCheckpointChanges = {},
514
+ errorCode?: PersistedMachineCode,
515
+ ts = Date.now(),
516
+ ): Promise<AgentSessionCheckpoint> {
517
+ return this.exclusive(() => this.finishOperationNow(event, changes, errorCode, ts));
518
+ }
519
+
520
+ private async finishOperationNow(
460
521
  event: "settled" | "failed" | "cancelled" | "interrupted",
461
522
  changes: TranscriptTerminalCheckpointChanges = {},
462
523
  errorCode?: PersistedMachineCode,
@@ -504,6 +565,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
504
565
  );
505
566
  this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery);
506
567
  this.activeOperation = null;
568
+ this.forgetPresentation(active.operationId);
507
569
  await this.publishManagedCheckpoint();
508
570
  return this.checkpoint;
509
571
  } catch (error) {
@@ -512,7 +574,14 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
512
574
  }
513
575
  }
514
576
 
515
- async abortOperation(
577
+ abortOperation(
578
+ reason: OperationAbortReason,
579
+ ts = Date.now(),
580
+ ): Promise<AgentSessionCheckpoint> {
581
+ return this.exclusive(() => this.abortOperationNow(reason, ts));
582
+ }
583
+
584
+ private async abortOperationNow(
516
585
  reason: OperationAbortReason,
517
586
  ts = Date.now(),
518
587
  ): Promise<AgentSessionCheckpoint> {
@@ -543,6 +612,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
543
612
  );
544
613
  this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery);
545
614
  this.activeOperation = null;
615
+ this.forgetPresentation(active.operationId);
546
616
  await this.publishManagedCheckpoint();
547
617
  return this.checkpoint;
548
618
  } catch (error) {
@@ -558,7 +628,11 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
558
628
  * already durable, only its missing checkpoint is materialized. The canonical reducer
559
629
  * validates the complete opening tail before the runtime exposes clean state.
560
630
  */
561
- async acceptHarnessRecovery(ts = Date.now()): Promise<AgentSessionCheckpoint> {
631
+ acceptHarnessRecovery(ts = Date.now()): Promise<AgentSessionCheckpoint> {
632
+ return this.exclusive(() => this.acceptHarnessRecoveryNow(ts));
633
+ }
634
+
635
+ private async acceptHarnessRecoveryNow(ts = Date.now()): Promise<AgentSessionCheckpoint> {
562
636
  this.assertUsable();
563
637
  if (this.activeOperation) throw new TranscriptRuntimeStateError("cannot resolve recovery during an active operation");
564
638
  if (this._recovery.kind !== "uncertain") {
@@ -607,7 +681,7 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
607
681
  this.installCheckpoint(physical, reduced.checkpoint, reduced.recovery, reduced.internalSessionHistory);
608
682
  this.openingStructuralTail = [];
609
683
  await this.publishManagedCheckpoint();
610
- await this.appendEvent({
684
+ await this.appendEventNow({
611
685
  kind: "lifecycle",
612
686
  event: "recovery_resolved",
613
687
  detail: {
@@ -624,11 +698,30 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
624
698
  }
625
699
 
626
700
  async close(): Promise<void> {
701
+ if (this.closed) return;
702
+ // Writes already requested still land; anything requested after this is refused.
703
+ await this.serial;
627
704
  if (this.closed) return;
628
705
  this.closed = true;
629
706
  await this.writer.close();
630
707
  }
631
708
 
709
+ presentationStartedAt(presentationId: string): number | undefined {
710
+ return this.presentationStates.get(presentationId)?.startedAt;
711
+ }
712
+
713
+ private forgetPresentation(operationId: string): void {
714
+ for (const [id, state] of this.presentationStates) {
715
+ if (state.operationId === operationId) this.presentationStates.delete(id);
716
+ }
717
+ }
718
+
719
+ private exclusive<T>(write: () => Promise<T>): Promise<T> {
720
+ const run = this.serial.then(write);
721
+ this.serial = run.catch(() => undefined);
722
+ return run;
723
+ }
724
+
632
725
  private installCheckpoint(
633
726
  record: TranscriptCheckpointRecord,
634
727
  checkpoint: AgentSessionCheckpoint,
package/src/repl/repl.ts CHANGED
@@ -308,7 +308,7 @@ export async function runRepl(
308
308
  busy = true;
309
309
  try {
310
310
  const handlers: PromptHandlers = { onChunk, onActivity };
311
- const result = await (execute ? execute(handlers) : client.prompt(text, handlers));
311
+ const result = await (execute ? execute(handlers) : client.prompt({ text, handlers }));
312
312
  spinner?.stop();
313
313
 
314
314
  if (wroteLabel) {