@qlairoslabs/acp-client 0.13.1-alpha.1 → 0.13.2-alpha.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.
Files changed (105) hide show
  1. package/CONSUMER_GUIDE.md +60 -26
  2. package/package.json +5 -1
  3. package/src/agent/config.ts +2 -0
  4. package/src/agent/native-operations.ts +1 -0
  5. package/src/agent-session.ts +11 -2
  6. package/src/agent.ts +4 -1
  7. package/src/index.ts +2 -0
  8. package/src/native/capabilities.ts +2 -2
  9. package/src/native/connection.ts +1 -1
  10. package/src/native/controller.ts +2 -1
  11. package/src/native/host-config.ts +2 -0
  12. package/src/native/host.ts +10 -0
  13. package/src/native/mcp.ts +47 -0
  14. package/src/native/recovery.ts +8 -7
  15. package/src/native/reminders/routine-guard.ts +4 -3
  16. package/src/native/reminders/routine-wire.ts +1 -1
  17. package/src/native-harness/README.md +58 -1
  18. package/src/native-harness/package.json +4 -0
  19. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  20. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  21. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  22. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  23. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  24. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  25. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  26. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  27. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  28. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  29. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  30. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  31. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  32. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  33. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  34. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  35. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  36. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  37. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  38. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  39. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  40. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  41. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  42. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  43. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  44. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  45. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  46. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  47. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  48. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  49. package/src/native-harness/src/contracts/agent.ts +3 -1
  50. package/src/native-harness/src/contracts/attachments.ts +62 -0
  51. package/src/native-harness/src/contracts/config-permissions.ts +13 -4
  52. package/src/native-harness/src/contracts/context.ts +1 -1
  53. package/src/native-harness/src/contracts/events.ts +2 -2
  54. package/src/native-harness/src/contracts/loop.ts +3 -3
  55. package/src/native-harness/src/contracts/mcp.ts +22 -0
  56. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  57. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  58. package/src/native-harness/src/contracts/protocol.ts +20 -4
  59. package/src/native-harness/src/contracts/session-file.ts +2 -1
  60. package/src/native-harness/src/contracts/session.ts +6 -1
  61. package/src/native-harness/src/contracts/storage.ts +23 -5
  62. package/src/native-harness/src/contracts/tools.ts +2 -0
  63. package/src/native-harness/src/contracts/web.ts +16 -0
  64. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  65. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  66. package/src/native-harness/src/index.ts +43 -11
  67. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  68. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  69. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  70. package/src/native-harness/src/interfaces/client.ts +8 -2
  71. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  72. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  73. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  74. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  75. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  76. package/src/native-harness/src/interfaces/protocol/server.ts +93 -29
  77. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +1 -0
  78. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  79. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  80. package/src/native-harness/src/kernel/channels.ts +19 -11
  81. package/src/native-harness/src/kernel/loop.ts +1 -1
  82. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  83. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  84. package/src/native-harness/src/runtime/config/paths.ts +3 -2
  85. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  86. package/src/native-harness/src/state/storage/archive.ts +95 -12
  87. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  88. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  89. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  90. package/src/native-harness/src/state/storage/engine.ts +194 -34
  91. package/src/native-harness/src/state/storage/inference.ts +30 -2
  92. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  93. package/src/native-harness/src/state/storage/memory.ts +18 -3
  94. package/src/native-harness/src/state/storage/reminder-archive.ts +2 -2
  95. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  96. package/src/native-harness/src/state/storage/sqlite.ts +51 -10
  97. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  98. package/src/native-harness/src/testing.ts +150 -55
  99. package/src/native-harness/src/util/attachment-input.ts +42 -0
  100. package/src/native-harness/src/util/config.ts +59 -12
  101. package/src/native-harness/src/util/mcp-config.ts +102 -0
  102. package/src/native-harness/src/util/web-config.ts +34 -0
  103. package/src/native-harness/src/util/web-usage.ts +33 -0
  104. package/src/steering/combine.ts +1 -0
  105. package/src/steering/contracts.ts +3 -0
@@ -0,0 +1,123 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import type { AttachmentMetadata, InputPart } from "../../contracts/attachments.ts";
3
+
4
+ /** Durable attachment rows live in the same SQLite transaction as the caller's
5
+ * inbox acceptance. The session owner is responsible for serialization with
6
+ * file publication and cleanup. No table or format change occurs on reads. */
7
+ export function sqliteAttachmentTables(db: Database) {
8
+ // Bun caches `query` statements; short-lived explicit statements must be
9
+ // finalized so the exclusive owner can close even after nested reads.
10
+ const query = <R = unknown, P extends any[] = any[]>(sql: string) => ({
11
+ get(...params: P): R | null { const statement = db.prepare<R, any[]>(sql); try { return statement.get(...params); } finally { statement.finalize(); } },
12
+ all(...params: P): R[] { const statement = db.prepare<R, any[]>(sql); try { return statement.all(...params); } finally { statement.finalize(); } },
13
+ run(...params: P) { const statement = db.prepare<R, any[]>(sql); try { return statement.run(...params); } finally { statement.finalize(); } },
14
+ });
15
+ const present = () => !!query<{ present: number }, []>(
16
+ "SELECT 1 AS present FROM sqlite_schema WHERE type='table' AND name='attachment_files'",
17
+ ).get();
18
+ const activate = () => {
19
+ db.exec(`CREATE TABLE IF NOT EXISTS attachment_files (
20
+ id TEXT PRIMARY KEY, channel TEXT NOT NULL, filename TEXT NOT NULL,
21
+ media_type TEXT NOT NULL, bytes INTEGER NOT NULL, sha256 TEXT NOT NULL,
22
+ ready_at TEXT NOT NULL
23
+ );
24
+ CREATE TABLE IF NOT EXISTS attachment_items (
25
+ attachment_id TEXT NOT NULL REFERENCES attachment_files(id),
26
+ item_id TEXT NOT NULL REFERENCES items(item_id),
27
+ PRIMARY KEY (attachment_id, item_id)
28
+ ) WITHOUT ROWID;
29
+ CREATE TABLE IF NOT EXISTS attachment_item_parts (
30
+ item_id TEXT PRIMARY KEY REFERENCES items(item_id), parts TEXT NOT NULL
31
+ ) WITHOUT ROWID;
32
+ CREATE INDEX IF NOT EXISTS attachment_items_by_item ON attachment_items(item_id);`);
33
+ const row = query<{ value: string }, []>("SELECT value FROM meta WHERE key='formatVersion'").get();
34
+ const format = Number(row?.value);
35
+ if (!Number.isSafeInteger(format) || format < 6 || format > 10) throw new Error("Unsupported session format");
36
+ const prior = format === 10 ? Number(query<{ value: string }, []>("SELECT value FROM meta WHERE key='webBaseFormat'").get()?.value) : format;
37
+ if (prior < 9) {
38
+ if (![6, 7, 8].includes(prior)) throw new Error("Invalid attachment base format");
39
+ query("INSERT INTO meta (key,value) VALUES ('attachmentBaseFormat', ?)").run(String(prior));
40
+ if (format === 10) query("UPDATE meta SET value='9' WHERE key='webBaseFormat'").run();
41
+ else query("UPDATE meta SET value='9' WHERE key='formatVersion'").run();
42
+ }
43
+ };
44
+ type Row = { id: string; channel: string; filename: string; media_type: string; bytes: number; sha256: string; ready_at: string };
45
+ const project = (row: Row) => ({ metadata: { id: row.id, channel: row.channel, filename: row.filename,
46
+ mediaType: row.media_type, bytes: row.bytes, sha256: row.sha256 }, readyAt: row.ready_at });
47
+ return {
48
+ baseFormat(): number | undefined {
49
+ const row = query<{ value: string }, []>("SELECT value FROM meta WHERE key='attachmentBaseFormat'").get();
50
+ return row ? Number(row.value) : undefined;
51
+ },
52
+ advanceBaseFormat(format: number) {
53
+ query("UPDATE meta SET value=? WHERE key='attachmentBaseFormat' AND CAST(value AS INTEGER) < ?").run(String(format), format);
54
+ },
55
+ hasRetained() {
56
+ return present() && !!query<{ yes: number }, []>("SELECT 1 AS yes FROM attachment_items LIMIT 1").get();
57
+ },
58
+ readyIds(): string[] {
59
+ return present() ? query<{ id: string }, []>("SELECT id FROM attachment_files ORDER BY id").all().map(row => row.id) : [];
60
+ },
61
+ retained() {
62
+ if (!present()) return [];
63
+ return query<Row, []>(`SELECT f.* FROM attachment_files f
64
+ WHERE EXISTS (SELECT 1 FROM attachment_items a WHERE a.attachment_id=f.id) ORDER BY f.id`).all().map(project);
65
+ },
66
+ restore(baseFormat: 6 | 7 | 8, records: readonly { metadata: AttachmentMetadata; readyAt: string }[]) {
67
+ activate();
68
+ query("INSERT INTO meta (key,value) VALUES ('attachmentBaseFormat', ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(String(baseFormat));
69
+ for (const record of records) this.publish(record.metadata, record.readyAt);
70
+ },
71
+ /** Caller executes inside its owner transaction after flushing file bytes. */
72
+ publish(metadata: AttachmentMetadata, readyAt: string) {
73
+ activate();
74
+ query("INSERT INTO attachment_files VALUES (?, ?, ?, ?, ?, ?, ?)")
75
+ .run(metadata.id, metadata.channel, metadata.filename, metadata.mediaType, metadata.bytes, metadata.sha256, readyAt);
76
+ },
77
+ get(id: string) {
78
+ if (!present()) return undefined;
79
+ const row = query<Row, [string]>("SELECT * FROM attachment_files WHERE id=?").get(id);
80
+ return row ? project(row) : undefined;
81
+ },
82
+ /** Call within the same transaction that inserts the accepted item. */
83
+ associate(id: string, itemId: string) {
84
+ if (!present()) throw new Error("Unknown attachment");
85
+ query("INSERT OR IGNORE INTO attachment_items VALUES (?, ?)").run(id, itemId);
86
+ },
87
+ /** Caller inserts the item and links every attachment in the same owner
88
+ * transaction. Retained order and boundaries do not depend on the links. */
89
+ saveParts(itemId: string, parts: readonly InputPart[]) {
90
+ if (!present()) throw new Error("Attachment storage has not been activated");
91
+ query("INSERT INTO attachment_item_parts VALUES (?, ?)").run(itemId, JSON.stringify(parts));
92
+ for (const part of parts) if (part.type === "attachment") this.associate(part.id, itemId);
93
+ },
94
+ parts(itemId: string): InputPart[] | undefined {
95
+ if (!present()) return undefined;
96
+ const row = query<{ parts: string }, [string]>("SELECT parts FROM attachment_item_parts WHERE item_id=?").get(itemId);
97
+ return row ? JSON.parse(row.parts) as InputPart[] : undefined;
98
+ },
99
+ isRetained(id: string) {
100
+ return present() && !!query<{ yes: number }, [string]>("SELECT 1 AS yes FROM attachment_items WHERE attachment_id=? LIMIT 1").get(id);
101
+ },
102
+ isTimelineVisible(id: string) {
103
+ return present() && !!query<{ yes: number }, [string]>(`SELECT 1 AS yes FROM attachment_items a
104
+ JOIN items i ON i.item_id=a.item_id WHERE a.attachment_id=? AND i.entry_seq IS NOT NULL LIMIT 1`).get(id);
105
+ },
106
+ /** Candidates are advisory: the owner must recheck under the same fence as
107
+ * acceptance immediately before removing any metadata or bytes. */
108
+ unreferencedBefore(readyAt: string) {
109
+ if (!present()) return [];
110
+ return query<Row, [string]>(`SELECT f.* FROM attachment_files f WHERE f.ready_at <= ?
111
+ AND NOT EXISTS (SELECT 1 FROM attachment_items a WHERE a.attachment_id=f.id) ORDER BY f.id`).all(readyAt).map(project);
112
+ },
113
+ /** Within the owner transaction, compete with acceptance on the same
114
+ * database. Once metadata is removed, a crash before unlink leaves only an
115
+ * orphan that the next owner can reclaim. */
116
+ reclaim(id: string, readyAt: string): boolean {
117
+ if (!present()) return false;
118
+ const result = query(`DELETE FROM attachment_files WHERE id=? AND ready_at <= ?
119
+ AND NOT EXISTS (SELECT 1 FROM attachment_items WHERE attachment_id=?)`).run(id, readyAt, id);
120
+ return result.changes === 1;
121
+ },
122
+ };
123
+ }
@@ -1,3 +1,4 @@
1
+ import { validCommittedWebUsage, validWebDispatch } from "../../util/web-usage.ts";
1
2
  import { resolveRoutineZone } from "../../capabilities/reminders/iana-zones.ts";
2
3
  import { SESSION_INTAKE_LIMITS } from "../../util/intake.ts";
3
4
  import { advanceRoutine } from "../../capabilities/reminders/routine-advance.ts";
@@ -6,6 +7,9 @@ import { createRoutineEvaluator } from "../../capabilities/reminders/routine-sch
6
7
  import { isRoutine, prepareRoutineRow } from "./routine-row.ts";
7
8
  import { unattendedAdmission } from "../../capabilities/reminders/unattended.ts";
8
9
  import { normalizeReminderSchedule, resolveAgentReminder } from "../../util/reminder-schedule.ts";
10
+ import { createHash } from "node:crypto";
11
+ import { validateMixedParts, mixedPartsSignature } from "../../util/attachment-input.ts";
12
+ import { encodeSessionFile, SessionFileError } from "./session-file.ts";
9
13
  import { applyReminderChange } from "./reminder-change.ts";
10
14
  import type { OneOffReminder, Reminder, ReminderChannelEvent } from "../../contracts/reminders.ts";
11
15
  import type { ReminderTables } from "./reminder-tables.ts";
@@ -48,6 +52,9 @@ export const emptyModelState = (): ModelState => ({ nextCall: 1, calls: [], item
48
52
  * rule of the storage contract; a backend only stores rows and makes
49
53
  * `transaction` atomic (all writes of a throwing callback are undone). */
50
54
  export interface Tables extends ContextRows {
55
+ web: import("./web-tables.ts").WebTables;
56
+ /** SQLite attachment metadata, absent in adapters without managed bytes. */
57
+ attachments?: ReturnType<typeof import("./attachment-tables.ts").sqliteAttachmentTables>;
51
58
  reminders: ReminderTables;
52
59
  retrievalCandidates(terms: readonly string[], channel: string | undefined, limit: number): Array<{ seq: number; bytes: number }>;
53
60
  retrievalEntry(seq: number): TimelineEntry | undefined;
@@ -124,8 +131,9 @@ function cleanName(name: unknown): string {
124
131
  }
125
132
 
126
133
  /** The contract's exact signature; identical for both adapters and archives. */
127
- export function signatureOf(item: Pick<AcceptItem, "kind" | "channelId" | "senderId" | "sourceChannelId" | "text" | "explicitPolicy" | "externalSource" | "inheritedPolicyNames">): string {
128
- return item.kind === "external_notice" ? externalNoticeSignature(item.channelId, item.externalSource, item.text, item.inheritedPolicyNames ?? []) : policyItemSignature(item);
134
+ export function signatureOf(item: Pick<AcceptItem, "kind" | "channelId" | "senderId" | "sourceChannelId" | "text" | "explicitPolicy" | "externalSource" | "inheritedPolicyNames" | "parts">): string {
135
+ const legacy = item.kind === "external_notice" ? externalNoticeSignature(item.channelId, item.externalSource, item.text, item.inheritedPolicyNames ?? []) : policyItemSignature(item);
136
+ return item.parts === undefined ? legacy : createHash("sha256").update(JSON.stringify([legacy, mixedPartsSignature(item.parts)])).digest("hex");
129
137
  }
130
138
 
131
139
  /** Strict JSON data: what survives a JSON round trip unchanged. */
@@ -151,8 +159,10 @@ function checkMessage(message: unknown): Stored {
151
159
  const m = message as Record<string, unknown>;
152
160
  const keys = Object.keys(m);
153
161
  if (m.role === "tool") {
154
- if (typeof m.content !== "string" || !text(m.callId) || keys.some(key => !["role", "content", "callId", "outcome"].includes(key)))
162
+ if (typeof m.content !== "string" || !text(m.callId) || keys.some(key => !["role", "content", "callId", "outcome", "usage", "webNoDispatch"].includes(key)))
155
163
  fail("invalid_input", "Tool result needs content and callId");
164
+ if (m.webNoDispatch !== undefined && m.webNoDispatch !== true) fail("invalid_input", "Invalid web refusal evidence");
165
+ if (m.usage !== undefined && !validCommittedWebUsage(m.usage)) fail("invalid_input", "Invalid web usage");
156
166
  // Decision 0021: an optional, typed outcome. Checked here so a stored
157
167
  // result never claims a status the invocation view cannot interpret.
158
168
  if (m.outcome !== undefined) {
@@ -175,7 +185,7 @@ function checkMessage(message: unknown): Stored {
175
185
  }
176
186
 
177
187
  function session(meta: Meta): StoredSession {
178
- return { sessionId: meta.sessionId, formatVersion: meta.formatVersion >= 8 ? 8 : meta.formatVersion === 7 ? 7 : 6, createdAt: meta.createdAt,
188
+ return { sessionId: meta.sessionId, formatVersion: meta.formatVersion >= 10 ? 10 : meta.formatVersion >= 9 ? 9 : meta.formatVersion >= 8 ? 8 : meta.formatVersion === 7 ? 7 : 6, createdAt: meta.createdAt,
179
189
  lifecycle: meta.lifecycle, compatibilityKey: meta.compatibilityKey };
180
190
  }
181
191
 
@@ -198,6 +208,7 @@ export function readSnapshot(tables: Tables): StorageSnapshot {
198
208
  const id = tables.getModelState()?.entryIds[String(entry.seq)];
199
209
  return id ? { ...entry, messageId: id } : entry;
200
210
  }),
211
+ ...(tables.web.baseFormat() === undefined ? {} : { webDispatches: tables.web.all() }),
201
212
  modelCalls: tables.getModelState()?.calls ?? [], scriptPositions: tables.getModelState()?.scriptPositions ?? {},
202
213
  ...(tables.getRevokedTools() === undefined ? {} : { revokedTools: tables.getRevokedTools()! }),
203
214
  };
@@ -222,8 +233,20 @@ export function initialIntakeHasParticipant(items: readonly StoredItem[]) {
222
233
  return false;
223
234
  }
224
235
 
236
+ /** Physical web format 10 retains the prior logical feature format separately. */
237
+ function logicalFormat(tables: Tables, meta: Meta): number {
238
+ const physical = meta.formatVersion === 10 ? tables.web.baseFormat() ?? 0 : meta.formatVersion;
239
+ return physical === 9 ? tables.attachments?.baseFormat() ?? 0 : physical;
240
+ }
241
+ function advancePriorFormat(tables: Tables, meta: Meta, format: 7 | 8) {
242
+ const physical = meta.formatVersion === 10 ? tables.web.baseFormat() ?? 0 : meta.formatVersion;
243
+ if (physical === 9) tables.attachments?.advanceBaseFormat(format);
244
+ else if (meta.formatVersion === 10) tables.web.advanceBaseFormat(format);
245
+ else meta.formatVersion = Math.max(meta.formatVersion, format);
246
+ }
247
+
225
248
  function routineHeldChannels(tables: Tables, meta: Meta): string[] {
226
- const limit = meta.formatVersion >= 8 ? tables.reminders.guardLimit() : undefined;
249
+ const limit = logicalFormat(tables, meta) >= 8 ? tables.reminders.guardLimit() : undefined;
227
250
  if (limit === undefined) return [];
228
251
  return tables.channels().filter(({ channelId, lifecycle }) => {
229
252
  if (lifecycle !== "open" || tables.reminders.guardSpent(channelId) < limit) return false;
@@ -232,7 +255,7 @@ function routineHeldChannels(tables: Tables, meta: Meta): string[] {
232
255
  }
233
256
 
234
257
  function refreshReminderWake(tables: Tables, meta: Meta) {
235
- if (meta.formatVersion < 7) return;
258
+ if (logicalFormat(tables, meta) < 7) return;
236
259
  const wake = tables.reminders.wake();
237
260
  const nextDueAt = meta.lifecycle === "running" ? tables.reminders.eligible(null, 1, routineHeldChannels(tables, meta))[0]?.reminder.nextRunAt ?? null : null;
238
261
  if (nextDueAt !== wake.nextDueAt) tables.reminders.setWake({ nextDueAt, reminderRevision: wake.reminderRevision + 1 });
@@ -249,13 +272,14 @@ export function bindUnattendedGuard(tables: Tables, requested: number | undefine
249
272
  if (requested === undefined || tables.reminders.guardLimit() !== undefined) return;
250
273
  tables.reminders.bindGuard(requested);
251
274
  const meta = tables.getMeta();
252
- tables.setMeta({ ...meta, formatVersion: 8, revision: meta.revision + 1 });
275
+ advancePriorFormat(tables, meta, 8);
276
+ tables.setMeta({ ...meta, revision: meta.revision + 1 });
253
277
  }
254
278
 
255
279
  type ReminderDeliveryEvent = { channel: string; event: ReminderChannelEvent };
256
280
 
257
281
  function migrateRoutineZones(tables: Tables, meta: Meta, events: ReminderDeliveryEvent[]) {
258
- if (meta.formatVersion < 8) return false;
282
+ if (logicalFormat(tables, meta) < 8) return false;
259
283
  const version = resolveRoutineZone("Etc/UTC")!.timezoneVersion;
260
284
  let after = 0, changed = false;
261
285
  for (;;) {
@@ -348,6 +372,9 @@ function unanswered(tables: Tables, turnId: number): string[] {
348
372
  }
349
373
 
350
374
  /** Older states lack dispatch evidence and retain the conservative old rule. */
375
+ function stateDispatched(turn: TurnRow, callId: string): boolean {
376
+ return (turn.state.status === "running" || turn.state.status === "suspended") && !!turn.state.dispatchedCallIds?.includes(callId);
377
+ }
351
378
  function uncertain(tables: Tables, turn: TurnRow): string[] {
352
379
  const open = unanswered(tables, turn.turnId);
353
380
  if (turn.state.status !== "running" && turn.state.status !== "suspended") return open;
@@ -356,13 +383,14 @@ function uncertain(tables: Tables, turn: TurnRow): string[] {
356
383
  }
357
384
 
358
385
  /** The contract over any backend. `ownerKey` is the key passed to this open. */
359
- export function createEngine(tables: Tables, ownerKey: string, release: () => void, config?: ManagedConfig, incompatibleViewOnly = false, recoveredReminderEvents: ReminderDeliveryEvent[] = []): SessionStorage {
386
+ export function createEngine(tables: Tables, ownerKey: string, release: () => void, config?: ManagedConfig, incompatibleViewOnly = false, recoveredReminderEvents: ReminderDeliveryEvent[] = [],
387
+ readFiles?: (records: ReturnType<NonNullable<Tables["attachments"]>["retained"]>, maxBytes: number) => NonNullable<SessionArchive["attachmentState"]>["files"]): SessionStorage {
360
388
  let closed = false;
361
389
  // This is the config validated at open, not the separately mutable saved copy.
362
390
  const ownerSnapshot = config === undefined ? undefined : structuredClone(config);
363
391
  const now = () => new Date().toISOString();
364
392
 
365
- function run<T>(work: (meta: Meta) => T, readOnly = false): StorageResult<T> {
393
+ function run<T>(work: (meta: Meta) => T, readOnly = false, alreadyDetached = false): StorageResult<T> {
366
394
  if (closed) return failure(new Fail("closed", "Storage handle is closed"));
367
395
  if (incompatibleViewOnly && !readOnly) return failure(new Fail("incompatible", "Stored policy is not available in the open configuration"));
368
396
  try {
@@ -372,7 +400,7 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
372
400
  if (!readOnly && JSON.stringify(meta) !== before) refreshReminderWake(tables, meta);
373
401
  if (JSON.stringify(meta) !== before) tables.setMeta(meta);
374
402
  // Results never alias rows a backend may keep in memory.
375
- return { ok: true as const, value: structuredClone(value), revision: meta.revision };
403
+ return { ok: true as const, value: alreadyDetached ? value : structuredClone(value), revision: meta.revision };
376
404
  });
377
405
  } catch (error) { return failure(error); }
378
406
  }
@@ -383,14 +411,29 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
383
411
  if (turn.state.status !== "running") fail("invalid_state", `Turn ${turnId} is ${turn.state.status}, not running`);
384
412
  return turn;
385
413
  }
414
+ function imageBytes(item: StoredItem): number {
415
+ let total = 0;
416
+ for (const part of item.parts ?? []) if (part.type === "attachment") {
417
+ const metadata = tables.attachments?.get(part.id)?.metadata;
418
+ if (!metadata) fail("storage_failure", `Attachment metadata unavailable: ${part.id}`);
419
+ if (metadata!.mediaType.startsWith("image/")) total += metadata!.bytes;
420
+ }
421
+ return total;
422
+ }
423
+ function turnImageBytes(turnId: number | undefined): number {
424
+ return turnId === undefined ? 0 : tables.itemsOfTurn(turnId).reduce((sum, item) => sum + imageBytes(item), 0);
425
+ }
386
426
  function boundaryPending(channelId: string, intake?: IntakeLimit, turnId?: number): StoredItem[] {
387
- if (!intake) return tables.pendingItems(channelId);
388
- const already = turnId === undefined ? [] : tables.contextInputs(turnId, tables.contextPreviousResponse(turnId), intake.maxTakenItems);
389
- const slots = intake.maxTakenItems - already.length;
427
+ const already = !intake || turnId === undefined ? [] : tables.contextInputs(turnId, tables.contextPreviousResponse(turnId), intake.maxTakenItems);
428
+ const slots = intake ? intake.maxTakenItems - already.length : Number.MAX_SAFE_INTEGER;
390
429
  if (slots <= 0) return [];
391
- let bytes = intake.maxTakenTextBytes - already.reduce((sum, row) => sum + (row.textBytes ?? 0), 0);
430
+ let bytes = intake ? intake.maxTakenTextBytes - already.reduce((sum, row) => sum + (row.textBytes ?? 0), 0) : Number.MAX_SAFE_INTEGER;
431
+ let activeImages = turnImageBytes(turnId);
392
432
  const selected: StoredItem[] = [];
393
433
  for (const item of tables.pendingItems(channelId, slots)) {
434
+ const images = imageBytes(item);
435
+ if (activeImages + images > 40 * 1024 * 1024) break;
436
+ activeImages += images;
394
437
  bytes -= byteLength(item.text);
395
438
  // A legacy oversized head advances alone and gets a typed build failure.
396
439
  if (bytes < 0 && (selected.length || already.length)) break;
@@ -406,7 +449,7 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
406
449
  from: item.senderId, kind: item.kind, ...(item.sourceChannelId ? { sourceChannelId: item.sourceChannelId } : {}),
407
450
  ...(item.externalSource !== undefined ? { externalSource: item.externalSource } : {}),
408
451
  itemId: item.itemId, message: { role: "user", content: item.kind !== "participant_message" ? item.text
409
- : `Participant: ${JSON.stringify(item.senderId)}\n\n${item.text}` } };
452
+ : `Participant: ${JSON.stringify(item.senderId)}\n\n${item.text}`, ...(item.parts ? { parts: item.parts } : {}) } };
410
453
  tables.addEntry(entry);
411
454
  const taken: StoredItem = { ...item, milestone: "taken", turnId: turn.turnId, entrySeq: entry.seq };
412
455
  tables.putItem(taken);
@@ -443,8 +486,12 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
443
486
  const requireCompatible = () => {
444
487
  if (!referencesCompatible(tables, activeConfig)) fail("incompatible", "A stored policy no longer exists");
445
488
  };
446
- const turnFingerprint = (turn: TurnRow) => fingerprint(activeConfig, contributingPolicies(tables.itemsOfTurn(turn.turnId)
447
- .map(item => item.policy ?? { resolved: legacy, inherited: [] })));
489
+ let mcpCatalog: string | undefined;
490
+ const turnFingerprint = (turn: TurnRow) => {
491
+ const policy = fingerprint(activeConfig, contributingPolicies(tables.itemsOfTurn(turn.turnId)
492
+ .map(item => item.policy ?? { resolved: legacy, inherited: [] })));
493
+ return mcpCatalog === undefined ? policy : JSON.stringify([policy, "mcp-v1", mcpCatalog]);
494
+ };
448
495
  const compatible = (turn: TurnRow) => {
449
496
  try { return turn.compatibilityKey === ownerKey && turn.state.status === "suspended" && turn.state.checkpoint.policyFingerprint === turnFingerprint(turn); }
450
497
  catch { return false; }
@@ -472,9 +519,16 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
472
519
  }
473
520
  if (changed.length) tables.setModelState(state, changed);
474
521
  };
475
- const accept = (meta: Meta, input: AcceptItem, maxInputBytes?: number) => {
522
+ const accept = (meta: Meta, input: AcceptItem, maxInputBytes?: number, options?: { imageInput?: boolean }) => {
476
523
  const external = input?.kind === "external_notice";
477
- if (!external) requireCompatible();
524
+ if (!external && input?.parts === undefined) requireCompatible();
525
+ if (input?.parts !== undefined) {
526
+ if (input.kind !== "participant_message") fail("invalid_input", "Only participant messages can carry attachments");
527
+ try { input = { ...input, parts: validateMixedParts(input.parts) }; }
528
+ catch (error) { fail((error as { code?: string }).code === "transfer_limit" ? "transfer_limit" : "invalid_input", String(error)); }
529
+ const textParts = input.parts!.filter(part => part.type === "text").map(part => (part as { text: string }).text).join("\n");
530
+ if (input.text !== textParts) fail("invalid_input", "Text projection does not match ordered parts");
531
+ }
478
532
  if (external && (!text(input.itemId) || !text(input.channelId) || !text(input.text)
479
533
  || (input.externalSource !== undefined && !text(input.externalSource))
480
534
  || !Array.isArray(input.inheritedPolicyNames) || !Array.from(input.inheritedPolicyNames).every(text)
@@ -491,8 +545,23 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
491
545
  return { item: known, duplicate: true };
492
546
  }
493
547
  }
548
+ if (!external && input?.parts !== undefined) requireCompatible();
549
+ if (input?.parts) {
550
+ const attachments = tables.attachments;
551
+ if (!attachments) fail("incompatible", "Managed attachments are unavailable in this store");
552
+ let imageBytes = 0;
553
+ for (const part of input.parts) if (part.type === "attachment") {
554
+ const metadata = attachments!.get(part.id)?.metadata;
555
+ if (!metadata || metadata.channel !== input.channelId) fail("not_found", "Unknown attachment");
556
+ if (metadata!.mediaType.startsWith("image/")) {
557
+ if (!options?.imageInput) fail("unsupported_image", "Image input is unsupported");
558
+ imageBytes += metadata!.bytes;
559
+ }
560
+ }
561
+ if (imageBytes > 40 * 1024 * 1024) fail("transfer_limit", "Input image budget exceeded");
562
+ }
494
563
  const notice = shaped && input.kind === "channel_notice";
495
- if (!shaped || !(notice || external || input.kind === "participant_message") || ![input.channelId, input.senderId, input.text].every(text)
564
+ if (!shaped || !(notice || external || input.kind === "participant_message") || ![input.channelId, input.senderId].every(text) || (input.parts === undefined && !text(input.text))
496
565
  || (input.itemId !== undefined && !text(input.itemId))
497
566
  || (notice ? !text(input.sourceChannelId) : input.sourceChannelId !== undefined))
498
567
  fail("invalid_input", "Item needs kind, channelId, senderId and text; a notice also needs sourceChannelId");
@@ -534,7 +603,7 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
534
603
  }
535
604
  const item: StoredItem = { itemId, kind: input.kind, channelId: input.channelId, senderId: external ? input.externalSource ?? "host" : input.senderId,
536
605
  ...(external ? { inheritedPolicyNames: inherited, ...(input.externalSource === undefined ? {} : { externalSource: input.externalSource }) } : {}),
537
- ...(notice ? { sourceChannelId: input.sourceChannelId } : {}), ...(input.explicitPolicy == null ? {} : { explicitPolicy: input.explicitPolicy }), text: input.text,
606
+ ...(notice ? { sourceChannelId: input.sourceChannelId } : {}), ...(input.explicitPolicy == null ? {} : { explicitPolicy: input.explicitPolicy }), text: input.text, ...(input.parts ? { parts: input.parts } : {}),
538
607
  signature: signatureOf(input), policy: { ...(input.explicitPolicy == null ? {} : { explicit: input.explicitPolicy }), resolved, inherited },
539
608
  acceptedSeq: seq(meta), acceptedAt: now(), milestone: "received" };
540
609
  if (!notice && !external) {
@@ -542,13 +611,14 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
542
611
  tables.addParticipant(item.senderId);
543
612
  }
544
613
  tables.putItem(item);
614
+ if (input.parts) tables.attachments!.saveParts(itemId, input.parts);
545
615
  return { item, duplicate: false };
546
616
  };
547
617
  const reminders = tables.reminders;
548
618
  const activateReminders = (meta: Meta) => {
549
- if (meta.formatVersion < 7) {
619
+ if (logicalFormat(tables, meta) < 7) {
550
620
  reminders.activate();
551
- meta.formatVersion = 7;
621
+ advancePriorFormat(tables, meta, 7);
552
622
  }
553
623
  };
554
624
  const putReminder = (meta: Meta, reminder: Reminder, defaultedExpiry?: boolean, original?: string) => {
@@ -577,6 +647,39 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
577
647
  }
578
648
  }
579
649
  return {
650
+ registerReadyAttachment: metadata => run(meta => {
651
+ if (!tables.attachments) fail("incompatible", "Managed attachments are unavailable in this store");
652
+ if (!metadata || typeof metadata.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(metadata.id)
653
+ || !text(metadata.channel) || typeof metadata.filename !== "string" || metadata.filename.length === 0 || !metadata.filename.isWellFormed()
654
+ || Buffer.byteLength(metadata.filename) > 255 || /[\u0000-\u001f\u007f-\u009f]/u.test(metadata.filename)
655
+ || typeof metadata.mediaType !== "string" || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(metadata.mediaType) || metadata.mediaType.length > 127
656
+ || !Number.isSafeInteger(metadata.bytes) || metadata.bytes <= 0 || metadata.bytes > 20 * 1024 * 1024
657
+ || !/^[a-f0-9]{64}$/.test(metadata.sha256)) fail("invalid_input", "Invalid attachment metadata");
658
+ channelOf(metadata.channel);
659
+ const attachments = tables.attachments!;
660
+ if (attachments.get(metadata.id)) fail("already_exists", "Attachment ID already exists");
661
+ attachments.publish(metadata, now());
662
+ if (meta.formatVersion === 10) tables.web.advanceBaseFormat(9);
663
+ else meta.formatVersion = 9;
664
+ seq(meta);
665
+ }),
666
+ readManagedAttachment: id => run(() => {
667
+ const attachments = tables.attachments;
668
+ if (!attachments || !text(id)) return undefined;
669
+ const row = attachments.get(id);
670
+ return row ? { metadata: row.metadata, timelineVisible: attachments.isTimelineVisible(id) } : undefined;
671
+ }, true),
672
+ managedAttachmentIds: () => run(() => tables.attachments?.readyIds() ?? [], true),
673
+ unreferencedAttachments: readyBefore => run(() => {
674
+ if (!Number.isFinite(Date.parse(readyBefore))) fail("invalid_input", "Invalid cleanup deadline");
675
+ return tables.attachments?.unreferencedBefore(readyBefore).map(row => row.metadata) ?? [];
676
+ }, true),
677
+ reclaimAttachment: (id, readyBefore) => run(meta => {
678
+ if (!text(id) || !Number.isFinite(Date.parse(readyBefore))) fail("invalid_input", "Invalid cleanup request");
679
+ const removed = tables.attachments?.reclaim(id, readyBefore) ?? false;
680
+ if (removed) seq(meta);
681
+ return removed;
682
+ }),
580
683
  startCall: (turnId, itemIds) => run(meta => {
581
684
  if (!/^[1-9]\d*$/.test(turnId) || !Number.isSafeInteger(Number(turnId))) fail("invalid_input", "Invalid turn ID");
582
685
  const turn = running(Number(turnId));
@@ -654,7 +757,7 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
654
757
  const calls = rows.slice(0, limit);
655
758
  return { calls, ...(rows.length > limit ? { next: calls.at(-1)!.callId } : {}) };
656
759
  }, true),
657
- acceptItem: (input, maxInputBytes) => run(meta => accept(meta, input, maxInputBytes), input?.kind === "external_notice"),
760
+ acceptItem: (input, maxInputBytes, options) => run(meta => accept(meta, input, maxInputBytes, options), input?.kind === "external_notice"),
658
761
 
659
762
  changeReminder: (change, wallTime) => run(meta => {
660
763
  requireCompatible();
@@ -677,7 +780,9 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
677
780
  },
678
781
  saveReceipt(receipt) {
679
782
  activateReminders(meta);
680
- if (routineSchedule) meta.formatVersion = 8;
783
+ if (routineSchedule) {
784
+ advancePriorFormat(tables, meta, 8);
785
+ }
681
786
  reminders.saveReceipt(receipt);
682
787
  seq(meta);
683
788
  },
@@ -831,7 +936,7 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
831
936
  if (tables.liveTurn(channel.channelId)) return null;
832
937
  const pending = boundaryPending(channelId, intake);
833
938
  if (!pending.length) return null;
834
- const limit = meta.formatVersion >= 8 ? reminders.guardLimit() : undefined;
939
+ const limit = logicalFormat(tables, meta) >= 8 ? reminders.guardLimit() : undefined;
835
940
  if (limit !== undefined) {
836
941
  const spent = reminders.guardSpent(channelId);
837
942
  const admission = unattendedAdmission(limit, spent, pending.some(item => item.kind === "participant_message"));
@@ -866,17 +971,32 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
866
971
  if (message.calls.length && turn.state.status === "running" && turn.state.dispatchedCallIds === undefined)
867
972
  tables.putTurn({ ...turn, state: { ...turn.state, dispatchedCallIds: [] } });
868
973
  } else if (!open.includes(message.callId)) fail("invalid_input", `No unanswered call ${message.callId} in this turn`);
974
+ if (message.role === "tool" && message.webNoDispatch) {
975
+ const call = tables.entriesOfTurn(turnId).flatMap(entry => entry.message.role === "assistant" ? entry.message.calls : []).find(candidate => candidate.id === message.callId);
976
+ if (!call || !["web_search", "web_fetch"].includes(call.name) || message.outcome?.status !== "skipped" || stateDispatched(turn, message.callId)) fail("invalid_input", "Invalid web refusal");
977
+ tables.web.activate(meta.formatVersion);
978
+ meta.formatVersion = 10;
979
+ }
980
+ if (message.role === "tool" && message.usage !== undefined && !tables.web.all().some(record => record.turnId === turnId && record.callId === message.callId && record.evidence.paid))
981
+ fail("invalid_input", "Web usage needs paid dispatch evidence");
869
982
  const entry: TimelineEntry = { seq: seq(meta), at: now(), channelId: turn.channelId, turnId,
870
983
  from: message.role === "tool" ? "tool" : "agent", message: structuredClone(message) };
871
984
  tables.addEntry(entry);
872
985
  return entry;
873
986
  }),
874
987
 
875
- markToolDispatched: (turnId, callId) => run(meta => {
988
+ markToolDispatched: (turnId, callId, evidence) => run(meta => {
876
989
  const turn = running(turnId);
877
990
  const state = turn.state.status === "running" ? turn.state : fail("invalid_state", "Turn is not running");
878
991
  if (!text(callId) || !unanswered(tables, turnId).includes(callId)
879
992
  || state.dispatchedCallIds?.includes(callId)) fail("invalid_state", "Call is not an undispatched outstanding call of this turn");
993
+ if (evidence !== undefined) {
994
+ if (!validWebDispatch(evidence)) fail("invalid_input", "Invalid web dispatch evidence");
995
+ const call = tables.entriesOfTurn(turnId).flatMap(entry => entry.message.role === "assistant" ? entry.message.calls : []).find(candidate => candidate.id === callId);
996
+ if (!call || call.name !== evidence.operation) fail("invalid_input", "Web dispatch operation does not match call");
997
+ tables.web.add({ turnId, callId, evidence }, meta.formatVersion);
998
+ meta.formatVersion = 10;
999
+ }
880
1000
  tables.putTurn({ ...turn, state: { ...state, dispatchedCallIds: [...(state.dispatchedCallIds ?? []), callId] } });
881
1001
  seq(meta);
882
1002
  }),
@@ -898,7 +1018,9 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
898
1018
  if (!last || last.role !== "assistant" || last.calls.length)
899
1019
  fail("invalid_state", "Completion needs a final assistant response without tool calls");
900
1020
  const pending = tables.pendingCount(turn.channelId);
901
- if (pending) return { finished: false as const, pending };
1021
+ const head = pending ? tables.pendingItems(turn.channelId, 1)[0] : undefined;
1022
+ const imageBlocked = !!head && turnImageBytes(turnId) + imageBytes(head) > 40 * 1024 * 1024;
1023
+ if (pending && !imageBlocked) return { finished: false as const, pending };
902
1024
  const done: TurnRow = { ...turn, state: { status: "completed" } };
903
1025
  tables.putTurn(done); settle(turn.channelId); seq(meta);
904
1026
  return { finished: true as const, turn: full(done) };
@@ -1072,7 +1194,11 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
1072
1194
  }),
1073
1195
 
1074
1196
  ownerConfig: () => run(() => ownerSnapshot, true),
1075
- unattendedGuard: () => run(meta => meta.formatVersion >= 8 ? reminders.guardLimit() : undefined, true),
1197
+ unattendedGuard: () => run(meta => logicalFormat(tables, meta) >= 8 ? reminders.guardLimit() : undefined, true),
1198
+ bindMcpCatalog(value) {
1199
+ if (mcpCatalog !== undefined) throw new Error("MCP catalog already bound");
1200
+ mcpCatalog = value;
1201
+ },
1076
1202
  executionCompatible: () => run(() => !incompatibleViewOnly && referencesCompatible(tables, activeConfig), true),
1077
1203
  importedConfig: () => run(() => tables.getConfig(), true),
1078
1204
  saveConfig: value => run(() => {
@@ -1091,7 +1217,7 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
1091
1217
  items: channels.flatMap(channel => tables.pendingItems(channel.channelId)) };
1092
1218
  }, true),
1093
1219
  readReadyChannels: intake => run(meta => {
1094
- const limit = meta.formatVersion >= 8 ? reminders.guardLimit() : undefined;
1220
+ const limit = logicalFormat(tables, meta) >= 8 ? reminders.guardLimit() : undefined;
1095
1221
  return { lifecycle: meta.lifecycle, channels: tables.channels()
1096
1222
  .filter(({ lifecycle, channelId }) => lifecycle === "open" && tables.pendingCount(channelId) > 0 &&
1097
1223
  (limit === undefined || reminders.guardSpent(channelId) < limit ||
@@ -1178,6 +1304,8 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
1178
1304
  }, true),
1179
1305
  snapshot: () => run(() => readSnapshot(tables), true),
1180
1306
 
1307
+ // Snapshot rows and file buffers are newly allocated. Avoid a second full
1308
+ // copy here so the bounded encoder stays within its archive memory budget.
1181
1309
  exportArchive: () => run(meta => {
1182
1310
  const snapshot = readSnapshot(tables);
1183
1311
  if (snapshot.modelCalls.some(call => call.outcome === "running" || call.attempts.some(attempt => attempt.outcome === "running")))
@@ -1186,11 +1314,43 @@ export function createEngine(tables: Tables, ownerKey: string, release: () => vo
1186
1314
  && !snapshot.channels.some(channel => channel.lifecycle === "suspending")
1187
1315
  && !snapshot.items.some(item => item.milestone === "received");
1188
1316
  if (meta.lifecycle !== "suspended" && !idle) fail("busy", "Export needs an idle or cleanly suspended session");
1189
- const archive: SessionArchive = { format: "harness-session", archiveVersion: meta.formatVersion >= 8 ? 7 : meta.formatVersion === 7 ? 6 : 5, exportedAt: now(), snapshot,
1190
- ...(meta.formatVersion >= 7 ? { reminderState: reminders.archive() } : {}),
1317
+ const webBase = meta.formatVersion === 10 ? tables.web.baseFormat() : undefined;
1318
+ if (meta.formatVersion === 10 && ![6, 7, 8, 9].includes(webBase ?? 0)) fail("invalid_archive", "Invalid web base format");
1319
+ let archiveFormat = webBase ?? meta.formatVersion;
1320
+ let attachmentState: SessionArchive["attachmentState"];
1321
+ if (archiveFormat === 9) {
1322
+ const attachments = tables.attachments;
1323
+ if (!attachments) throw new Fail("invalid_archive", "Attachment storage is unavailable");
1324
+ const base = attachments.baseFormat();
1325
+ if (base !== 6 && base !== 7 && base !== 8) throw new Fail("invalid_archive", "Invalid attachment base format");
1326
+ archiveFormat = base;
1327
+ const records = attachments.retained();
1328
+ if (records.length) {
1329
+ if (!readFiles) throw new Fail("attachment_unavailable", "Managed attachment files are unavailable");
1330
+ const placeholder = { format: "harness-session", archiveVersion: webBase === undefined ? 8 : 9, exportedAt: now(), snapshot,
1331
+ ...(webBase === undefined ? {} : { webState: { baseFormat: 9 } }),
1332
+ ...(base >= 7 ? { reminderState: reminders.archive() } : {}), allocation: { nextTurnId: meta.nextTurnId, nextSeq: meta.revision + 1, nextItemNumber: meta.nextItemNumber },
1333
+ attachmentState: { baseFormat: base, files: records.map(record => ({ ...record, bytes: new Uint8Array() })) } };
1334
+ const max = 268435456;
1335
+ const header = (size: number) => size < 24 ? 1 : size <= 255 ? 2 : size <= 65535 ? 3 : size <= 0xffffffff ? 5 : 9;
1336
+ let required: number;
1337
+ try { required = encodeSessionFile({ archive: placeholder, config: ownerSnapshot ?? null }, max).length; }
1338
+ catch (error) { if (error instanceof SessionFileError && error.code === "transfer_limit") throw new Fail("transfer_limit", error.message); throw error; }
1339
+ for (const record of records) required += record.metadata.bytes + header(record.metadata.bytes) - 1;
1340
+ if (!Number.isSafeInteger(required) || required > max) throw new Fail("transfer_limit", "Session file exceeds limit");
1341
+ try { attachmentState = { baseFormat: base, files: readFiles(records, max - required + records.reduce((n, record) => n + record.metadata.bytes, 0)) }; }
1342
+ catch (error) { const code = (error as { code?: string }).code; throw new Fail(code === "transfer_limit" ? "transfer_limit" : "attachment_unavailable", String(error)); }
1343
+ } else if (webBase === undefined) snapshot.session.formatVersion = base;
1344
+ }
1345
+ const priorFormat = attachmentState ? 9 : archiveFormat;
1346
+ const webState: SessionArchive["webState"] = webBase === undefined ? undefined : { baseFormat: priorFormat as 6 | 7 | 8 | 9 };
1347
+ const archive: SessionArchive = { format: "harness-session", archiveVersion: webState ? 9 : attachmentState ? 8 : archiveFormat >= 8 ? 7 : archiveFormat === 7 ? 6 : 5, exportedAt: now(), snapshot,
1348
+ ...(webState ? { webState } : {}),
1349
+ ...(attachmentState ? { attachmentState } : {}),
1350
+ ...(archiveFormat >= 7 ? { reminderState: reminders.archive() } : {}),
1191
1351
  allocation: { nextTurnId: meta.nextTurnId, nextSeq: meta.revision + 1, nextItemNumber: meta.nextItemNumber } };
1192
1352
  return archive;
1193
- }),
1353
+ }, false, true),
1194
1354
 
1195
1355
  close() {
1196
1356
  if (closed) return { ok: true, value: undefined, revision: 0 };