@qlairoslabs/acp-client 0.11.0 → 0.11.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.
package/CONSUMER_GUIDE.md CHANGED
@@ -987,8 +987,8 @@ SQLite file and one audit destination; different storage locations need a second
987
987
 
988
988
  A prompt sent while a turn runs waits. How it waits is its **delivery**:
989
989
 
990
- - `"queue"` (the default): it runs after the running turn ends, as its own turn.
991
- - `"steer"`: it is delivered at the next tool boundary. The library cancels the running turn once a
990
+ - `"queue"`: it runs after the running turn ends, as its own turn.
991
+ - `"steer"` (the default): it is delivered at the next tool boundary. The library cancels the running turn once a
992
992
  tool call has settled and nothing else is running, then sends the message, so the agent gets the
993
993
  information without losing the work it has done. If the turn ends first, the message is sent as the
994
994
  next prompt, so a message is never delivered later than the end of the turn. A text-only turn is not
@@ -1007,13 +1007,13 @@ const answer = await note; // the turn that carried the message
1007
1007
  `prompt()` and `promptFrom()` return a handle: the promise of that prompt's result, plus `id` and
1008
1008
  `withdraw()`. A prompt that does not have to wait runs immediately and `delivery` has no effect.
1009
1009
 
1010
- Set the default for prompts that do not say, per Agent or per conversation. It is `"queue"` unless you
1011
- change it:
1010
+ Set the default for prompts that do not say, per Agent or per conversation. It is `"steer"` unless you
1011
+ change it (before this was `"queue"`; set `busyDelivery: "queue"` to keep the old behaviour):
1012
1012
 
1013
1013
  ```ts
1014
1014
  const agent = await Agent.open({
1015
1015
  // ...
1016
- conversationDefaults: { busyDelivery: "steer" },
1016
+ conversationDefaults: { busyDelivery: "queue" },
1017
1017
  });
1018
1018
  ```
1019
1019
 
@@ -1133,13 +1133,32 @@ tell an adopted conversation by `adopted: true` in its context and choose what i
1133
1133
  session on success but does not repeat the history import or the recap.
1134
1134
  - **After a restart** an adopted conversation opens like any other: by loading its recorded provider session.
1135
1135
 
1136
+ ### Where checkpointing starts
1137
+
1138
+ Summarizing stored messages is a prompt, and a long history does not fit one (Codex refuses a message past 1,048,576
1139
+ characters), so an adopted conversation's checkpoints never look at the history that came before its adoption. When the
1140
+ conversation checkpoints, adoption places a **floor**: a checkpoint covering everything up to 50 messages before the end of
1141
+ what is stored (or the recap, when the history is shorter than that).
1142
+
1143
+ - With a recap, the floor's summary *is* the recap. It stands for the whole provider history, imported or not, and a
1144
+ recovery seeds the recap plus the messages after the floor.
1145
+ - Without a recap, the floor is a baseline with no summary: a recovery seeds only the messages after it, and identity
1146
+ delivers the stored messages as it would without a checkpoint.
1147
+ - A conversation with no recap and 50 messages or fewer stored gets no floor; its first scheduled checkpoint summarizes them.
1148
+ - Every stored message stays readable (listing, pagination, search); only summarizing starts after the floor. Checkpoints that
1149
+ follow chain from it.
1150
+ - The checkpoint schedule (responses 1, 5, 10, ...) counts responses after what the adoption stored, as for a new conversation.
1151
+ - A checkpoint whose records do not fit one prompt (700,000 characters) fails with `checkpoint_source_too_large` and is not
1152
+ retried. Only a conversation that stores a very long run of messages between two checkpoints can reach it.
1153
+
1136
1154
  ### Limits to know about
1137
1155
 
1138
1156
  - Replays differ by harness (measured on Codex and OpenCode with `smoke-tests/session-replay-probe`): both send message
1139
1157
  boundaries, tool calls and, for OpenCode, thoughts; neither sends timestamps or usage. Codex replays the tool call of a turn
1140
1158
  that was cancelled mid-tool after the next turn's user message, and it is imported where it arrives.
1141
1159
  - The recap is a hidden turn on the adopted session itself, so the provider's own history then contains the question and the
1142
- answer. The model is asked not to use tools; ACP gives no way to forbid them for one turn.
1160
+ answer. The model is asked not to use tools; ACP gives no way to forbid them for one turn. A later adoption of the same
1161
+ session does not import that question or its answer as turns.
1143
1162
  - With `importHistory: true`, every imported message is also delivered to the Agent's other conversations (within identity's
1144
1163
  budget): prefer the default tail with a recap for long sessions.
1145
1164
  - The first prompt after an adoption runs on a thread whose usage counters did not start at zero, so its metering is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -0,0 +1,47 @@
1
+ import type { AgentConversationId } from "../../agent-ids.ts";
2
+ import { createConversationRecoveryCheckpointId } from "../../checkpointing/ids.ts";
3
+ import type { ConversationRecoveryCheckpointRepository } from "../../checkpointing/contracts.ts";
4
+
5
+ /** Messages left after the floor, so a recovery or a first checkpoint still sees the end of the history. */
6
+ export const DEFAULT_ADOPTION_TAIL_MESSAGES = 50;
7
+
8
+ export interface AdoptionRecapPlacement {
9
+ readonly summary: string;
10
+ /** Sequence of the stored recap message. */
11
+ readonly sequence: number;
12
+ }
13
+
14
+ /**
15
+ * Where checkpointing starts for an adopted conversation, so that nothing ever summarizes the history that
16
+ * came before it. Summarizing stored records is a prompt, and a long history does not fit one (a harness
17
+ * refuses a message past about a million characters), so the floor sits `tailMessages` before the end of
18
+ * what is stored: the recap's own message when that is later, so a conversation whose history is short
19
+ * keeps the recap as the first thing it recovers from.
20
+ *
21
+ * With a recap the checkpoint's summary is the recap, which covers the whole provider history; without one the
22
+ * checkpoint is a baseline with no summary, and recovery seeds only the messages after it. A conversation
23
+ * with no recap and no more than `tailMessages` stored messages has nothing to place a floor under, and gets
24
+ * none: its first scheduled checkpoint summarizes those few messages.
25
+ *
26
+ * The checkpoint schedule counts responses after the stored history, so an import does not use up the
27
+ * milestones a new conversation starts with.
28
+ */
29
+ export async function publishAdoptionFloor(
30
+ repository: ConversationRecoveryCheckpointRepository,
31
+ conversationId: AgentConversationId,
32
+ options: { readonly recap?: AdoptionRecapPlacement; readonly tailMessages?: number },
33
+ ): Promise<boolean> {
34
+ const tail = Math.max(0, options.tailMessages ?? DEFAULT_ADOPTION_TAIL_MESSAGES);
35
+ const lastSequence = await repository.latestMessageSequence(conversationId);
36
+ const floor = Math.max(options.recap?.sequence ?? 0, lastSequence - tail);
37
+ if (floor < 1) return false;
38
+ await repository.publish({
39
+ checkpointId: createConversationRecoveryCheckpointId(),
40
+ agentConversationId: conversationId,
41
+ coveredSequence: floor,
42
+ source: options.recap ? "adoption_recap" : "adoption_baseline",
43
+ summary: options.recap?.summary ?? "",
44
+ responsesCountedAfterSequence: lastSequence,
45
+ });
46
+ return true;
47
+ }
@@ -1,7 +1,9 @@
1
1
  export { DEFAULT_RECAP_TAIL_TURNS, normalizeAdoption } from "./config.ts";
2
2
  export { RECAP_INSTRUCTION, RECAP_ORIGIN } from "./recap.ts";
3
3
  export type { AdoptProviderSessionConfig, NormalizedAdoption } from "./config.ts";
4
- export { turnsFromReplay, selectTail } from "./replay.ts";
4
+ export { turnsFromReplay, selectTail, withoutRecapTurns } from "./replay.ts";
5
+ export { publishAdoptionFloor, DEFAULT_ADOPTION_TAIL_MESSAGES } from "./checkpoint-floor.ts";
6
+ export type { AdoptionRecapPlacement } from "./checkpoint-floor.ts";
5
7
  export { deleteProviderSession } from "./provider-session-delete.ts";
6
8
  export { listProviderSessions, DEFAULT_PROVIDER_SESSION_LIMIT } from "./provider-sessions.ts";
7
9
  export type { ListProviderSessionsOptions, ProviderSessionListing, ProviderSessionSummary } from "./provider-sessions.ts";
@@ -1,4 +1,5 @@
1
1
  import type { ActivityEvent } from "../../types.ts";
2
+ import { RECAP_INSTRUCTION } from "./recap.ts";
2
3
  import { extractResponseChunk, toActivityEvent } from "../../updates.ts";
3
4
 
4
5
  /** One piece of an imported turn, in the order the provider replayed it. */
@@ -82,3 +83,16 @@ export function turnsFromReplay(notifications: readonly unknown[]): ImportedTurn
82
83
  export function selectTail(turns: readonly ImportedTurn[], last: number | undefined): ImportedTurn[] {
83
84
  return last === undefined ? [...turns] : turns.slice(-last);
84
85
  }
86
+
87
+ /**
88
+ * Drop the turns that are an earlier adoption's recap: the question is a turn of the provider's own history
89
+ * once it has been asked, so a later adoption of the same session replays it. It is not something the
90
+ * participants said, and the answer is the recap, which this adoption makes (or does not) for itself.
91
+ */
92
+ export function withoutRecapTurns(turns: readonly ImportedTurn[]): ImportedTurn[] {
93
+ const question = RECAP_INSTRUCTION.trim();
94
+ return turns.filter((turn) => {
95
+ const first = turn.items.find((item) => item.kind === "user");
96
+ return !(first && first.text.trim() === question);
97
+ });
98
+ }
@@ -74,6 +74,10 @@ import {
74
74
  normalizeAdoption,
75
75
  selectTail,
76
76
  turnsFromReplay,
77
+ withoutRecapTurns,
78
+ publishAdoptionFloor,
79
+ DEFAULT_ADOPTION_TAIL_MESSAGES,
80
+ type AdoptionRecapPlacement,
77
81
  type ListProviderSessionsOptions,
78
82
  type NormalizedAdoption,
79
83
  type ProviderSessionSummary,
@@ -226,11 +230,12 @@ export class DefaultAgentConversationManager implements AgentConversationManager
226
230
  }
227
231
  try {
228
232
  await this.recordAdoptedProviderSession(conversation, id, attemptId);
229
- if (adoption.recap) await this.recap(conversation, id, attemptId, settings);
233
+ const recap = adoption.recap ? await this.recap(conversation, id, attemptId, settings) : undefined;
230
234
  if (adoption.importHistory) {
231
- const turns = selectTail(turnsFromReplay(replay), adoption.importHistory.last);
235
+ const turns = selectTail(withoutRecapTurns(turnsFromReplay(replay)), adoption.importHistory.last);
232
236
  await conversation.importHistory(turns, `${attemptId}-import`);
233
237
  }
238
+ await this.placeCheckpointFloor(id, recap, settings);
234
239
  } catch (error) {
235
240
  this.live.delete(id);
236
241
  await conversation.stop().catch(() => undefined);
@@ -249,11 +254,16 @@ export class DefaultAgentConversationManager implements AgentConversationManager
249
254
  id: AgentConversationId,
250
255
  attemptId: string,
251
256
  settings: ManagerSettings,
252
- ): Promise<void> {
257
+ ): Promise<AdoptionRecapPlacement | undefined> {
253
258
  const recapId = `${attemptId}-recap`;
254
259
  try {
255
260
  const summary = await conversation.requestRecap(RECAP_INSTRUCTION, recapId);
256
261
  await conversation.recordRecap(summary, recapId, RECAP_ORIGIN);
262
+ // Stored before anything is imported, so its sequence is the last one so far. A conversation that
263
+ // stores no messages has no sequence to cover (adoption requires `content` capture, so this is a
264
+ // backend without checkpoints).
265
+ const sequence = await this.agent.persistence.recoveryCheckpoints?.latestMessageSequence(id);
266
+ return sequence ? { summary: summary.trim(), sequence } : undefined;
257
267
  } catch (error) {
258
268
  await this.recordConversationError({
259
269
  settings,
@@ -265,6 +275,38 @@ export class DefaultAgentConversationManager implements AgentConversationManager
265
275
  message: "The adopted session could not be summarized.",
266
276
  details: providerSessionErrorDetails(error),
267
277
  });
278
+ return undefined;
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Put the conversation's checkpoint floor after the adopted history (see `publishAdoptionFloor`), when the
284
+ * conversation checkpoints at all. A failure here is recorded and does not fail the adoption: the
285
+ * conversation is usable, and its first scheduled checkpoint then starts from whatever is stored.
286
+ */
287
+ private async placeCheckpointFloor(
288
+ id: AgentConversationId,
289
+ recap: AdoptionRecapPlacement | undefined,
290
+ settings: ManagerSettings,
291
+ ): Promise<void> {
292
+ const repository = this.agent.persistence.recoveryCheckpoints;
293
+ if (!repository || !settings.checkpointing?.enabled) return;
294
+ try {
295
+ await publishAdoptionFloor(repository, id, {
296
+ ...(recap ? { recap } : {}),
297
+ tailMessages: Math.min(DEFAULT_ADOPTION_TAIL_MESSAGES, settings.checkpointing.recovery.maxTailMessages),
298
+ });
299
+ } catch (error) {
300
+ await this.recordConversationError({
301
+ settings,
302
+ agentConversationId: id,
303
+ attemptId: `${id}-checkpoint-floor`,
304
+ source: "operation",
305
+ code: "adoption_checkpoint_floor_failed",
306
+ recoverability: "retryable",
307
+ message: "The checkpoint floor of the adopted conversation could not be placed.",
308
+ details: providerSessionErrorDetails(error),
309
+ });
268
310
  }
269
311
  }
270
312
 
@@ -328,7 +328,7 @@ export interface AgentSessionConfig {
328
328
  defaultPermission?: "approve" | "cancel";
329
329
  /**
330
330
  * How a prompt sent while a turn is running waits when the prompt does not say. `queue` runs it after
331
- * the turn ends; `steer` delivers it at the next tool boundary. Default `queue`.
331
+ * the turn ends; `steer` delivers it at the next tool boundary. Default `steer`.
332
332
  */
333
333
  busyDelivery?: PromptDelivery;
334
334
  clientInfo?: { name: string; title?: string; version?: string };
@@ -560,7 +560,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
560
560
  cancelProviderTurn: () => this.controller.interrupt(),
561
561
  emitState: () => this.emitStateIfChanged(),
562
562
  },
563
- config.busyDelivery ?? "queue",
563
+ config.busyDelivery ?? "steer",
564
564
  );
565
565
  this._participants = (config.participants ?? []).map((participant) => Object.freeze({ ...participant }));
566
566
  this._adapterId = config.adapterId;
@@ -3,14 +3,33 @@ import type { InternalInferenceId } from "../internal-inference/contracts.ts";
3
3
 
4
4
  export type ConversationRecoveryCheckpointId = `chk-${string}`;
5
5
 
6
+ /**
7
+ * What made a checkpoint. `internal_inference` is the normal case: a model call over stored records.
8
+ * The adoption sources have no generator: the summary is the recap the adopted session wrote of its own
9
+ * history (`adoption_recap`), or empty (`adoption_baseline`, a floor only). Either way the checkpoint says
10
+ * where summarizing starts, so nothing ever tries to summarize the history that came before it.
11
+ */
12
+ export type ConversationRecoveryCheckpointSource =
13
+ | "internal_inference"
14
+ | "adoption_recap"
15
+ | "adoption_baseline";
16
+
6
17
  export interface ConversationRecoveryCheckpoint {
7
18
  readonly checkpointId: ConversationRecoveryCheckpointId;
8
19
  readonly agentConversationId: AgentConversationId;
9
20
  readonly revision: number;
10
21
  readonly coveredSequence: number;
11
22
  readonly previousCheckpointId?: ConversationRecoveryCheckpointId;
12
- readonly generatorInternalInferenceId: InternalInferenceId;
23
+ /** Absent for the adoption sources, which no internal inference generated. */
24
+ readonly generatorInternalInferenceId?: InternalInferenceId;
25
+ readonly source: ConversationRecoveryCheckpointSource;
26
+ /** Empty only for `adoption_baseline`. */
13
27
  readonly summary: string;
28
+ /**
29
+ * Adoption only: the checkpoint schedule counts successful responses after this sequence, so the history
30
+ * an adoption imported does not use up the milestones a new conversation starts with.
31
+ */
32
+ readonly responsesCountedAfterSequence?: number;
14
33
  readonly createdAt: string;
15
34
  readonly metadata?: string;
16
35
  }
@@ -20,8 +39,11 @@ export interface PublishConversationRecoveryCheckpointInput {
20
39
  readonly agentConversationId: AgentConversationId;
21
40
  readonly coveredSequence: number;
22
41
  readonly previousCheckpointId?: ConversationRecoveryCheckpointId;
23
- readonly generatorInternalInferenceId: InternalInferenceId;
42
+ readonly generatorInternalInferenceId?: InternalInferenceId;
43
+ /** Default `internal_inference`, which requires a generator and a summary. */
44
+ readonly source?: ConversationRecoveryCheckpointSource;
24
45
  readonly summary: string;
46
+ readonly responsesCountedAfterSequence?: number;
25
47
  readonly createdAt?: string;
26
48
  readonly metadata?: string;
27
49
  }
@@ -32,7 +54,10 @@ export interface ConversationRecoveryCheckpointListOptions {
32
54
  }
33
55
 
34
56
  export interface ConversationRecoveryCheckpointRepository {
35
- /** Count completed provider turns using the stable operation ID on assistant messages. */
57
+ /**
58
+ * Count completed provider turns using the stable operation ID on assistant messages, after the
59
+ * adoption checkpoint's `responsesCountedAfterSequence` when the conversation has one.
60
+ */
36
61
  successfulResponseCount(agentConversationId: AgentConversationId): Promise<number>;
37
62
  latestMessageSequence(agentConversationId: AgentConversationId): Promise<number>;
38
63
  latest(agentConversationId: AgentConversationId): Promise<ConversationRecoveryCheckpoint | null>;
@@ -7,6 +7,7 @@ import type {
7
7
  ConversationRecoveryCheckpointId,
8
8
  ConversationRecoveryCheckpointListOptions,
9
9
  ConversationRecoveryCheckpointRepository,
10
+ ConversationRecoveryCheckpointSource,
10
11
  PublishConversationRecoveryCheckpointInput,
11
12
  } from "../contracts.ts";
12
13
 
@@ -18,8 +19,10 @@ interface CheckpointRow {
18
19
  revision: number;
19
20
  covered_sequence: number;
20
21
  previous_checkpoint_id: string | null;
21
- generator_internal_inference_id: string;
22
+ generator_internal_inference_id: string | null;
23
+ source: string;
22
24
  summary: string;
25
+ responses_counted_after_sequence: number | null;
23
26
  created_at: string;
24
27
  metadata: string | null;
25
28
  }
@@ -36,7 +39,12 @@ implements ConversationRecoveryCheckpointRepository {
36
39
  WHERE r.agent_conversation_id = ? AND r.kind = 'message'
37
40
  AND m.role = 'assistant'
38
41
  AND m.status = 'completed'
39
- AND r.operation_id IS NOT NULL`,
42
+ AND r.operation_id IS NOT NULL
43
+ AND r.sequence > COALESCE((
44
+ SELECT c.responses_counted_after_sequence FROM conversation_recovery_checkpoints c
45
+ WHERE c.agent_conversation_id = r.agent_conversation_id AND c.source <> 'internal_inference'
46
+ ORDER BY c.revision LIMIT 1
47
+ ), 0)`,
40
48
  ).get(agentConversationId);
41
49
  return Number(row?.count ?? 0);
42
50
  }
@@ -97,7 +105,17 @@ implements ConversationRecoveryCheckpointRepository {
97
105
  async publish(input: PublishConversationRecoveryCheckpointInput): Promise<ConversationRecoveryCheckpoint> {
98
106
  return await this.runWrite(() => {
99
107
  const summary = input.summary.trim();
100
- if (!summary) throw new Error("recovery checkpoint summary cannot be blank");
108
+ const source = input.source ?? "internal_inference";
109
+ // Only a baseline is a floor with nothing to say; every other checkpoint summarizes something, and
110
+ // only an internal inference has a generator.
111
+ if (source === "adoption_baseline" ? summary !== "" : !summary) {
112
+ throw new Error(source === "adoption_baseline"
113
+ ? "an adoption baseline checkpoint has no summary"
114
+ : "recovery checkpoint summary cannot be blank");
115
+ }
116
+ if ((source === "internal_inference") !== (input.generatorInternalInferenceId !== undefined)) {
117
+ throw new Error("only an internal-inference checkpoint has a generator, and it must have one");
118
+ }
101
119
  if (!Number.isSafeInteger(input.coveredSequence) || input.coveredSequence < 1) {
102
120
  throw new Error("recovery checkpoint coveredSequence must be a positive integer");
103
121
  }
@@ -110,6 +128,7 @@ implements ConversationRecoveryCheckpointRepository {
110
128
  checkpoint.agentConversationId !== input.agentConversationId
111
129
  || checkpoint.coveredSequence !== input.coveredSequence
112
130
  || checkpoint.generatorInternalInferenceId !== input.generatorInternalInferenceId
131
+ || checkpoint.source !== source
113
132
  || checkpoint.summary !== summary
114
133
  ) throw new PersistenceConflictError(`recovery checkpoint id conflict: ${input.checkpointId}`);
115
134
  return checkpoint;
@@ -130,20 +149,23 @@ implements ConversationRecoveryCheckpointRepository {
130
149
  this.database.query(
131
150
  `INSERT INTO conversation_recovery_checkpoints(
132
151
  checkpoint_id, agent_conversation_id, revision, covered_sequence,
133
- previous_checkpoint_id, generator_internal_inference_id, summary, created_at, metadata
134
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
152
+ previous_checkpoint_id, generator_internal_inference_id, source, summary,
153
+ responses_counted_after_sequence, created_at, metadata
154
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
135
155
  ).run(
136
156
  input.checkpointId,
137
157
  input.agentConversationId,
138
158
  revision,
139
159
  input.coveredSequence,
140
160
  input.previousCheckpointId ?? null,
141
- input.generatorInternalInferenceId,
161
+ input.generatorInternalInferenceId ?? null,
162
+ source,
142
163
  summary,
164
+ input.responsesCountedAfterSequence ?? null,
143
165
  createdAt,
144
166
  input.metadata ?? null,
145
167
  );
146
- return Object.freeze({ ...input, summary, revision, createdAt });
168
+ return Object.freeze({ ...input, source, summary, revision, createdAt });
147
169
  });
148
170
  }
149
171
  }
@@ -157,8 +179,14 @@ function fromRow(row: CheckpointRow): ConversationRecoveryCheckpoint {
157
179
  ...(row.previous_checkpoint_id
158
180
  ? { previousCheckpointId: row.previous_checkpoint_id as ConversationRecoveryCheckpointId }
159
181
  : {}),
160
- generatorInternalInferenceId: row.generator_internal_inference_id as InternalInferenceId,
182
+ ...(row.generator_internal_inference_id
183
+ ? { generatorInternalInferenceId: row.generator_internal_inference_id as InternalInferenceId }
184
+ : {}),
185
+ source: row.source as ConversationRecoveryCheckpointSource,
161
186
  summary: row.summary,
187
+ ...(row.responses_counted_after_sequence !== null
188
+ ? { responsesCountedAfterSequence: Number(row.responses_counted_after_sequence) }
189
+ : {}),
162
190
  createdAt: row.created_at,
163
191
  ...(row.metadata ? { metadata: row.metadata } : {}),
164
192
  });
@@ -90,8 +90,10 @@ export async function buildRecoverySeed(
90
90
  return Object.freeze({
91
91
  prompt: [
92
92
  config.seedInstruction,
93
- `Continuation checkpoint through canonical sequence ${checkpoint.coveredSequence}:`,
94
- checkpoint.summary,
93
+ // An adoption baseline has no summary: only the messages after it are known.
94
+ ...(checkpoint.summary
95
+ ? [`Continuation checkpoint through canonical sequence ${checkpoint.coveredSequence}:`, checkpoint.summary]
96
+ : []),
95
97
  tail.length
96
98
  ? `Canonical messages after the checkpoint:\n${JSON.stringify(tail)}`
97
99
  : "There are no canonical messages after the checkpoint.",
@@ -13,6 +13,20 @@ const CHECKPOINT_READ_ONLY_INSTRUCTION = [
13
13
  "Only summarize the records supplied in this prompt.",
14
14
  ].join(" ");
15
15
 
16
+ /**
17
+ * The most characters of stored records one checkpoint prompt may carry. Harnesses refuse a message past
18
+ * about a million characters (Codex: "Message exceeds the maximum length of 1048576 characters"), and a
19
+ * prompt that cannot be sent cannot succeed however often it is retried.
20
+ */
21
+ export const MAX_CHECKPOINT_SOURCE_CHARS = 700_000;
22
+
23
+ export class CheckpointSourceTooLargeError extends Error {
24
+ constructor(readonly chars: number, readonly limit: number) {
25
+ super(`conversation checkpoint source is too large: ${chars} characters, the limit is ${limit}`);
26
+ this.name = "CheckpointSourceTooLargeError";
27
+ }
28
+ }
29
+
16
30
  export type ConversationCheckpointPayload = {
17
31
  readonly instruction: string;
18
32
  };
@@ -47,15 +61,20 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
47
61
  if (through <= from) throw new Error("conversation checkpoint source range is empty");
48
62
  const records = await readRecords(context.persistence.records, conversationId, from, through);
49
63
  if (!records.length) throw new Error("conversation checkpoint source contains no records");
64
+ const serialized = JSON.stringify(records);
65
+ if (serialized.length + (previous?.summary.length ?? 0) > MAX_CHECKPOINT_SOURCE_CHARS) {
66
+ throw new CheckpointSourceTooLargeError(serialized.length + (previous?.summary.length ?? 0), MAX_CHECKPOINT_SOURCE_CHARS);
67
+ }
50
68
  return Object.freeze({
51
69
  prompt: [
52
70
  payload.instruction,
53
71
  CHECKPOINT_READ_ONLY_INSTRUCTION,
54
- previous
72
+ // An adoption baseline is a floor without a summary: nothing to build on, and nothing before it is read.
73
+ previous?.summary
55
74
  ? `Previous continuation summary:\n${previous.summary}`
56
75
  : "There is no previous continuation summary.",
57
76
  `New canonical records after sequence ${from} through ${through}:`,
58
- JSON.stringify(records),
77
+ serialized,
59
78
  ].join("\n\n"),
60
79
  metadata: JSON.stringify({ previousCheckpointId: previous?.checkpointId ?? null, through }),
61
80
  });
@@ -77,6 +96,7 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
77
96
  ? { previousCheckpointId: context.attempt.sourceCheckpointId as `chk-${string}` }
78
97
  : {}),
79
98
  generatorInternalInferenceId: result.internalInferenceId,
99
+ source: "internal_inference",
80
100
  summary,
81
101
  });
82
102
  const record = {
@@ -114,6 +134,9 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
114
134
  }
115
135
 
116
136
  classifyError(error: unknown) {
137
+ if (error instanceof CheckpointSourceTooLargeError) {
138
+ return { kind: "terminal" as const, code: "checkpoint_source_too_large" };
139
+ }
117
140
  const message = error instanceof Error ? error.message : String(error);
118
141
  if (message.includes("source changed") || message.includes("coverage") || message.includes("source range")) {
119
142
  return { kind: "terminal" as const, code: "checkpoint_source_conflict" };
@@ -160,7 +160,7 @@ export class CheckpointBackedIdentityRuntime implements AgentIdentityRuntime {
160
160
  const header = `Source conversation ${conversation.agentConversationId}${label}; participants=${JSON.stringify(participants)}\n`;
161
161
  if (header.length >= maxChars) return null;
162
162
  const start = cursor?.deliveredThroughSequence ?? 0;
163
- const initialSummary = !cursor && checkpoint
163
+ const initialSummary = !cursor && checkpoint?.summary
164
164
  ? summaryText(checkpoint, "Summary")
165
165
  : "";
166
166
  const summaryFits = initialSummary.length > 0 && header.length + initialSummary.length <= maxChars;
@@ -173,7 +173,7 @@ export class CheckpointBackedIdentityRuntime implements AgentIdentityRuntime {
173
173
  );
174
174
  let text = header + (summaryFits ? initialSummary : "") + raw.text;
175
175
  let throughSequence = Math.max(from, raw.throughSequence);
176
- if (cursor && !raw.complete && checkpoint && checkpoint.coveredSequence > throughSequence) {
176
+ if (cursor && !raw.complete && checkpoint?.summary && checkpoint.coveredSequence > throughSequence) {
177
177
  const replacement = summaryText(checkpoint, "Updated summary, superseding earlier source context");
178
178
  if (header.length + replacement.length <= maxChars) {
179
179
  const tail = await this.readMessages(
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
 
3
- export const SQLITE_AGENT_SCHEMA_VERSION = 13;
3
+ export const SQLITE_AGENT_SCHEMA_VERSION = 14;
4
4
 
5
5
  const BASE_SCHEMA = `
6
6
  CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -376,12 +376,20 @@ CREATE TABLE IF NOT EXISTS conversation_recovery_checkpoints (
376
376
  revision INTEGER NOT NULL CHECK (revision >= 1),
377
377
  covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 1),
378
378
  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),
379
+ generator_internal_inference_id TEXT UNIQUE REFERENCES internal_inferences(internal_inference_id),
380
+ source TEXT NOT NULL DEFAULT 'internal_inference'
381
+ CHECK (source IN ('internal_inference', 'adoption_recap', 'adoption_baseline')),
382
+ summary TEXT NOT NULL,
383
+ responses_counted_after_sequence INTEGER CHECK (responses_counted_after_sequence IS NULL OR responses_counted_after_sequence >= 0),
381
384
  created_at TEXT NOT NULL,
382
385
  metadata TEXT,
383
386
  UNIQUE (agent_conversation_id, revision),
384
- UNIQUE (agent_conversation_id, covered_sequence)
387
+ UNIQUE (agent_conversation_id, covered_sequence),
388
+ CHECK (
389
+ (source = 'internal_inference' AND generator_internal_inference_id IS NOT NULL AND length(summary) > 0)
390
+ OR (source = 'adoption_recap' AND generator_internal_inference_id IS NULL AND length(summary) > 0)
391
+ OR (source = 'adoption_baseline' AND generator_internal_inference_id IS NULL AND summary = '')
392
+ )
385
393
  );
386
394
 
387
395
  CREATE INDEX IF NOT EXISTS recovery_checkpoints_latest_idx
@@ -549,7 +557,7 @@ export function migrateSqliteAgentSchema(database: Database): void {
549
557
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
550
558
  ).get()?.version ?? 0)
551
559
  : 0;
552
- if (existing !== 0 && ![8, 9, 10, 11, 12, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
560
+ if (existing !== 0 && ![8, 9, 10, 11, 12, 13, SQLITE_AGENT_SCHEMA_VERSION].includes(existing)) {
553
561
  throw new Error(
554
562
  `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
555
563
  );
@@ -557,7 +565,7 @@ export function migrateSqliteAgentSchema(database: Database): void {
557
565
  // Admitting the `error` kind means rebuilding conversation_records: its kind CHECK is a
558
566
  // closed list SQLite cannot alter in place. Foreign keys must be off for that drop, or
559
567
  // the implicit delete would cascade into every detail table.
560
- const rebuildRecords = existing > 0 && existing < 12;
568
+ const rebuildRecords = existing > 0 && existing < 14;
561
569
  if (rebuildRecords) database.exec("PRAGMA foreign_keys = OFF");
562
570
  try {
563
571
  database.exec("BEGIN IMMEDIATE");
@@ -599,6 +607,13 @@ export function migrateSqliteAgentSchema(database: Database): void {
599
607
  database.exec("ALTER TABLE conversations ADD COLUMN adopted INTEGER NOT NULL DEFAULT 0 CHECK (adopted IN (0, 1))");
600
608
  database.exec("ALTER TABLE conversations ADD COLUMN adopt_provider_session_id TEXT");
601
609
  }
610
+ if (version > 0 && version < 14) {
611
+ rebuildRecoveryCheckpointsForAdoption(database);
612
+ const violations = database.query<Record<string, unknown>, []>("PRAGMA foreign_key_check").all();
613
+ if (violations.length > 0) {
614
+ throw new Error("SQLite schema migration to version 14 left foreign key violations");
615
+ }
616
+ }
602
617
  if (version < SQLITE_AGENT_SCHEMA_VERSION) {
603
618
  database.query<unknown, [number, string]>(
604
619
  "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
@@ -614,6 +629,48 @@ export function migrateSqliteAgentSchema(database: Database): void {
614
629
  }
615
630
  }
616
631
 
632
+ /**
633
+ * Rebuild `conversation_recovery_checkpoints` so a checkpoint may have no generator and an empty summary
634
+ * (adoption checkpoints), with a `source` and the adoption response-count base. SQLite cannot relax a
635
+ * NOT NULL or a CHECK in place. Foreign keys are off (see the caller). The old table's index goes with it and
636
+ * is recreated on the new one.
637
+ */
638
+ function rebuildRecoveryCheckpointsForAdoption(database: Database): void {
639
+ database.exec("ALTER TABLE conversation_recovery_checkpoints RENAME TO conversation_recovery_checkpoints_v13");
640
+ database.exec("DROP INDEX IF EXISTS recovery_checkpoints_latest_idx");
641
+ database.exec(`
642
+ CREATE TABLE conversation_recovery_checkpoints (
643
+ checkpoint_id TEXT PRIMARY KEY,
644
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
645
+ revision INTEGER NOT NULL CHECK (revision >= 1),
646
+ covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 1),
647
+ previous_checkpoint_id TEXT REFERENCES conversation_recovery_checkpoints(checkpoint_id),
648
+ generator_internal_inference_id TEXT UNIQUE REFERENCES internal_inferences(internal_inference_id),
649
+ source TEXT NOT NULL DEFAULT 'internal_inference'
650
+ CHECK (source IN ('internal_inference', 'adoption_recap', 'adoption_baseline')),
651
+ summary TEXT NOT NULL,
652
+ responses_counted_after_sequence INTEGER CHECK (responses_counted_after_sequence IS NULL OR responses_counted_after_sequence >= 0),
653
+ created_at TEXT NOT NULL,
654
+ metadata TEXT,
655
+ UNIQUE (agent_conversation_id, revision),
656
+ UNIQUE (agent_conversation_id, covered_sequence),
657
+ CHECK (
658
+ (source = 'internal_inference' AND generator_internal_inference_id IS NOT NULL AND length(summary) > 0)
659
+ OR (source = 'adoption_recap' AND generator_internal_inference_id IS NULL AND length(summary) > 0)
660
+ OR (source = 'adoption_baseline' AND generator_internal_inference_id IS NULL AND summary = '')
661
+ )
662
+ )`);
663
+ database.exec(`INSERT INTO conversation_recovery_checkpoints(
664
+ checkpoint_id, agent_conversation_id, revision, covered_sequence, previous_checkpoint_id,
665
+ generator_internal_inference_id, source, summary, created_at, metadata
666
+ ) SELECT checkpoint_id, agent_conversation_id, revision, covered_sequence, previous_checkpoint_id,
667
+ generator_internal_inference_id, 'internal_inference', summary, created_at, metadata
668
+ FROM conversation_recovery_checkpoints_v13`);
669
+ database.exec("DROP TABLE conversation_recovery_checkpoints_v13");
670
+ database.exec(`CREATE INDEX IF NOT EXISTS recovery_checkpoints_latest_idx
671
+ ON conversation_recovery_checkpoints(agent_conversation_id, revision DESC)`);
672
+ }
673
+
617
674
  /**
618
675
  * Rebuild `conversation_records` so its `kind` CHECK admits `error`.
619
676
  *