@qlairoslabs/acp-client 0.9.4 → 0.10.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.
@@ -33,6 +33,7 @@ export const CONVERSATION_RECORD_KINDS = [
33
33
  "thinking",
34
34
  "activity",
35
35
  "metering",
36
+ "error",
36
37
  ] as const;
37
38
 
38
39
  export type ConversationRecordKind = (typeof CONVERSATION_RECORD_KINDS)[number];
@@ -150,6 +151,44 @@ export interface MeteringReferenceRecord extends ConversationRecordEnvelope<"met
150
151
  readonly status: "available" | "partial" | "unavailable";
151
152
  }
152
153
 
154
+ /** Operational boundary a conversation error was observed at. Closed taxonomy. */
155
+ export type ConversationErrorSource =
156
+ | "provider_session"
157
+ | "transport"
158
+ | "operation"
159
+ | "recovery";
160
+
161
+ /** What a consumer may reasonably do about a failed operation. */
162
+ export type ConversationErrorRecoverability =
163
+ | "retryable"
164
+ | "recoverable"
165
+ | "terminal"
166
+ | "unknown";
167
+
168
+ /** Allow-listed provider detail, retained only at raw capture. */
169
+ export interface ConversationErrorDetails {
170
+ readonly providerCode?: string | number;
171
+ readonly rpcCode?: number;
172
+ readonly service?: string;
173
+ readonly exitCode?: number;
174
+ readonly signal?: string;
175
+ readonly transportState?: string;
176
+ }
177
+
178
+ /** Immutable, sanitized diagnosis at a meaningful conversation boundary. */
179
+ export interface ErrorRecord extends ConversationRecordEnvelope<"error"> {
180
+ readonly source: ConversationErrorSource;
181
+ /** Stable machine-readable value. The type stays open for future codes. */
182
+ readonly code: string;
183
+ readonly recoverability: ConversationErrorRecoverability;
184
+ /** Sanitized fallback text intended for display, not a raw exception dump. */
185
+ readonly message?: string;
186
+ readonly operationId?: string;
187
+ readonly transitionId?: string;
188
+ readonly internalSessionId?: string;
189
+ readonly details?: ConversationErrorDetails;
190
+ }
191
+
153
192
  export type ConversationRecord =
154
193
  | MessageRecord
155
194
  | ToolCallRecord
@@ -160,7 +199,8 @@ export type ConversationRecord =
160
199
  | AgentActionRecord
161
200
  | ThinkingRecord
162
201
  | ActivityRecord
163
- | MeteringReferenceRecord;
202
+ | MeteringReferenceRecord
203
+ | ErrorRecord;
164
204
 
165
205
  type WithoutSequence<T> = T extends ConversationRecord ? Omit<T, "sequence"> : never;
166
206
  export type NewConversationRecord = WithoutSequence<ConversationRecord>;
@@ -209,6 +249,7 @@ export const DEFAULT_CONVERSATION_RECORD_CAPTURE: ConversationRecordCapturePolic
209
249
  thinking: "none",
210
250
  activity: "metadata",
211
251
  metering: "metadata",
252
+ error: "content",
212
253
  });
213
254
 
214
255
  export interface AgentPersistenceIdentity {
@@ -822,6 +863,10 @@ export function searchableText(record: ConversationRecord): string {
822
863
  return [record.activityType, contentText(record.content), jsonText(record.data)].filter(Boolean).join("\n");
823
864
  case "metering":
824
865
  return [record.operationId, record.meteringRecordId, record.status].join("\n");
866
+ case "error":
867
+ // Errors are operational history, not searchable conversation content; v1 keeps them
868
+ // out of full-text search.
869
+ return "";
825
870
  }
826
871
  }
827
872
 
@@ -0,0 +1,104 @@
1
+ import type {
2
+ ConversationErrorDetails,
3
+ ConversationErrorRecoverability,
4
+ ConversationErrorSource,
5
+ } from "./backend.ts";
6
+
7
+ /** Machine-readable codes the library owns. Readers must tolerate unknown future values. */
8
+ export const CONVERSATION_ERROR_CODES = Object.freeze([
9
+ "provider_session_create_failed",
10
+ "provider_session_load_failed",
11
+ "provider_session_missing",
12
+ "provider_process_exited",
13
+ "connection_lost",
14
+ "prompt_interrupted",
15
+ "recovery_failed",
16
+ "unknown",
17
+ ] as const);
18
+
19
+ export type ConversationErrorCode = (typeof CONVERSATION_ERROR_CODES)[number];
20
+
21
+ export const CONVERSATION_ERROR_SOURCES: readonly ConversationErrorSource[] = Object.freeze([
22
+ "provider_session",
23
+ "transport",
24
+ "operation",
25
+ "recovery",
26
+ ]);
27
+
28
+ export const CONVERSATION_ERROR_RECOVERABILITIES: readonly ConversationErrorRecoverability[] =
29
+ Object.freeze(["retryable", "recoverable", "terminal", "unknown"]);
30
+
31
+ const MAX_ERROR_MESSAGE_CHARS = 512;
32
+ const MAX_ERROR_DETAIL_CHARS = 128;
33
+
34
+ /**
35
+ * Reduce an arbitrary thrown value to a short, safe, single-line display string.
36
+ *
37
+ * The ordinary message must never carry a stack trace, credentials, a prompt, environment
38
+ * values, filesystem contents, or a raw provider payload. Producers normally supply a
39
+ * curated message; this is the safety net when a raw error is passed instead. Anything it
40
+ * cannot reduce to a short non-blank string is dropped rather than persisted.
41
+ */
42
+ export function sanitizeConversationErrorMessage(value: unknown): string | undefined {
43
+ const raw = typeof value === "string"
44
+ ? value
45
+ : value instanceof Error
46
+ ? value.message
47
+ : undefined;
48
+ if (raw === undefined) return undefined;
49
+ const firstLine = raw.split(/\r?\n/, 1)[0]?.replace(/\s+/g, " ").trim() ?? "";
50
+ if (!firstLine) return undefined;
51
+ return firstLine.slice(0, MAX_ERROR_MESSAGE_CHARS);
52
+ }
53
+
54
+ export interface ConversationErrorDetailInput {
55
+ readonly providerCode?: unknown;
56
+ readonly rpcCode?: unknown;
57
+ readonly service?: unknown;
58
+ readonly exitCode?: unknown;
59
+ readonly signal?: unknown;
60
+ readonly transportState?: unknown;
61
+ }
62
+
63
+ /**
64
+ * Build the raw-capture detail bag from allow-listed fields only.
65
+ *
66
+ * Unknown provider fields are discarded rather than recursively copied or heuristically
67
+ * redacted. Returns undefined when no allow-listed field is present, so `details` is absent
68
+ * rather than an empty object.
69
+ */
70
+ export function buildConversationErrorDetails(
71
+ input: ConversationErrorDetailInput,
72
+ ): ConversationErrorDetails | undefined {
73
+ const providerCode = allowCode(input.providerCode);
74
+ const rpcCode = allowInteger(input.rpcCode);
75
+ const service = allowLabel(input.service);
76
+ const exitCode = allowInteger(input.exitCode);
77
+ const signal = allowLabel(input.signal);
78
+ const transportState = allowLabel(input.transportState);
79
+ const details: ConversationErrorDetails = Object.freeze({
80
+ ...(providerCode === undefined ? {} : { providerCode }),
81
+ ...(rpcCode === undefined ? {} : { rpcCode }),
82
+ ...(service === undefined ? {} : { service }),
83
+ ...(exitCode === undefined ? {} : { exitCode }),
84
+ ...(signal === undefined ? {} : { signal }),
85
+ ...(transportState === undefined ? {} : { transportState }),
86
+ });
87
+ return Object.keys(details).length > 0 ? details : undefined;
88
+ }
89
+
90
+ function allowCode(value: unknown): string | number | undefined {
91
+ if (typeof value === "number" && Number.isFinite(value)) return value;
92
+ return allowLabel(value);
93
+ }
94
+
95
+ function allowInteger(value: unknown): number | undefined {
96
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
97
+ }
98
+
99
+ function allowLabel(value: unknown): string | undefined {
100
+ if (typeof value !== "string") return undefined;
101
+ const trimmed = value.trim();
102
+ if (!trimmed) return undefined;
103
+ return trimmed.slice(0, MAX_ERROR_DETAIL_CHARS);
104
+ }
@@ -599,7 +599,18 @@ function validateCreationOrRestorationStages(
599
599
  const matchingFields = maintenance.kind === "creation"
600
600
  ? ["adapterId", "mode", "internalSessionId", "internalSessionActivatedAt", "model", "sessionConfiguration", "protocol"] as const
601
601
  : ["adapterId", "mode", "internalSessionId", "internalSessionActivatedAt", "protocol"] as const;
602
+ // The continuation records the thread this attempt acquired, so a resumed creation
603
+ // can reuse it instead of orphaning it. The record says which thread is selected for
604
+ // a later open, and a thread that has completed no turn is not selected yet. So the
605
+ // record may leave the slot empty while the continuation names one — never the
606
+ // reverse, and never a different id.
607
+ const deferredAttachment = stagedRecord.internalSessionId === null
608
+ && (stagedContinuation as Record<string, unknown>).internalSessionId !== null;
602
609
  for (const field of matchingFields) {
610
+ if (deferredAttachment
611
+ && (field === "internalSessionId" || field === "internalSessionActivatedAt")) {
612
+ continue;
613
+ }
603
614
  if (canonicalizeJson(stagedRecord[field]) !== canonicalizeJson((stagedContinuation as Record<string, unknown>)[field])) {
604
615
  throw new AgentSessionRegistryError(`stagedRecord ${field} disagrees with stagedContinuation`);
605
616
  }
@@ -0,0 +1,46 @@
1
+ import type { AgentMode } from "../controller.ts";
2
+
3
+ export interface ProviderAttachmentDescriptor {
4
+ readonly attachmentAttemptId: string;
5
+ readonly internalSessionId: string;
6
+ readonly adapterId: string;
7
+ readonly mode: AgentMode;
8
+ readonly model?: string;
9
+ readonly acquiredAt: string;
10
+ readonly providerSessionRecordId?: string;
11
+ readonly transitionId?: string;
12
+ }
13
+
14
+ export type ProviderAttachmentState =
15
+ | { readonly kind: "absent" }
16
+ | { readonly kind: "runtime_only"; readonly descriptor: ProviderAttachmentDescriptor }
17
+ | { readonly kind: "recorded"; readonly descriptor: ProviderAttachmentDescriptor };
18
+
19
+ export interface ProviderAttachmentCommitAcknowledgement {
20
+ readonly attachmentAttemptId: string;
21
+ readonly providerSessionRecordId: string;
22
+ }
23
+
24
+ export function runtimeOnlyProviderAttachment(
25
+ descriptor: ProviderAttachmentDescriptor,
26
+ ): ProviderAttachmentState {
27
+ return Object.freeze({ kind: "runtime_only", descriptor: Object.freeze({ ...descriptor }) });
28
+ }
29
+
30
+ export function recordedProviderAttachment(
31
+ descriptor: ProviderAttachmentDescriptor,
32
+ ): ProviderAttachmentState {
33
+ return Object.freeze({ kind: "recorded", descriptor: Object.freeze({ ...descriptor }) });
34
+ }
35
+
36
+ export function acknowledgeProviderAttachment(
37
+ state: ProviderAttachmentState,
38
+ acknowledgement: ProviderAttachmentCommitAcknowledgement,
39
+ ): ProviderAttachmentState {
40
+ if (state.kind !== "runtime_only") return state;
41
+ if (state.descriptor.attachmentAttemptId !== acknowledgement.attachmentAttemptId) return state;
42
+ return recordedProviderAttachment({
43
+ ...state.descriptor,
44
+ providerSessionRecordId: acknowledgement.providerSessionRecordId,
45
+ });
46
+ }
@@ -221,7 +221,12 @@ export function reduceTranscriptState(
221
221
  }
222
222
  pendingRepair = null;
223
223
  }
224
- if (!expectedRepair) assertRoutingStable(candidate, checkpoint);
224
+ // A terminal checkpoint may fill in a thread slot the conversation never had. That is
225
+ // the first attachment, not a routing change: nothing is superseded, so there is no
226
+ // `from` descriptor to validate and no history entry to write.
227
+ if (!expectedRepair) {
228
+ assertRoutingStable(candidate, checkpoint, active?.terminal === "settled");
229
+ }
225
230
  if (active) {
226
231
  if (active.terminal) {
227
232
  if (candidate.stateRevision <= checkpoint.stateRevision) {
@@ -422,12 +427,20 @@ function assertCheckpointIdentityStable(
422
427
  function assertRoutingStable(
423
428
  candidate: AgentSessionCheckpoint,
424
429
  previous: AgentSessionCheckpoint,
430
+ allowInitialAttachment = false,
425
431
  ): void {
432
+ // A thread slot that was never filled can be filled by the checkpoint that settles the
433
+ // turn justifying it. Replacing an already selected thread stays a transition.
434
+ // The checkpoint constructor already refuses an id without its activation time, so
435
+ // exempting both fields together cannot smuggle a half-formed attachment through.
436
+ const attaching = allowInitialAttachment
437
+ && previous.internalSessionId === null
438
+ && candidate.internalSessionId !== null;
426
439
  const candidateRouting = {
427
440
  adapterId: candidate.adapterId,
428
441
  mode: candidate.mode,
429
- internalSessionId: candidate.internalSessionId,
430
- internalSessionActivatedAt: candidate.internalSessionActivatedAt,
442
+ internalSessionId: attaching ? null : candidate.internalSessionId,
443
+ internalSessionActivatedAt: attaching ? null : candidate.internalSessionActivatedAt,
431
444
  protocol: candidate.protocol,
432
445
  lastTransition: candidate.lastTransition ?? null,
433
446
  };
@@ -1,6 +1,9 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
  import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
3
3
  import type {
4
+ ConversationErrorDetails,
5
+ ConversationErrorRecoverability,
6
+ ConversationErrorSource,
4
7
  ConversationRecord,
5
8
  ConversationRecordKind,
6
9
  NewConversationRecord,
@@ -24,6 +27,7 @@ type SqlValue = string | number | bigint | boolean | Uint8Array | null;
24
27
 
25
28
  export function operationIdFromRecord(record: NewConversationRecord): string | null {
26
29
  if (record.kind === "metering") return record.operationId;
30
+ if (record.kind === "error") return record.operationId ?? null;
27
31
  if (!record.metadata) return null;
28
32
  try {
29
33
  const metadata = JSON.parse(record.metadata) as { operationId?: unknown };
@@ -194,6 +198,22 @@ export function insertConversationRecordDetail(
194
198
  record.status,
195
199
  );
196
200
  return;
201
+ case "error":
202
+ run(database,
203
+ `INSERT INTO conversation_error_records(
204
+ record_row_id, source, code, recoverability, message, transition_id,
205
+ internal_session_id, details_json
206
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
207
+ rowId,
208
+ record.source,
209
+ record.code,
210
+ record.recoverability,
211
+ record.message ?? null,
212
+ record.transitionId ?? null,
213
+ record.internalSessionId ?? null,
214
+ encodeJson(record.details as PersistenceJsonValue | undefined),
215
+ );
216
+ return;
197
217
  }
198
218
  }
199
219
 
@@ -240,6 +260,7 @@ const DETAIL_TABLES: Readonly<Record<ConversationRecordKind, string>> = Object.f
240
260
  thinking: "conversation_thinking_events",
241
261
  activity: "conversation_activity_events",
242
262
  metering: "conversation_metering_references",
263
+ error: "conversation_error_records",
243
264
  });
244
265
 
245
266
  function recordFromRows(
@@ -360,6 +381,23 @@ function recordFromRows(
360
381
  meteringRecordId: string(detail.metering_record_id),
361
382
  status: string(detail.status) as "available" | "partial" | "unavailable",
362
383
  });
384
+ case "error":
385
+ return Object.freeze({
386
+ ...envelope,
387
+ kind: "error",
388
+ source: string(detail.source) as ConversationErrorSource,
389
+ code: string(detail.code),
390
+ recoverability: string(detail.recoverability) as ConversationErrorRecoverability,
391
+ ...(detail.message !== null ? { message: string(detail.message) } : {}),
392
+ ...(row.operation_id !== null ? { operationId: string(row.operation_id) } : {}),
393
+ ...(detail.transition_id !== null ? { transitionId: string(detail.transition_id) } : {}),
394
+ ...(detail.internal_session_id !== null
395
+ ? { internalSessionId: string(detail.internal_session_id) }
396
+ : {}),
397
+ ...(detail.details_json !== null
398
+ ? { details: decodeJson(detail.details_json) as ConversationErrorDetails }
399
+ : {}),
400
+ });
363
401
  }
364
402
  }
365
403
 
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
 
3
- export const SQLITE_AGENT_SCHEMA_VERSION = 11;
3
+ export const SQLITE_AGENT_SCHEMA_VERSION = 12;
4
4
 
5
5
  const BASE_SCHEMA = `
6
6
  CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -65,7 +65,8 @@ CREATE TABLE IF NOT EXISTS conversation_records (
65
65
  'agent_action',
66
66
  'thinking',
67
67
  'activity',
68
- 'metering'
68
+ 'metering',
69
+ 'error'
69
70
  )),
70
71
  timestamp TEXT NOT NULL,
71
72
  operation_id TEXT,
@@ -210,6 +211,24 @@ CREATE TABLE IF NOT EXISTS conversation_metering_references (
210
211
  CREATE INDEX IF NOT EXISTS conversation_metering_operation_idx
211
212
  ON conversation_metering_references(operation_id, record_row_id);
212
213
 
214
+ CREATE TABLE IF NOT EXISTS conversation_error_records (
215
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
216
+ source TEXT NOT NULL CHECK (source IN (
217
+ 'provider_session', 'transport', 'operation', 'recovery'
218
+ )),
219
+ code TEXT NOT NULL CHECK (length(trim(code)) > 0),
220
+ recoverability TEXT NOT NULL CHECK (recoverability IN (
221
+ 'retryable', 'recoverable', 'terminal', 'unknown'
222
+ )),
223
+ message TEXT,
224
+ transition_id TEXT,
225
+ internal_session_id TEXT,
226
+ details_json TEXT CHECK (details_json IS NULL OR json_valid(details_json))
227
+ );
228
+
229
+ CREATE INDEX IF NOT EXISTS conversation_error_source_code_idx
230
+ ON conversation_error_records(source, code, record_row_id);
231
+
213
232
  CREATE TABLE IF NOT EXISTS conversation_checkpoints (
214
233
  agent_conversation_id TEXT PRIMARY KEY REFERENCES conversations(agent_conversation_id),
215
234
  revision INTEGER NOT NULL CHECK (revision >= 0),
@@ -518,58 +537,120 @@ END;
518
537
  `;
519
538
 
520
539
  export function migrateSqliteAgentSchema(database: Database): void {
521
- database.exec("BEGIN IMMEDIATE");
540
+ const hasMigrations = database.query<{ present: number }, []>(
541
+ "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
542
+ ).get() !== null;
543
+ const existing = hasMigrations
544
+ ? Number(database.query<{ version: number }, []>(
545
+ "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
546
+ ).get()?.version ?? 0)
547
+ : 0;
548
+ if (existing !== 0 && ![8, 9, 10, 11, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
549
+ throw new Error(
550
+ `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
551
+ );
552
+ }
553
+ // Admitting the `error` kind means rebuilding conversation_records: its kind CHECK is a
554
+ // closed list SQLite cannot alter in place. Foreign keys must be off for that drop, or
555
+ // the implicit delete would cascade into every detail table.
556
+ const rebuildRecords = existing > 0 && existing < 12;
557
+ if (rebuildRecords) database.exec("PRAGMA foreign_keys = OFF");
522
558
  try {
523
- const hasMigrations = database.query<{ present: number }, []>(
524
- "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
525
- ).get() !== null;
526
- if (hasMigrations) {
527
- const existing = Number(database.query<{ version: number }, []>(
559
+ database.exec("BEGIN IMMEDIATE");
560
+ try {
561
+ database.exec(BASE_SCHEMA);
562
+ const row = database.query<{ version: number }, []>(
528
563
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
529
- ).get()?.version ?? 0);
530
- if (existing !== 0 && existing !== 8 && existing !== 9 && existing !== 10
531
- && existing !== SQLITE_AGENT_SCHEMA_VERSION) {
532
- throw new Error(
533
- `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
534
- );
564
+ ).get();
565
+ const version = Number(row?.version ?? 0);
566
+ if (version > 0 && version < 10) {
567
+ database.exec(`ALTER TABLE conversation_messages ADD COLUMN consumer_metadata_json TEXT
568
+ CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json))`);
569
+ database.exec("ALTER TABLE conversations ADD COLUMN last_human_message_at TEXT");
570
+ database.exec(`UPDATE conversations SET last_human_message_at = (
571
+ SELECT r.timestamp FROM conversation_records r
572
+ JOIN conversation_messages m ON m.record_row_id = r.row_id
573
+ JOIN participants p ON p.participant_id = m.participant_id
574
+ WHERE r.agent_conversation_id = conversations.agent_conversation_id
575
+ AND r.kind = 'message' AND m.role = 'user' AND p.kind = 'user'
576
+ ORDER BY r.sequence DESC LIMIT 1
577
+ )`);
535
578
  }
579
+ if (version > 0 && version < 11) {
580
+ database.exec("ALTER TABLE conversation_messages ADD COLUMN logical_message_id TEXT");
581
+ }
582
+ database.exec(`CREATE INDEX IF NOT EXISTS conversation_messages_logical_idx
583
+ ON conversation_messages(logical_message_id, record_row_id)
584
+ WHERE logical_message_id IS NOT NULL`);
585
+ if (version > 0 && version < 12) {
586
+ rebuildConversationRecordsForErrorKind(database);
587
+ const violations = database.query<Record<string, unknown>, []>("PRAGMA foreign_key_check").all();
588
+ if (violations.length > 0) {
589
+ throw new Error("SQLite schema migration to version 12 left foreign key violations");
590
+ }
591
+ }
592
+ if (version < SQLITE_AGENT_SCHEMA_VERSION) {
593
+ database.query<unknown, [number, string]>(
594
+ "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
595
+ ).run(SQLITE_AGENT_SCHEMA_VERSION, new Date().toISOString());
596
+ }
597
+ database.exec("COMMIT");
598
+ } catch (error) {
599
+ if (database.inTransaction) database.exec("ROLLBACK");
600
+ throw error;
536
601
  }
537
- database.exec(BASE_SCHEMA);
538
- const row = database.query<{ version: number }, []>(
539
- "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
540
- ).get();
541
- const version = Number(row?.version ?? 0);
542
- if (version > 0 && version < 10) {
543
- database.exec(`ALTER TABLE conversation_messages ADD COLUMN consumer_metadata_json TEXT
544
- CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json))`);
545
- database.exec("ALTER TABLE conversations ADD COLUMN last_human_message_at TEXT");
546
- database.exec(`UPDATE conversations SET last_human_message_at = (
547
- SELECT r.timestamp FROM conversation_records r
548
- JOIN conversation_messages m ON m.record_row_id = r.row_id
549
- JOIN participants p ON p.participant_id = m.participant_id
550
- WHERE r.agent_conversation_id = conversations.agent_conversation_id
551
- AND r.kind = 'message' AND m.role = 'user' AND p.kind = 'user'
552
- ORDER BY r.sequence DESC LIMIT 1
553
- )`);
554
- }
555
- if (version > 0 && version < 11) {
556
- database.exec("ALTER TABLE conversation_messages ADD COLUMN logical_message_id TEXT");
557
- }
558
- database.exec(`CREATE INDEX IF NOT EXISTS conversation_messages_logical_idx
559
- ON conversation_messages(logical_message_id, record_row_id)
560
- WHERE logical_message_id IS NOT NULL`);
561
- if (version < SQLITE_AGENT_SCHEMA_VERSION) {
562
- database.query<unknown, [number, string]>(
563
- "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
564
- ).run(SQLITE_AGENT_SCHEMA_VERSION, new Date().toISOString());
565
- }
566
- database.exec("COMMIT");
567
- } catch (error) {
568
- if (database.inTransaction) database.exec("ROLLBACK");
569
- throw error;
602
+ } finally {
603
+ if (rebuildRecords) database.exec("PRAGMA foreign_keys = ON");
570
604
  }
571
605
  }
572
606
 
607
+ /**
608
+ * Rebuild `conversation_records` so its `kind` CHECK admits `error`.
609
+ *
610
+ * Row ids are copied verbatim, so every detail table's `record_row_id` reference survives
611
+ * the swap. The caller runs this with foreign keys disabled and verifies with
612
+ * `PRAGMA foreign_key_check` afterward.
613
+ */
614
+ function rebuildConversationRecordsForErrorKind(database: Database): void {
615
+ database.exec(`CREATE TABLE conversation_records_v12 (
616
+ row_id INTEGER PRIMARY KEY,
617
+ record_id TEXT NOT NULL UNIQUE,
618
+ agent_session_id TEXT NOT NULL,
619
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
620
+ sequence INTEGER NOT NULL CHECK (sequence > 0),
621
+ kind TEXT NOT NULL CHECK (kind IN (
622
+ 'message',
623
+ 'tool_call',
624
+ 'permission',
625
+ 'configuration',
626
+ 'protocol',
627
+ 'native_action',
628
+ 'agent_action',
629
+ 'thinking',
630
+ 'activity',
631
+ 'metering',
632
+ 'error'
633
+ )),
634
+ timestamp TEXT NOT NULL,
635
+ operation_id TEXT,
636
+ metadata TEXT,
637
+ UNIQUE (agent_conversation_id, sequence)
638
+ )`);
639
+ database.exec(`INSERT INTO conversation_records_v12(
640
+ row_id, record_id, agent_session_id, agent_conversation_id, sequence, kind, timestamp, operation_id, metadata
641
+ ) SELECT row_id, record_id, agent_session_id, agent_conversation_id, sequence, kind, timestamp, operation_id, metadata
642
+ FROM conversation_records`);
643
+ database.exec("DROP TABLE conversation_records");
644
+ database.exec("ALTER TABLE conversation_records_v12 RENAME TO conversation_records");
645
+ database.exec(`CREATE INDEX IF NOT EXISTS conversation_records_kind_idx
646
+ ON conversation_records(agent_conversation_id, kind, sequence)`);
647
+ database.exec(`CREATE INDEX IF NOT EXISTS conversation_records_time_idx
648
+ ON conversation_records(timestamp, agent_conversation_id)`);
649
+ database.exec(`CREATE INDEX IF NOT EXISTS conversation_records_operation_idx
650
+ ON conversation_records(agent_conversation_id, operation_id, sequence)
651
+ WHERE operation_id IS NOT NULL`);
652
+ }
653
+
573
654
  export function installSqliteFts(database: Database): boolean {
574
655
  const row = database.query<{ enabled: number }, []>(
575
656
  "SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled",
@@ -135,6 +135,9 @@ export class RegistryPersistenceRuntime implements PersistenceStateRuntime {
135
135
  ts = Date.now(),
136
136
  ): Promise<AgentSessionCheckpoint> {
137
137
  const active = this.requireActive();
138
+ if (changes.providerAttachment && this.current.internalSessionId !== null) {
139
+ throw new Error("replacing a selected provider thread is a transition, not a terminal checkpoint change");
140
+ }
138
141
  this.current = nextCheckpoint(this.current, {
139
142
  ...changes,
140
143
  boundary: changes.boundary ?? { status: "settled", lastSettledOperationId: active.operationId },
@@ -180,6 +183,10 @@ function nextCheckpoint(
180
183
  ...(changes.model === undefined ? {} : { model: changes.model }),
181
184
  ...(changes.sessionConfiguration === undefined ? {} : { sessionConfiguration: changes.sessionConfiguration }),
182
185
  ...(changes.metering === undefined ? {} : { metering: changes.metering }),
186
+ ...(changes.providerAttachment === undefined ? {} : {
187
+ internalSessionId: changes.providerAttachment.internalSessionId,
188
+ internalSessionActivatedAt: changes.providerAttachment.activatedAt,
189
+ }),
183
190
  stateRevision: source.stateRevision + 1,
184
191
  boundary: changes.boundary ?? source.boundary,
185
192
  updatedAt: new Date(ts).toISOString(),
@@ -43,6 +43,18 @@ export interface TranscriptTerminalCheckpointChanges {
43
43
  readonly sessionConfiguration?: SessionConfigurationCheckpoint;
44
44
  readonly metering?: AgentSessionCheckpoint["metering"];
45
45
  readonly boundary?: AgentSessionBoundary;
46
+ /**
47
+ * Fill in a thread slot the conversation never had.
48
+ *
49
+ * A newly created provider thread is kept in memory until a completed turn justifies
50
+ * selecting it for a later resume; the turn's own terminal checkpoint is what records
51
+ * it, so the response and the thread it came from commit together. Replacing an already
52
+ * selected thread is a transition and is rejected here.
53
+ */
54
+ readonly providerAttachment?: {
55
+ readonly internalSessionId: string;
56
+ readonly activatedAt: string;
57
+ };
46
58
  }
47
59
 
48
60
  type NormalizedTransitionEvent = Extract<NormalizedPersistenceEvent, { kind: "transition" }>;
@@ -452,6 +464,11 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
452
464
  ): Promise<AgentSessionCheckpoint> {
453
465
  this.assertUsable();
454
466
  const active = this.requireActive();
467
+ if (changes.providerAttachment && this._checkpoint.internalSessionId !== null) {
468
+ throw new TranscriptRuntimeStateError(
469
+ "replacing a selected provider thread is a transition, not a terminal checkpoint change",
470
+ );
471
+ }
455
472
  const terminal: TranscriptOperationRecord = {
456
473
  ...this.envelope(this.writer.nextSequence, ts),
457
474
  t: "operation",
@@ -469,6 +486,10 @@ export class TranscriptPersistenceRuntime implements PersistenceStateRuntime {
469
486
  ? {}
470
487
  : { sessionConfiguration: structuredClone(changes.sessionConfiguration) }),
471
488
  ...(changes.metering === undefined ? {} : { metering: structuredClone(changes.metering) }),
489
+ ...(changes.providerAttachment === undefined ? {} : {
490
+ internalSessionId: changes.providerAttachment.internalSessionId,
491
+ internalSessionActivatedAt: changes.providerAttachment.activatedAt,
492
+ }),
472
493
  stateRevision: this._checkpoint.stateRevision + 1,
473
494
  transcript: { ...this._checkpoint.transcript!, coveredSequence: terminal.seq },
474
495
  boundary: changes.boundary ?? { status: "settled", lastSettledOperationId: active.operationId },