@qlairoslabs/acp-client 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG-consumer-fixes.md +55 -0
  2. package/CHANGELOG-operation-lifecycle.md +64 -0
  3. package/CONSUMER_GUIDE.md +311 -17
  4. package/MIGRATION-0.10-to-0.12.md +189 -0
  5. package/README.md +6 -3
  6. package/package.json +5 -2
  7. package/src/adapters.ts +3 -1
  8. package/src/agent/adoption/checkpoint-floor.ts +47 -0
  9. package/src/agent/adoption/index.ts +3 -1
  10. package/src/agent/adoption/replay.ts +15 -0
  11. package/src/agent/config.ts +4 -0
  12. package/src/agent/conversation-manager.ts +223 -153
  13. package/src/agent/error-record-writer.ts +77 -0
  14. package/src/agent/persisted-lifecycle.ts +152 -35
  15. package/src/agent/record-capture.ts +18 -18
  16. package/src/agent-adapter-registry.ts +2 -0
  17. package/src/agent-client.ts +9 -3
  18. package/src/agent-conversation-contracts.ts +6 -0
  19. package/src/agent-conversation-owner.ts +31 -6
  20. package/src/agent-conversation-presentation.ts +12 -1
  21. package/src/agent-conversation-queue.ts +3 -2
  22. package/src/agent-session.ts +537 -96
  23. package/src/agent.ts +46 -23
  24. package/src/audit/config.ts +4 -0
  25. package/src/audit/projection.ts +3 -0
  26. package/src/checkpointing/contracts.ts +28 -3
  27. package/src/checkpointing/persistence/sqlite-repository.ts +36 -8
  28. package/src/checkpointing/recovery.ts +9 -2
  29. package/src/checkpointing/strategy.ts +27 -2
  30. package/src/client.ts +120 -30
  31. package/src/controller.ts +116 -7
  32. package/src/degraded/pty-client.ts +25 -1
  33. package/src/identity/checkpoint-backed.ts +2 -2
  34. package/src/index.ts +17 -0
  35. package/src/internal-inference/config.ts +7 -0
  36. package/src/internal-inference/contracts.ts +3 -0
  37. package/src/internal-inference/coordination/handles.ts +11 -2
  38. package/src/internal-inference/coordination/manager.ts +20 -3
  39. package/src/internal-inference/index.ts +2 -0
  40. package/src/internal-inference/persistence/records.ts +3 -1
  41. package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
  42. package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
  43. package/src/internal-inference/runtime/harness-runtime.ts +19 -2
  44. package/src/media/acp.ts +118 -0
  45. package/src/media/capture.ts +15 -0
  46. package/src/media/content.ts +142 -0
  47. package/src/media/files.ts +28 -0
  48. package/src/media/parts.ts +145 -0
  49. package/src/media/pending.ts +51 -0
  50. package/src/media/redact.ts +14 -0
  51. package/src/media/store.ts +127 -0
  52. package/src/metering/provider.ts +8 -1
  53. package/src/operations/activity-tracker.ts +31 -0
  54. package/src/operations/contracts.ts +63 -0
  55. package/src/operations/errors.ts +31 -0
  56. package/src/operations/index.ts +6 -0
  57. package/src/operations/stale-policy.ts +51 -0
  58. package/src/operations/supervisor.ts +209 -0
  59. package/src/operations/timers.ts +12 -0
  60. package/src/out-of-band-messages.ts +49 -32
  61. package/src/persistence/audit-runtime.ts +14 -2
  62. package/src/persistence/backend.ts +108 -12
  63. package/src/persistence/error-records.ts +27 -0
  64. package/src/persistence/index.ts +8 -0
  65. package/src/persistence/presentation.ts +9 -1
  66. package/src/persistence/projection.ts +20 -0
  67. package/src/persistence/records.ts +45 -6
  68. package/src/persistence/sqlite-backend.ts +207 -16
  69. package/src/persistence/sqlite-conversation-records.ts +31 -4
  70. package/src/persistence/sqlite-files.ts +95 -0
  71. package/src/persistence/sqlite-media-store.ts +67 -0
  72. package/src/persistence/sqlite-schema.ts +146 -13
  73. package/src/persistence/state-runtime.ts +2 -0
  74. package/src/persistence/timeline-reconcile.ts +21 -4
  75. package/src/persistence/transcript-reader.ts +11 -4
  76. package/src/persistence/transcript-runtime.ts +105 -12
  77. package/src/repl/repl.ts +1 -1
  78. package/src/response.ts +40 -8
  79. package/src/steering/combine.ts +11 -4
  80. package/src/steering/contracts.ts +14 -4
  81. package/src/steering/controller.ts +96 -21
  82. package/src/steering/index.ts +1 -0
  83. package/src/transport/acp-transport.ts +18 -7
  84. package/src/types.ts +7 -0
  85. package/src/updates.ts +4 -4
package/src/agent.ts CHANGED
@@ -40,6 +40,7 @@ import type {
40
40
  } from "./internal-inference/contracts.ts";
41
41
  import { DefaultInternalInferenceManager } from "./internal-inference/coordination/manager.ts";
42
42
  import { HarnessInternalInferenceRuntime } from "./internal-inference/runtime/harness-runtime.ts";
43
+ import { withoutHarnessBackgroundWork } from "./internal-inference/runtime/disposable-session-env.ts";
43
44
  import {
44
45
  ConversationCheckpointCoordinator,
45
46
  ConversationCheckpointStrategy,
@@ -57,6 +58,9 @@ import type {
57
58
  AgentConfig,
58
59
  AgentConversationManager,
59
60
  } from "./agent/config.ts";
61
+ import { forgetPendingParts } from "./media/pending.ts";
62
+ import type { AgentConversationId } from "./agent-ids.ts";
63
+ import type { MediaConfig } from "./media/store.ts";
60
64
 
61
65
  export type {
62
66
  AdoptProviderSessionConfig,
@@ -88,6 +92,7 @@ export type {
88
92
 
89
93
  /** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
90
94
  export class Agent {
95
+ readonly media: MediaConfig;
91
96
  readonly id: AgentSessionId;
92
97
  readonly persistence: PersistenceBackend;
93
98
  readonly identity: AgentIdentityRuntime;
@@ -106,6 +111,18 @@ export class Agent {
106
111
  private detachInternalInferenceAudit?: () => void;
107
112
  private closed = false;
108
113
 
114
+ /** Remove a kept copy's bytes. Records keep its metadata and a ref that now resolves to nothing. */
115
+ async deleteMedia(ref: string): Promise<void> {
116
+ await (this.media.store ?? this.persistence.media)?.delete(ref);
117
+ }
118
+
119
+ /** Remove the bytes of every copy one conversation kept, and its waiting out-of-band parts. */
120
+ async deleteMediaForConversation(owner: AgentConversationId): Promise<void> {
121
+ forgetPendingParts(this, owner);
122
+ const store = this.media.store ?? this.persistence.media;
123
+ if (store) for (const media of await store.list(owner)) await store.delete(media.ref);
124
+ }
125
+
109
126
  private constructor(
110
127
  id: AgentSessionId,
111
128
  persistence: PersistenceBackend,
@@ -115,6 +132,7 @@ export class Agent {
115
132
  private readonly auditLog: ResolvedAgentAuditLogConfig | null,
116
133
  audit: AgentAuditRuntime | undefined,
117
134
  ) {
135
+ this.media = config.media ?? {};
118
136
  this.id = id;
119
137
  this.persistence = persistence;
120
138
  this.adapters = adapters;
@@ -169,7 +187,10 @@ export class Agent {
169
187
  ...(config.capture ? { captureConfig: config.capture } : {}),
170
188
  ...(config.auditLog && config.auditLog.capture ? { auditCaptureConfig: config.auditLog.capture } : {}),
171
189
  ...(config.conversationPersistence ? { conversationPersistence: config.conversationPersistence } : {}),
172
- defaults: config.conversationDefaults ?? {},
190
+ defaults: {
191
+ ...config.conversationDefaults,
192
+ ...(config.operationLifecycle ? { operationLifecycle: config.operationLifecycle } : {}),
193
+ },
173
194
  meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
174
195
  checkpointing,
175
196
  auditLog,
@@ -197,29 +218,31 @@ export class Agent {
197
218
  if (!persistence.internalInferences) {
198
219
  throw new Error("persistence backend does not support internal inference");
199
220
  }
221
+ const suppressBackgroundWork = inferenceConfig.suppressHarnessBackgroundWork !== false;
200
222
  const runtime = settings.runtime ?? new HarnessInternalInferenceRuntime({
201
- controllerConfig: (request) => ({
202
- adapter: adapters.require(request.adapterId),
203
- adapterId: request.adapterId,
204
- ...(config.conversationDefaults?.launcher
205
- ? { launcher: config.conversationDefaults.launcher }
206
- : {}),
207
- ...(config.conversationDefaults?.execPrefix
208
- ? { execPrefix: config.conversationDefaults.execPrefix }
209
- : {}),
210
- ...(config.conversationDefaults?.env ? { env: config.conversationDefaults.env } : {}),
211
- ...(config.conversationDefaults?.cwd ? { cwd: config.conversationDefaults.cwd } : {}),
212
- ...(config.conversationDefaults?.clientInfo
213
- ? { clientInfo: config.conversationDefaults.clientInfo }
214
- : {}),
215
- ...(config.conversationDefaults?.clientCapabilities
216
- ? { clientCapabilities: config.conversationDefaults.clientCapabilities }
217
- : {}),
218
- ...(config.conversationDefaults?.logger
219
- ? { logger: config.conversationDefaults.logger }
220
- : {}),
221
- ...(config.conversationDefaults?.wire ? { wire: config.conversationDefaults.wire } : {}),
222
- }),
223
+ controllerConfig: (request) => {
224
+ const adapter = adapters.require(request.adapterId);
225
+ const defaults = config.conversationDefaults;
226
+ const launch = suppressBackgroundWork
227
+ ? withoutHarnessBackgroundWork(request.adapterId, adapter, {
228
+ ...(defaults?.env ? { env: defaults.env } : {}),
229
+ ...(defaults?.launcher ? { launcher: defaults.launcher } : {}),
230
+ })
231
+ : { env: defaults?.env, launcher: defaults?.launcher };
232
+ return {
233
+ adapter,
234
+ adapterId: request.adapterId,
235
+ operationLifecycle: config.operationLifecycle ?? defaults?.operationLifecycle,
236
+ ...(launch.launcher ? { launcher: launch.launcher } : {}),
237
+ ...(defaults?.execPrefix ? { execPrefix: defaults.execPrefix } : {}),
238
+ ...(launch.env ? { env: launch.env } : {}),
239
+ ...(defaults?.cwd ? { cwd: defaults.cwd } : {}),
240
+ ...(defaults?.clientInfo ? { clientInfo: defaults.clientInfo } : {}),
241
+ ...(defaults?.clientCapabilities ? { clientCapabilities: defaults.clientCapabilities } : {}),
242
+ ...(defaults?.logger ? { logger: defaults.logger } : {}),
243
+ ...(defaults?.wire ? { wire: defaults.wire } : {}),
244
+ };
245
+ },
223
246
  });
224
247
  const strategies = [...(inferenceConfig.strategies ?? [])];
225
248
  if (checkpointing?.enabled) {
@@ -20,6 +20,7 @@ export interface AgentAuditCaptureConfig {
20
20
  readonly thinking?: RecordCaptureLevel;
21
21
  readonly activity?: RecordCaptureLevel;
22
22
  readonly error?: RecordCaptureLevel;
23
+ readonly cancellation?: RecordCaptureLevel;
23
24
  readonly metering?: "none" | "metadata" | "summary" | "raw";
24
25
  readonly agent_lifecycle?: RecordCaptureLevel;
25
26
  readonly identity?: RecordCaptureLevel;
@@ -56,6 +57,7 @@ export interface ResolvedAgentAuditCapturePolicy {
56
57
  readonly thinking: RecordCaptureLevel;
57
58
  readonly activity: RecordCaptureLevel;
58
59
  readonly error: RecordCaptureLevel;
60
+ readonly cancellation: RecordCaptureLevel;
59
61
  readonly metering: "none" | "metadata" | "summary" | "raw";
60
62
  readonly agent_lifecycle: RecordCaptureLevel;
61
63
  readonly identity: RecordCaptureLevel;
@@ -83,6 +85,7 @@ export const DEFAULT_AGENT_AUDIT_CAPTURE: ResolvedAgentAuditCapturePolicy = Obje
83
85
  thinking: "none",
84
86
  activity: "metadata",
85
87
  error: "content",
88
+ cancellation: "metadata",
86
89
  metering: "summary",
87
90
  agent_lifecycle: "metadata",
88
91
  identity: "metadata",
@@ -170,6 +173,7 @@ export function resolveAgentAuditCapture(
170
173
  thinking: general("thinking"),
171
174
  activity: general("activity"),
172
175
  error: general("error"),
176
+ cancellation: general("cancellation"),
173
177
  metering: specialized("metering", ["none", "metadata", "summary", "raw"]),
174
178
  agent_lifecycle: general("agent_lifecycle"),
175
179
  identity: general("identity"),
@@ -101,6 +101,9 @@ function projectRecordPayload(
101
101
  ...(level !== "metadata" && record.message ? { message: record.message } : {}),
102
102
  ...(level === "raw" && record.details ? { details: json(record.details) } : {}),
103
103
  };
104
+ case "cancellation":
105
+ return { ...base, cancellationId: record.cancellationId, state: record.state, reason: record.reason,
106
+ ...(record.outcome ? { outcome: record.outcome } : {}) };
104
107
  case "metering": {
105
108
  const metering = observation.meteringRecord;
106
109
  if (level === "raw" && metering) return json(metering);
@@ -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
  });
@@ -35,6 +35,9 @@ export function isMissingProviderSessionError(
35
35
  && message.toLowerCase() === "internal error: opencode service failure"
36
36
  && data?.service === "session"
37
37
  ) return true;
38
+ // ACP's standard "resource not found". This classifier only sees `session/load` failures, so the
39
+ // resource is the session (Claude reports a missing session this way).
40
+ if (value?.code === -32002) return true;
38
41
  const text = [
39
42
  message,
40
43
  safeJson(value?.data),
@@ -42,6 +45,8 @@ export function isMissingProviderSessionError(
42
45
  return [
43
46
  "failed to resolve rollout path",
44
47
  "no rollout found for thread id",
48
+ // Codex archives a deleted session; it cannot be loaded until unarchived outside the library.
49
+ "is archived. run `codex unarchive",
45
50
  "session not found",
46
51
  "unknown session",
47
52
  "no such session",
@@ -90,8 +95,10 @@ export async function buildRecoverySeed(
90
95
  return Object.freeze({
91
96
  prompt: [
92
97
  config.seedInstruction,
93
- `Continuation checkpoint through canonical sequence ${checkpoint.coveredSequence}:`,
94
- checkpoint.summary,
98
+ // An adoption baseline has no summary: only the messages after it are known.
99
+ ...(checkpoint.summary
100
+ ? [`Continuation checkpoint through canonical sequence ${checkpoint.coveredSequence}:`, checkpoint.summary]
101
+ : []),
95
102
  tail.length
96
103
  ? `Canonical messages after the checkpoint:\n${JSON.stringify(tail)}`
97
104
  : "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 = {
@@ -85,6 +105,8 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
85
105
  agentConversationId: conversationId,
86
106
  kind: "native_action" as const,
87
107
  timestamp: checkpoint.createdAt,
108
+ // The internal inference that wrote the summary is the operation this action belongs to.
109
+ operationId: result.internalInferenceId,
88
110
  action: "conversation_checkpoint",
89
111
  state: "completed" as const,
90
112
  output: {
@@ -114,6 +136,9 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
114
136
  }
115
137
 
116
138
  classifyError(error: unknown) {
139
+ if (error instanceof CheckpointSourceTooLargeError) {
140
+ return { kind: "terminal" as const, code: "checkpoint_source_too_large" };
141
+ }
117
142
  const message = error instanceof Error ? error.message : String(error);
118
143
  if (message.includes("source changed") || message.includes("coverage") || message.includes("source range")) {
119
144
  return { kind: "terminal" as const, code: "checkpoint_source_conflict" };