@qlairoslabs/acp-client 0.10.1 → 0.11.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 (42) hide show
  1. package/CONSUMER_GUIDE.md +252 -0
  2. package/README.md +0 -3
  3. package/package.json +1 -1
  4. package/src/agent/adoption/config.ts +57 -0
  5. package/src/agent/adoption/index.ts +8 -0
  6. package/src/agent/adoption/provider-session-delete.ts +27 -0
  7. package/src/agent/adoption/provider-sessions.ts +73 -0
  8. package/src/agent/adoption/recap.ts +15 -0
  9. package/src/agent/adoption/replay.ts +84 -0
  10. package/src/agent/config.ts +182 -0
  11. package/src/agent/conversation-manager.ts +1006 -0
  12. package/src/agent/manager-settings.ts +46 -0
  13. package/src/agent/persisted-lifecycle.ts +309 -0
  14. package/src/agent/persistence-policy/index.ts +8 -0
  15. package/src/agent/persistence-policy/resolver.ts +118 -0
  16. package/src/agent/persistence-policy/types.ts +50 -0
  17. package/src/agent/record-capture.ts +243 -0
  18. package/src/agent-conversation-contracts.ts +11 -0
  19. package/src/agent-conversation-errors.ts +24 -0
  20. package/src/agent-conversation-owner.ts +7 -0
  21. package/src/agent-conversation-queue.ts +23 -0
  22. package/src/agent-session.ts +236 -66
  23. package/src/agent.ts +63 -1223
  24. package/src/audit/config.ts +29 -0
  25. package/src/audit/index.ts +1 -0
  26. package/src/checkpointing/contracts.ts +2 -0
  27. package/src/checkpointing/persistence/sqlite-repository.ts +13 -0
  28. package/src/checkpointing/strategy.ts +11 -5
  29. package/src/client.ts +25 -2
  30. package/src/controller.ts +3 -0
  31. package/src/index.ts +24 -0
  32. package/src/internal-inference/contracts.ts +23 -0
  33. package/src/internal-inference/coordination/manager.ts +22 -8
  34. package/src/persistence/backend.ts +17 -0
  35. package/src/persistence/sqlite-backend.ts +30 -4
  36. package/src/persistence/sqlite-provider-sessions.ts +35 -0
  37. package/src/persistence/sqlite-schema.ts +13 -3
  38. package/src/steering/combine.ts +56 -0
  39. package/src/steering/contracts.ts +84 -0
  40. package/src/steering/controller.ts +205 -0
  41. package/src/steering/index.ts +14 -0
  42. package/src/transport/acp-transport.ts +11 -0
@@ -188,3 +188,32 @@ function safeInteger(value: number, minimum: number, label: string): number {
188
188
  }
189
189
  return value;
190
190
  }
191
+
192
+ /** Audit kinds observed at agent scope. A conversation cannot tune them: they are not about one conversation. */
193
+ const AGENT_SCOPE_AUDIT_KINDS = new Set(["agent_lifecycle", "identity", "internal_inference"]);
194
+
195
+ /**
196
+ * The audit configuration one conversation runs with: the Agent's destination and delivery settings
197
+ * unchanged, with its capture layered over by the conversation's override (keys the override sets replace
198
+ * the Agent's; omitted keys follow the Agent). The result carries its own fingerprint, so an entry says which
199
+ * policy projected it. An override that changes nothing returns the Agent's configuration itself.
200
+ */
201
+ export function resolveConversationAuditConfig(
202
+ base: ResolvedAgentAuditLogConfig,
203
+ baseCapture: AgentAuditCaptureConfig | undefined,
204
+ override: AgentAuditCaptureConfig,
205
+ ): ResolvedAgentAuditLogConfig {
206
+ for (const key of Object.keys(override)) {
207
+ if (AGENT_SCOPE_AUDIT_KINDS.has(key)) {
208
+ throw new Error(`conversation audit capture cannot select agent-scope kind: ${key}`);
209
+ }
210
+ }
211
+ const capture = resolveAgentAuditCapture({ ...baseCapture, ...override });
212
+ const captureFingerprint = sha256CanonicalJson({
213
+ projectionSchemaVersion: 1,
214
+ capture,
215
+ limits: DEFAULT_PERSISTENCE_LIMITS,
216
+ });
217
+ if (captureFingerprint === base.captureFingerprint) return base;
218
+ return Object.freeze({ ...base, capture, captureFingerprint });
219
+ }
@@ -4,6 +4,7 @@ export {
4
4
  DEFAULT_AUDIT_ROTATION,
5
5
  DEFAULT_AUDIT_SHUTDOWN_GRACE_MS,
6
6
  resolveAgentAuditCapture,
7
+ resolveConversationAuditConfig,
7
8
  resolveAgentAuditLogConfig,
8
9
  } from "./config.ts";
9
10
  export type {
@@ -42,4 +42,6 @@ export interface ConversationRecoveryCheckpointRepository {
42
42
  options?: ConversationRecoveryCheckpointListOptions,
43
43
  ): Promise<readonly ConversationRecoveryCheckpoint[]>;
44
44
  publish(input: PublishConversationRecoveryCheckpointInput): Promise<ConversationRecoveryCheckpoint>;
45
+ /** Delete every checkpoint of a conversation. Returns how many. Optional. */
46
+ deleteForConversation?(agentConversationId: AgentConversationId): Promise<number>;
45
47
  }
@@ -49,6 +49,19 @@ implements ConversationRecoveryCheckpointRepository {
49
49
  return Number(row?.sequence ?? 0);
50
50
  }
51
51
 
52
+ async deleteForConversation(agentConversationId: AgentConversationId): Promise<number> {
53
+ return await this.runWrite(() => {
54
+ const count = this.database.query<{ n: number }, [string]>(
55
+ "SELECT COUNT(*) AS n FROM conversation_recovery_checkpoints WHERE agent_conversation_id = ?",
56
+ ).get(agentConversationId)?.n ?? 0;
57
+ // One statement: the checkpoints reference each other (previous_checkpoint_id), and a single DELETE
58
+ // checks that reference after all of them are gone.
59
+ this.database.query("DELETE FROM conversation_recovery_checkpoints WHERE agent_conversation_id = ?")
60
+ .run(agentConversationId);
61
+ return Number(count);
62
+ });
63
+ }
64
+
52
65
  async latest(agentConversationId: AgentConversationId): Promise<ConversationRecoveryCheckpoint | null> {
53
66
  const row = this.database.query<CheckpointRow, [string]>(
54
67
  `SELECT * FROM conversation_recovery_checkpoints
@@ -79,23 +79,29 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
79
79
  generatorInternalInferenceId: result.internalInferenceId,
80
80
  summary,
81
81
  });
82
- const appended = await context.persistence.records.append({
82
+ const record = {
83
83
  recordId: `${result.internalInferenceId}:checkpoint`,
84
84
  agentSessionId: context.attempt.agentSessionId,
85
85
  agentConversationId: conversationId,
86
- kind: "native_action",
86
+ kind: "native_action" as const,
87
87
  timestamp: checkpoint.createdAt,
88
88
  action: "conversation_checkpoint",
89
- state: "completed",
89
+ state: "completed" as const,
90
90
  output: {
91
91
  internalInferenceId: result.internalInferenceId,
92
92
  checkpointId: checkpoint.checkpointId,
93
93
  coveredSequence: checkpoint.coveredSequence,
94
94
  },
95
- });
95
+ };
96
+ // Under the conversation's capture and audit policy when the Agent supplies one: the record is stored at
97
+ // the conversation's `native_action` level (or dropped) and audited as the conversation says. Without
98
+ // one it is appended as it always was.
99
+ const appended = context.appendRecord
100
+ ? await context.appendRecord(record)
101
+ : await context.persistence.records.append(record);
96
102
  // Hand the committed record to the manager so it reaches the Agent's live bus after
97
103
  // the completion transaction commits, exactly like every other Agent-owned record.
98
- context.onRecordAppended?.(appended);
104
+ if (appended) context.onRecordAppended?.(appended);
99
105
  return Object.freeze({
100
106
  internalInferenceId: result.internalInferenceId,
101
107
  rootInternalInferenceId: context.attempt.rootId,
package/src/client.ts CHANGED
@@ -134,6 +134,11 @@ export interface StartSessionOptions {
134
134
  loadFailure?: SessionLoadFailure;
135
135
  /** MCP servers bound at session creation. */
136
136
  mcpServers?: schema.McpServer[];
137
+ /**
138
+ * Raw `session/update` notifications of the history a loaded session replays. Without it the replay is
139
+ * dropped: it arrives before the load returns and belongs to no turn.
140
+ */
141
+ onReplayUpdate?: (notification: unknown) => void;
137
142
  }
138
143
 
139
144
  export type SessionLoadFailure = "error" | "new";
@@ -401,7 +406,10 @@ export class AcpClient implements AgentClient {
401
406
 
402
407
  if (resumeId && this.capabilities.agent.loadSession) {
403
408
  try {
404
- const result = await this.loadSessionInternal(transport, resumeId, { mcpServers });
409
+ const result = await this.loadSessionInternal(transport, resumeId, {
410
+ mcpServers,
411
+ ...(options.onReplayUpdate ? { onUpdate: options.onReplayUpdate } : {}),
412
+ });
405
413
  sessionId = result.sessionId;
406
414
  resumed = result.resumed;
407
415
  } catch (err) {
@@ -499,6 +507,19 @@ export class AcpClient implements AgentClient {
499
507
  return { sessionId, resumed: true };
500
508
  }
501
509
 
510
+ /**
511
+ * Ask the agent to delete a session it holds (`session/delete`), when advertised. This is the provider's own
512
+ * deletion: it does not touch any local record, and not every provider offers it.
513
+ */
514
+ async deleteSession(sessionId: string): Promise<void> {
515
+ const transport = this.requireTransport();
516
+ if (!this.capabilities.agent.sessionCapabilities.delete) {
517
+ throw new Error("agent does not advertise session/delete (sessionCapabilities.delete)");
518
+ }
519
+ await transport.deleteSession({ sessionId } as schema.DeleteSessionRequest);
520
+ this.log.info("session_deleted", { sessionId });
521
+ }
522
+
502
523
  /** Fork an existing session and switch this client to the newly-created fork. */
503
524
  async forkSession(
504
525
  sessionId: string,
@@ -720,7 +741,9 @@ export class AcpClient implements AgentClient {
720
741
  } as schema.PromptRequest);
721
742
  this.log.debug("prompt_response", { response: res });
722
743
 
723
- const cancelled = this.active.cancelled;
744
+ // What the provider reported, not what we asked for: a cancel can lose the race with a normal
745
+ // ending, and the turn is then complete, not cancelled.
746
+ const cancelled = res.stopReason === "cancelled";
724
747
  const text = this.active.response.text;
725
748
  const messages = this.active.response.snapshot();
726
749
  // ACP usage is optional and experimental: validate rather than cast. An
package/src/controller.ts CHANGED
@@ -51,6 +51,8 @@ export interface AgentControllerConfig {
51
51
  sessionId?: string;
52
52
  /** Policy when sessionId cannot be loaded. Default "new" for compatibility. */
53
53
  sessionLoadFailure?: SessionLoadFailure;
54
+ /** Receives the history a loaded `sessionId` replays (raw `session/update` notifications). */
55
+ onSessionReplay?: (notification: unknown) => void;
54
56
  /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
55
57
  mcpServers?: schema.McpServer[];
56
58
  defaultPermission?: "approve" | "cancel";
@@ -508,6 +510,7 @@ export class AgentController implements AgentClient {
508
510
  result = await client.startSession({
509
511
  mcpServers: this.config.mcpServers,
510
512
  loadFailure: this.config.sessionLoadFailure,
513
+ ...(this.config.onSessionReplay ? { onReplayUpdate: this.config.onSessionReplay } : {}),
511
514
  });
512
515
  } catch (err) {
513
516
  if (sessionId && this.config.sessionLoadFailure === "error") {
package/src/index.ts CHANGED
@@ -44,6 +44,18 @@ export type {
44
44
  CreateAgentConversationConfig,
45
45
  OpenAgentConversationConfig,
46
46
  OpenOwnedAgentConversationResult,
47
+ AdoptProviderSessionConfig,
48
+ ClearTranscriptOptions,
49
+ ClearTranscriptResult,
50
+ DeleteConversationOptions,
51
+ DeleteConversationResult,
52
+ ListProviderSessionsOptions,
53
+ ProviderSessionSummary,
54
+ AgentConversationAuditCaptureConfig,
55
+ AgentConversationPersistenceOverride,
56
+ AgentScopeAuditObservationKind,
57
+ ConversationPersistenceContext,
58
+ ConversationPersistenceResolver,
47
59
  } from "./agent.ts";
48
60
  export {
49
61
  OUT_OF_BAND_MESSAGE_ORIGIN,
@@ -180,6 +192,8 @@ export {
180
192
  ContinuationUnavailableError,
181
193
  DirectAuditPersistenceUnsupportedError,
182
194
  ProviderSessionError,
195
+ ProviderSessionInUseError,
196
+ ProviderSessionListUnsupportedError,
183
197
  } from "./agent-session.ts";
184
198
  export type { ProviderSessionErrorDetails } from "./agent-session.ts";
185
199
  export type {
@@ -254,6 +268,16 @@ export type { TerminalHandlers } from "./transport/acp-transport.ts";
254
268
 
255
269
  export { extractChunkText, extractResponseChunk, toActivityEvent } from "./updates.ts";
256
270
  export { formatResponseMessages } from "./response.ts";
271
+ export type {
272
+ MessageDeliveryVia,
273
+ MessageEvent,
274
+ PendingMessage,
275
+ PendingMessageId,
276
+ PromptDelivery,
277
+ PromptEndedBy,
278
+ PromptHandle,
279
+ PromptPart,
280
+ } from "./steering/index.ts";
257
281
 
258
282
  export {
259
283
  ActivityAggregator,
@@ -4,6 +4,8 @@ import type { OperationMeteringRecord, OperationOutcome } from "../metering/reco
4
4
  import type { StatefulSubscribable, Subscribable } from "../observation/contracts.ts";
5
5
  import type {
6
6
  ConversationRecord,
7
+ MeteringRecordRetention,
8
+ NewConversationRecord,
7
9
  PersistenceJsonValue,
8
10
  PersistenceScope,
9
11
  } from "../persistence/backend.ts";
@@ -201,6 +203,21 @@ export interface InternalInferencePreparationContext {
201
203
  readonly signal?: AbortSignal;
202
204
  }
203
205
 
206
+ /**
207
+ * What one conversation persists, for the writes an internal inference makes about it. Resolved before the
208
+ * inference runs, so a policy that cannot be resolved fails the attempt instead of writing under defaults.
209
+ */
210
+ export interface ConversationWritePolicy {
211
+ /** Retention of the detailed metering record of this conversation's inferences. */
212
+ readonly meteringRecords: MeteringRecordRetention;
213
+ /**
214
+ * Append a canonical record as the conversation's capture and audit policy say: it is stored at its capture
215
+ * level (or dropped, when the level is `none`) and its audit entry is queued, in the given transaction.
216
+ * Returns the stored record, or `undefined` when capture dropped it.
217
+ */
218
+ appendRecord(persistence: PersistenceScope, record: NewConversationRecord): Promise<ConversationRecord | undefined>;
219
+ }
220
+
204
221
  export interface InternalInferenceCompletionContext {
205
222
  readonly attempt: InternalInferenceSnapshot;
206
223
  /** Transaction-scoped persistence used to publish the purpose artifact atomically. */
@@ -213,6 +230,12 @@ export interface InternalInferenceCompletionContext {
213
230
  * simply do not call it.
214
231
  */
215
232
  readonly onRecordAppended?: (record: ConversationRecord) => void;
233
+ /**
234
+ * Append a canonical record about the attempt's conversation under that conversation's capture and audit
235
+ * policy, inside this completion transaction. Absent when the Agent has no per-conversation policy to
236
+ * apply, in which case a strategy appends through `persistence.records` as before.
237
+ */
238
+ readonly appendRecord?: (record: NewConversationRecord) => Promise<ConversationRecord | undefined>;
216
239
  }
217
240
 
218
241
  export interface InternalInferenceStrategy<TPayload = PersistenceJsonValue> {
@@ -42,6 +42,13 @@ export interface DefaultInternalInferenceManagerConfig {
42
42
  session: { readonly internalSessionId: string; readonly model: string | null },
43
43
  ) => Promise<InternalInferenceMeteringOperation | null>;
44
44
  readonly meteringRecords?: import("../../persistence/backend.ts").MeteringRecordRetention;
45
+ /**
46
+ * What a conversation persists, asked for before an attempt about that conversation runs. A failure here
47
+ * fails the attempt through the normal retry rules; nothing is written under the Agent's defaults.
48
+ */
49
+ readonly resolveConversationWrites?: (
50
+ agentConversationId: NonNullable<InternalInferenceSnapshot["agentConversationId"]>,
51
+ ) => Promise<import("../contracts.ts").ConversationWritePolicy>;
45
52
  readonly pollIntervalMs?: number;
46
53
  /**
47
54
  * Observe canonical records appended by a strategy's completion, after the transaction
@@ -225,6 +232,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
225
232
  ): Promise<void> {
226
233
  let metering: InternalInferenceMeteringOperation | null = null;
227
234
  let meteringRecord: OperationMeteringRecord | null = null;
235
+ let writes: import("../contracts.ts").ConversationWritePolicy | undefined;
228
236
  const heartbeat = setInterval(() => {
229
237
  void this.config.repository.heartbeat(
230
238
  attempt.internalInferenceId,
@@ -240,6 +248,9 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
240
248
  attempt.input.version,
241
249
  );
242
250
  this.publishProgress(attempt.internalInferenceId, "preparing_input");
251
+ if (attempt.agentConversationId && this.config.resolveConversationWrites) {
252
+ writes = await this.config.resolveConversationWrites(attempt.agentConversationId);
253
+ }
243
254
  const payload = strategy.validatePayload(attempt.input.payload);
244
255
  const prepared = await strategy.prepare({
245
256
  attempt: snapshotOf(attempt),
@@ -289,6 +300,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
289
300
  attempt: snapshotOf(attempt),
290
301
  persistence,
291
302
  onRecordAppended: (record) => appended.push(record),
303
+ ...(writes ? { appendRecord: (record) => writes!.appendRecord(persistence, record) } : {}),
292
304
  }, result);
293
305
  if (this.fenced.has(attempt.internalInferenceId)) {
294
306
  throw new Error("internal inference was fenced during completion");
@@ -297,13 +309,13 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
297
309
  await persistence.metering.commit({
298
310
  agentConversationId: attempt.agentConversationId,
299
311
  record: meteringRecord,
300
- meteringRecords: this.config.meteringRecords ?? "all",
312
+ meteringRecords: writes?.meteringRecords ?? this.config.meteringRecords ?? "all",
301
313
  });
302
314
  } else if (meteringRecord) {
303
315
  await persistence.metering.commitAgent({
304
316
  agentSessionId: attempt.agentSessionId,
305
317
  record: meteringRecord,
306
- meteringRecords: this.config.meteringRecords ?? "all",
318
+ meteringRecords: writes?.meteringRecords ?? this.config.meteringRecords ?? "all",
307
319
  });
308
320
  }
309
321
  return await persistence.internalInferences!.complete({
@@ -332,9 +344,9 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
332
344
  .catch(() => null);
333
345
  }
334
346
  if (this.closed && abort.signal.aborted) {
335
- await this.recordShutdownInterruption(attempt, leaseToken, error, meteringRecord);
347
+ await this.recordShutdownInterruption(attempt, leaseToken, error, meteringRecord, writes?.meteringRecords);
336
348
  } else {
337
- await this.recordFailure(attempt, leaseToken, error, meteringRecord);
349
+ await this.recordFailure(attempt, leaseToken, error, meteringRecord, writes?.meteringRecords);
338
350
  }
339
351
  } finally {
340
352
  clearInterval(heartbeat);
@@ -349,6 +361,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
349
361
  leaseToken: string,
350
362
  error: unknown,
351
363
  meteringRecord: OperationMeteringRecord | null,
364
+ retention?: import("../../persistence/backend.ts").MeteringRecordRetention,
352
365
  ): Promise<void> {
353
366
  const canRetry = attempt.attemptNumber < this.config.settings.retry.maxAttempts;
354
367
  await this.config.persistence.transaction(async (persistence) => {
@@ -356,13 +369,13 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
356
369
  await persistence.metering.commit({
357
370
  agentConversationId: attempt.agentConversationId,
358
371
  record: meteringRecord,
359
- meteringRecords: this.config.meteringRecords ?? "all",
372
+ meteringRecords: retention ?? this.config.meteringRecords ?? "all",
360
373
  });
361
374
  } else if (meteringRecord) {
362
375
  await persistence.metering.commitAgent({
363
376
  agentSessionId: attempt.agentSessionId,
364
377
  record: meteringRecord,
365
- meteringRecords: this.config.meteringRecords ?? "all",
378
+ meteringRecords: retention ?? this.config.meteringRecords ?? "all",
366
379
  });
367
380
  }
368
381
  await persistence.internalInferences!.fail({
@@ -381,6 +394,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
381
394
  leaseToken: string,
382
395
  error: unknown,
383
396
  meteringRecord: OperationMeteringRecord | null,
397
+ retention?: import("../../persistence/backend.ts").MeteringRecordRetention,
384
398
  ): Promise<void> {
385
399
  const strategy = this.registry.get(attempt.purpose, attempt.input.strategyId, attempt.input.version);
386
400
  const disposition = strategy?.classifyError(error) ?? { kind: "terminal" as const, code: "unknown_strategy" };
@@ -392,13 +406,13 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
392
406
  await persistence.metering.commit({
393
407
  agentConversationId: attempt.agentConversationId,
394
408
  record: meteringRecord,
395
- meteringRecords: this.config.meteringRecords ?? "all",
409
+ meteringRecords: retention ?? this.config.meteringRecords ?? "all",
396
410
  });
397
411
  } else if (meteringRecord) {
398
412
  await persistence.metering.commitAgent({
399
413
  agentSessionId: attempt.agentSessionId,
400
414
  record: meteringRecord,
401
- meteringRecords: this.config.meteringRecords ?? "all",
415
+ meteringRecords: retention ?? this.config.meteringRecords ?? "all",
402
416
  });
403
417
  }
404
418
  return await persistence.internalInferences!.fail({
@@ -269,6 +269,10 @@ export interface AgentConversationSummary {
269
269
  readonly latestSequence: number;
270
270
  readonly deletedAt?: string;
271
271
  readonly metadata?: string;
272
+ /** True when the conversation was created by adopting an existing provider session. Absent otherwise. */
273
+ readonly adopted?: boolean;
274
+ /** The provider session an adoption asked for, kept so a failed adoption can be retried. */
275
+ readonly adoptProviderSessionId?: string;
272
276
  }
273
277
 
274
278
  export interface CreateAgentConversationInput {
@@ -278,6 +282,8 @@ export interface CreateAgentConversationInput {
278
282
  readonly title?: string;
279
283
  readonly createdAt?: string;
280
284
  readonly metadata?: string;
285
+ /** Mark the conversation as created by adopting this provider session. */
286
+ readonly adoptProviderSessionId?: string;
281
287
  }
282
288
 
283
289
  export interface ConversationListOptions {
@@ -512,6 +518,11 @@ export interface ConversationRecordPersistence {
512
518
  agentConversationId: AgentConversationId,
513
519
  options?: RecordListOptions,
514
520
  ): Promise<ConversationRecordPage>;
521
+ /**
522
+ * Physically delete every record of a conversation, keeping the conversation itself. Returns how many were
523
+ * deleted. Sequence numbers are not reused. Optional: an append-only backend cannot clear a transcript.
524
+ */
525
+ deleteForConversation?(agentConversationId: AgentConversationId): Promise<number>;
515
526
  /** Optional efficient newest-first history API. Use list(afterSequence) for live catch-up. */
516
527
  listRecent?(
517
528
  agentConversationId: AgentConversationId,
@@ -538,6 +549,12 @@ export interface ProviderSessionPersistence {
538
549
  append(record: ProviderSessionRecord): Promise<void>;
539
550
  list(agentConversationId: AgentConversationId): Promise<readonly ProviderSessionRecord[]>;
540
551
  active(agentConversationId: AgentConversationId): Promise<ProviderSessionRecord | null>;
552
+ /**
553
+ * Conversations that own this provider session: those where it is the active session, and those
554
+ * that asked to adopt it and have not attached it yet. Deleted conversations do not count.
555
+ * Optional: a backend without it cannot refuse a second adoption of the same session.
556
+ */
557
+ conversationsUsing?(internalSessionId: string): Promise<readonly AgentConversationId[]>;
541
558
  }
542
559
 
543
560
  export type MeteringRecordRetention = "all" | "none" | { readonly retain: number };
@@ -74,6 +74,7 @@ import {
74
74
  import type { OperationMeteringRecord } from "../metering/record.ts";
75
75
  import type { AgentSessionMeteringState } from "../metering/state.ts";
76
76
  import { installSqliteFts, migrateSqliteAgentSchema } from "./sqlite-schema.ts";
77
+ import { conversationsUsingProviderSession } from "./sqlite-provider-sessions.ts";
77
78
  import { SqliteInternalInferenceRepository } from "../internal-inference/persistence/sqlite-repository.ts";
78
79
  import type { InternalInferenceRepository } from "../internal-inference/persistence/repository.ts";
79
80
  import type { ConversationRecoveryCheckpointRepository } from "../checkpointing/contracts.ts";
@@ -101,6 +102,8 @@ interface ConversationRow {
101
102
  last_human_message_at: string | null;
102
103
  deleted_at: string | null;
103
104
  metadata: string | null;
105
+ adopted: number;
106
+ adopt_provider_session_id: string | null;
104
107
  }
105
108
 
106
109
  interface IdentityRow {
@@ -420,14 +423,17 @@ class SqliteConversationPersistence implements ConversationPersistence {
420
423
  assertInstant(now, "conversation createdAt");
421
424
  runSql(this.database,
422
425
  `INSERT INTO conversations(
423
- agent_conversation_id, agent_session_id, title, created_at, updated_at, metadata
424
- ) VALUES (?, ?, ?, ?, ?, ?)`,
426
+ agent_conversation_id, agent_session_id, title, created_at, updated_at, metadata,
427
+ adopted, adopt_provider_session_id
428
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
425
429
  input.agentConversationId,
426
430
  input.agentSessionId,
427
431
  input.title ?? null,
428
432
  now,
429
433
  now,
430
434
  input.metadata ?? null,
435
+ input.adoptProviderSessionId === undefined ? 0 : 1,
436
+ input.adoptProviderSessionId ?? null,
431
437
  );
432
438
  const participants = input.participants?.length
433
439
  ? input.participants
@@ -623,6 +629,19 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
623
629
  return Object.freeze(appended);
624
630
  }
625
631
 
632
+ async deleteForConversation(agentConversationId: AgentConversationId): Promise<number> {
633
+ return await this.runWrite(() => {
634
+ requireConversation(this.database, agentConversationId);
635
+ // Counted first: the changes count of a DELETE also includes the detail rows and full-text entries
636
+ // that go with each record (ON DELETE CASCADE and triggers), which are not records.
637
+ const count = this.database.query<{ n: number }, [string]>(
638
+ "SELECT COUNT(*) AS n FROM conversation_records WHERE agent_conversation_id = ?",
639
+ ).get(agentConversationId)?.n ?? 0;
640
+ this.database.query("DELETE FROM conversation_records WHERE agent_conversation_id = ?").run(agentConversationId);
641
+ return Number(count);
642
+ });
643
+ }
644
+
626
645
  async get(recordId: string): Promise<ConversationRecord | null> {
627
646
  const row = this.database.query<ConversationRecordRow, [string]>(
628
647
  "SELECT * FROM conversation_records WHERE record_id = ?",
@@ -946,6 +965,10 @@ class SqliteProviderSessionPersistence implements ProviderSessionPersistence {
946
965
  ).get(agentConversationId);
947
966
  return row ? providerSessionFromRow(row) : null;
948
967
  }
968
+
969
+ async conversationsUsing(internalSessionId: string): Promise<readonly AgentConversationId[]> {
970
+ return conversationsUsingProviderSession(this.database, internalSessionId);
971
+ }
949
972
  }
950
973
 
951
974
  class SqliteMeteringPersistence implements MeteringPersistence {
@@ -1703,11 +1726,12 @@ class SqliteAuditOutboxPersistence implements AuditOutboxPersistence {
1703
1726
  item.createdAt,
1704
1727
  );
1705
1728
  runSql(this.database,
1729
+ // The state's fingerprint is the Agent's base policy and only `initialize` writes it: an entry
1730
+ // carries the fingerprint of the policy that projected it, which a conversation's override changes.
1706
1731
  `UPDATE agent_audit_state
1707
- SET last_allocated_sequence = ?, capture_fingerprint = ?, updated_at = ?
1732
+ SET last_allocated_sequence = ?, updated_at = ?
1708
1733
  WHERE singleton = 1`,
1709
1734
  auditSequence,
1710
- item.captureFingerprint,
1711
1735
  item.createdAt,
1712
1736
  );
1713
1737
  return auditOutboxFromRow(this.database.query<Record<string, unknown>, [string]>(
@@ -1898,6 +1922,8 @@ function summaryFromRowWithParticipants(
1898
1922
  updatedAt: row.updated_at,
1899
1923
  latestSequence: Number(row.latest_sequence),
1900
1924
  ...(row.deleted_at !== null ? { deletedAt: row.deleted_at } : {}),
1925
+ ...(row.adopted ? { adopted: true } : {}),
1926
+ ...(row.adopt_provider_session_id !== null ? { adoptProviderSessionId: row.adopt_provider_session_id } : {}),
1901
1927
  ...(row.metadata !== null ? { metadata: row.metadata } : {}),
1902
1928
  });
1903
1929
  }
@@ -0,0 +1,35 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import type { AgentConversationId } from "../agent-ids.ts";
3
+
4
+ /**
5
+ * Conversations that own a provider session: the one it is active in, and the ones that asked to adopt it and
6
+ * have not attached it yet (an adoption that failed before the session was recorded still holds its claim).
7
+ * Deleted conversations hold nothing.
8
+ */
9
+ export function conversationsUsingProviderSession(
10
+ database: Database,
11
+ internalSessionId: string,
12
+ ): readonly AgentConversationId[] {
13
+ const rows = database.query<{ agent_conversation_id: string }, [string, string]>(
14
+ `SELECT c.agent_conversation_id
15
+ FROM conversations c
16
+ WHERE c.deleted_at IS NULL
17
+ AND (
18
+ EXISTS (
19
+ SELECT 1 FROM provider_sessions p
20
+ WHERE p.agent_conversation_id = c.agent_conversation_id
21
+ AND p.internal_session_id = ?
22
+ AND p.deactivated_at IS NULL
23
+ )
24
+ OR (
25
+ c.adopt_provider_session_id = ?
26
+ AND NOT EXISTS (
27
+ SELECT 1 FROM provider_sessions p
28
+ WHERE p.agent_conversation_id = c.agent_conversation_id AND p.deactivated_at IS NULL
29
+ )
30
+ )
31
+ )
32
+ ORDER BY c.created_at, c.agent_conversation_id`,
33
+ ).all(internalSessionId, internalSessionId);
34
+ return Object.freeze(rows.map((row) => row.agent_conversation_id as AgentConversationId));
35
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
 
3
- export const SQLITE_AGENT_SCHEMA_VERSION = 12;
3
+ export const SQLITE_AGENT_SCHEMA_VERSION = 13;
4
4
 
5
5
  const BASE_SCHEMA = `
6
6
  CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -25,7 +25,9 @@ CREATE TABLE IF NOT EXISTS conversations (
25
25
  latest_sequence INTEGER NOT NULL DEFAULT 0 CHECK (latest_sequence >= 0),
26
26
  last_human_message_at TEXT,
27
27
  deleted_at TEXT,
28
- metadata TEXT
28
+ metadata TEXT,
29
+ adopted INTEGER NOT NULL DEFAULT 0 CHECK (adopted IN (0, 1)),
30
+ adopt_provider_session_id TEXT
29
31
  );
30
32
 
31
33
  CREATE INDEX IF NOT EXISTS conversations_updated_idx
@@ -252,6 +254,8 @@ CREATE TABLE IF NOT EXISTS provider_sessions (
252
254
 
253
255
  CREATE INDEX IF NOT EXISTS provider_sessions_conversation_idx
254
256
  ON provider_sessions(agent_conversation_id, activated_at, provider_session_record_id);
257
+ CREATE INDEX IF NOT EXISTS provider_sessions_internal_idx
258
+ ON provider_sessions(internal_session_id);
255
259
  CREATE UNIQUE INDEX IF NOT EXISTS provider_sessions_one_active_idx
256
260
  ON provider_sessions(agent_conversation_id) WHERE deactivated_at IS NULL;
257
261
 
@@ -545,7 +549,7 @@ export function migrateSqliteAgentSchema(database: Database): void {
545
549
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
546
550
  ).get()?.version ?? 0)
547
551
  : 0;
548
- if (existing !== 0 && ![8, 9, 10, 11, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
552
+ if (existing !== 0 && ![8, 9, 10, 11, 12, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
549
553
  throw new Error(
550
554
  `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
551
555
  );
@@ -589,6 +593,12 @@ export function migrateSqliteAgentSchema(database: Database): void {
589
593
  throw new Error("SQLite schema migration to version 12 left foreign key violations");
590
594
  }
591
595
  }
596
+ if (version > 0 && version < 13) {
597
+ // Adoption: whether the conversation was created from an existing provider session, and which
598
+ // one it asked for (kept so a failed adoption can be retried).
599
+ database.exec("ALTER TABLE conversations ADD COLUMN adopted INTEGER NOT NULL DEFAULT 0 CHECK (adopted IN (0, 1))");
600
+ database.exec("ALTER TABLE conversations ADD COLUMN adopt_provider_session_id TEXT");
601
+ }
592
602
  if (version < SQLITE_AGENT_SCHEMA_VERSION) {
593
603
  database.query<unknown, [number, string]>(
594
604
  "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
@@ -0,0 +1,56 @@
1
+ import type { PromptHandlers } from "../types.ts";
2
+ import type { PromptPart, SteeringPrompt } from "./contracts.ts";
3
+
4
+ /** Text of a combined prompt: the messages in order, separated by a blank line. Nothing is added. */
5
+ export const COMBINED_TEXT_SEPARATOR = "\n\n";
6
+
7
+ /**
8
+ * Every combined message keeps its own handlers: each one receives the events of the shared turn.
9
+ * Permission requests have one answer, so the first message that handles them decides.
10
+ */
11
+ export function mergeHandlers(list: readonly (PromptHandlers | undefined)[]): PromptHandlers | undefined {
12
+ const handlers = list.filter((entry): entry is PromptHandlers => entry !== undefined);
13
+ if (handlers.length === 0) return undefined;
14
+ if (handlers.length === 1) return handlers[0];
15
+ const merged: PromptHandlers = {
16
+ onChunk: (text) => handlers.forEach((entry) => entry.onChunk?.(text)),
17
+ onResponseChunk: (chunk) => handlers.forEach((entry) => entry.onResponseChunk?.(chunk)),
18
+ onActivity: (event) => handlers.forEach((entry) => entry.onActivity?.(event)),
19
+ onRecord: (record) => handlers.forEach((entry) => entry.onRecord?.(record)),
20
+ onUpdate: (notification) => handlers.forEach((entry) => entry.onUpdate?.(notification)),
21
+ };
22
+ const permission = handlers.find((entry) => entry.onPermissionRequest)?.onPermissionRequest;
23
+ if (permission) merged.onPermissionRequest = permission;
24
+ return merged;
25
+ }
26
+
27
+ function partOf(prompt: SteeringPrompt): PromptPart {
28
+ return {
29
+ id: prompt.turnId,
30
+ text: prompt.text,
31
+ ...(prompt.participantId ? { participantId: prompt.participantId } : {}),
32
+ ...(prompt.consumerMetadata !== undefined ? { consumerMetadata: prompt.consumerMetadata } : {}),
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Build the one prompt that carries a run of messages. The head keeps its id, so the combined prompt
38
+ * is one operation (one metering record). Every original promise settles with the same result.
39
+ * A run of one is returned unchanged.
40
+ */
41
+ export function combinePrompts<T extends SteeringPrompt>(run: readonly T[]): T {
42
+ const [head] = run;
43
+ if (!head) throw new Error("cannot combine an empty run of prompts");
44
+ if (run.length === 1) return head;
45
+ const attachments = run.flatMap((prompt) => prompt.attachments ?? []);
46
+ const handlers = mergeHandlers(run.map((prompt) => prompt.handlers));
47
+ return {
48
+ ...head,
49
+ text: run.map((prompt) => prompt.text).join(COMBINED_TEXT_SEPARATOR),
50
+ parts: run.map(partOf),
51
+ ...(attachments.length > 0 ? { attachments } : { attachments: undefined }),
52
+ ...(handlers ? { handlers } : { handlers: undefined }),
53
+ resolve: (result) => run.forEach((prompt) => prompt.resolve(result)),
54
+ reject: (error) => run.forEach((prompt) => prompt.reject(error)),
55
+ };
56
+ }