maka-agent 0.2.0-dev.23.20260906 → 0.2.0-dev.24.20260907

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 (148) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  28. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  29. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  30. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  31. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  32. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  33. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  34. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  35. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  36. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  37. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  38. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  39. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  40. package/node_modules/@maka/core/dist/session.js +54 -52
  41. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  42. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  43. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  44. package/node_modules/@maka/core/package.json +4 -0
  45. package/node_modules/@maka/mcp/dist/index.js +131 -1
  46. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  49. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +127 -133
  50. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  51. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  52. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  53. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  54. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  55. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  56. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  57. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  58. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  59. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  60. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  61. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  62. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  63. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  64. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  65. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  66. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  67. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  68. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  69. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  70. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  71. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  72. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  73. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  74. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  75. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  76. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  77. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  78. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  79. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  80. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  81. package/node_modules/@maka/runtime/package.json +1 -0
  82. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  83. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  84. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  85. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  86. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  87. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  88. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  89. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  90. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  91. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  92. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  93. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  94. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  95. package/node_modules/@maka/runtime-host/dist/protocol/index.js +25 -1
  96. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  97. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  98. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  99. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  100. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  101. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  102. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  103. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  104. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +100 -24
  105. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  106. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  107. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  108. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  109. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  110. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  111. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  112. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  113. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  114. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  115. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  116. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  117. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  118. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  119. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  120. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  121. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  122. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  123. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  124. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +0 -1
  125. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  126. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  127. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  128. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  129. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  130. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  131. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  132. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  133. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  134. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  135. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  136. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  137. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  138. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  139. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  140. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  141. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  142. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  143. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  144. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  145. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  146. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  147. package/node_modules/@maka/storage/package.json +2 -0
  148. package/package.json +1 -1
@@ -0,0 +1,109 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ const ACTIVE_DELAY_MS = 100;
20
+ const IDLE_DELAY_MS = 60_000;
21
+ const MAX_BATCH_ITEMS = 64;
22
+ const MAX_BATCH_BYTES = 16 * 1024 * 1024;
23
+ /** Physical cleanup is optional work, admitted only after the Host publishes Ready. */
24
+ export class HostStorageMaintenance {
25
+ #lanes;
26
+ #onError;
27
+ #started = false;
28
+ #draining = false;
29
+ constructor(input) {
30
+ this.#onError = input.onError;
31
+ let after;
32
+ this.#lanes = [
33
+ {
34
+ name: 'artifact upgrade cleanup',
35
+ failures: 0,
36
+ run: async () => {
37
+ const result = await input.artifacts.reclaimUpgradeResidue({
38
+ after,
39
+ maxPaths: MAX_BATCH_ITEMS,
40
+ });
41
+ after = result.nextAfter ?? undefined;
42
+ if (result.failedPaths > 0) {
43
+ this.#report('artifact upgrade cleanup', new Error(`${result.failedPaths} paths remain pending`));
44
+ }
45
+ return result.nextAfter !== null;
46
+ },
47
+ },
48
+ ];
49
+ const context = input.contextOffload;
50
+ if (context)
51
+ this.#lanes.push({
52
+ name: 'context garbage collection',
53
+ failures: 0,
54
+ run: async () => (await context.collectGarbage({
55
+ olderThan: Date.now(),
56
+ maxBlobs: MAX_BATCH_ITEMS,
57
+ maxBytes: MAX_BATCH_BYTES,
58
+ })).hasMore,
59
+ });
60
+ }
61
+ start() {
62
+ if (this.#started || this.#draining)
63
+ return;
64
+ this.#started = true;
65
+ for (const lane of this.#lanes)
66
+ this.#schedule(lane, ACTIVE_DELAY_MS);
67
+ }
68
+ beginDrain() {
69
+ this.#draining = true;
70
+ for (const lane of this.#lanes)
71
+ clearTimeout(lane.timer);
72
+ }
73
+ async close() {
74
+ this.beginDrain();
75
+ await Promise.all(this.#lanes.map((lane) => lane.pending));
76
+ }
77
+ #schedule(lane, delay) {
78
+ if (this.#draining)
79
+ return;
80
+ lane.timer = setTimeout(() => {
81
+ lane.pending = this.#run(lane);
82
+ }, delay);
83
+ lane.timer.unref();
84
+ }
85
+ async #run(lane) {
86
+ if (this.#draining)
87
+ return;
88
+ let delay;
89
+ try {
90
+ const more = await lane.run();
91
+ lane.failures = 0;
92
+ delay = more ? ACTIVE_DELAY_MS : IDLE_DELAY_MS;
93
+ }
94
+ catch (error) {
95
+ lane.failures = Math.min(lane.failures + 1, 7);
96
+ delay = Math.min(IDLE_DELAY_MS, 1000 * 2 ** (lane.failures - 1));
97
+ this.#report(lane.name, error);
98
+ }
99
+ this.#schedule(lane, delay);
100
+ }
101
+ #report(name, error) {
102
+ try {
103
+ this.#onError(name, error);
104
+ }
105
+ catch {
106
+ // Diagnostics must not terminate a maintenance lane or poison Host readiness.
107
+ }
108
+ }
109
+ }
@@ -619,7 +619,6 @@ function coordinationSummaryMessages(input) {
619
619
  turnId: input.turnId,
620
620
  ts: ts + 2,
621
621
  status: 'completed',
622
- partialOutputRetained: false,
623
622
  },
624
623
  ];
625
624
  }
@@ -240,18 +240,22 @@ class SqliteArtifactStore {
240
240
  * once its file is gone, and a file that will not go keeps only its own note
241
241
  * rather than holding up the ones behind it.
242
242
  */
243
- async reclaimUpgradeResidue() {
244
- await this.enqueueMutation(async () => {
245
- await this.prepareMutationUnlocked();
246
- const recorded = this.metadataRepository.readUpgradeOrphanPaths();
247
- if (recorded.length === 0)
248
- return;
249
- const claimed = new Set(this.records.map((record) => record.relativePath));
243
+ async reclaimUpgradeResidue(input) {
244
+ if (!Number.isSafeInteger(input.maxPaths) || input.maxPaths < 1 || input.maxPaths > 1024) {
245
+ throw new TypeError('Artifact cleanup path limit must be between 1 and 1024');
246
+ }
247
+ const after = input.after ?? '';
248
+ const maxPaths = input.maxPaths;
249
+ return this.enqueueMutation(async () => {
250
+ const recorded = this.metadataRepository.readUpgradeOrphanPaths(after, maxPaths + 1);
251
+ const selected = recorded.slice(0, maxPaths);
250
252
  const directories = new Set();
251
253
  const discharged = [];
254
+ let failedPaths = 0;
252
255
  try {
253
- for (const relativePath of recorded) {
254
- if (claimed.has(relativePath) || !isSafeRelativeArtifactPath(relativePath)) {
256
+ for (const relativePath of selected) {
257
+ if (this.metadataRepository.hasRelativePath(relativePath) ||
258
+ !isSafeRelativeArtifactPath(relativePath)) {
255
259
  discharged.push(relativePath);
256
260
  continue;
257
261
  }
@@ -261,8 +265,10 @@ class SqliteArtifactStore {
261
265
  directories.add(dirname(target));
262
266
  }
263
267
  catch (error) {
264
- if (!isNotFound(error))
268
+ if (!isNotFound(error)) {
269
+ failedPaths += 1;
265
270
  continue;
271
+ }
266
272
  }
267
273
  discharged.push(relativePath);
268
274
  }
@@ -273,6 +279,11 @@ class SqliteArtifactStore {
273
279
  }
274
280
  if (discharged.length > 0)
275
281
  this.metadataRepository.forgetUpgradeOrphanPaths(discharged);
282
+ return {
283
+ nextAfter: recorded.length > selected.length ? selected.at(-1) : null,
284
+ processedPaths: selected.length,
285
+ failedPaths,
286
+ };
276
287
  });
277
288
  }
278
289
  async replayExistingArtifactUnlocked(existing, input, canonical) {
@@ -103,7 +103,7 @@ function createWriterFacade(lease, authority) {
103
103
  return run(() => store.copyConversationArtifacts(acceptedInput));
104
104
  },
105
105
  purgeSessionArtifacts: (sessionId) => run(() => store.purgeSessionArtifacts(sessionId)),
106
- reclaimUpgradeResidue: () => run(() => store.reclaimUpgradeResidue()),
106
+ reclaimUpgradeResidue: (input) => run(() => store.reclaimUpgradeResidue(input)),
107
107
  deleteUserArtifactInSession: (sessionId, artifactId) => run(() => store.deleteUserArtifactInSession(sessionId, artifactId)),
108
108
  close: () => {
109
109
  if (writerByLease.get(lease) === facade)
@@ -393,7 +393,6 @@ export function convertTranscript(sessionId, rawRecords) {
393
393
  status: 'aborted',
394
394
  abortedAt: turn.lastTs,
395
395
  abortSource: 'claude-code.interrupt',
396
- partialOutputRetained: true,
397
396
  });
398
397
  }
399
398
  else if (turn.failed) {
@@ -404,7 +403,6 @@ export function convertTranscript(sessionId, rawRecords) {
404
403
  ts: turn.lastTs,
405
404
  status: 'failed',
406
405
  errorClass: 'claude_code_api_error',
407
- partialOutputRetained: true,
408
406
  });
409
407
  }
410
408
  else if (turn.terminalStop) {
@@ -414,7 +412,6 @@ export function convertTranscript(sessionId, rawRecords) {
414
412
  turnId: turn.turnId,
415
413
  ts: turn.lastTs,
416
414
  status: 'completed',
417
- partialOutputRetained: true,
418
415
  });
419
416
  }
420
417
  else {
@@ -426,7 +423,6 @@ export function convertTranscript(sessionId, rawRecords) {
426
423
  status: 'aborted',
427
424
  abortedAt: turn.lastTs,
428
425
  abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
429
- partialOutputRetained: true,
430
426
  });
431
427
  }
432
428
  turn = undefined;
@@ -378,7 +378,6 @@ function convertCodexRollout(text, expectedSessionId, fallbackName, fallbackCwd)
378
378
  ts: timestampFor(record),
379
379
  status: failed ? 'failed' : 'completed',
380
380
  ...(failed ? { errorClass: 'codex_error' } : {}),
381
- partialOutputRetained: true,
382
381
  });
383
382
  failedTurnIds.delete(turnId);
384
383
  if (activeTurnId === turnId) {
@@ -398,7 +397,6 @@ function convertCodexRollout(text, expectedSessionId, fallbackName, fallbackCwd)
398
397
  status: 'aborted',
399
398
  abortedAt: normalizeEpochMs(payload.completed_at) ?? ts,
400
399
  abortSource: stringField(payload, 'reason') ?? 'codex',
401
- partialOutputRetained: true,
402
400
  });
403
401
  if (activeTurnId === turnId) {
404
402
  activeTurnId = undefined;
@@ -0,0 +1,325 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { createHash } from 'node:crypto';
20
+ import { createReadStream } from 'node:fs';
21
+ import { chmod, copyFile, lstat, mkdir, realpath } from 'node:fs/promises';
22
+ import { dirname, join, resolve } from 'node:path';
23
+ import { backup, DatabaseSync } from 'node:sqlite';
24
+ import { isCanonicalStorageRef } from '@maka/core/events';
25
+ import { discoverMarkedStorageRoot, runWithStorageRootLease, tryAcquireInteractiveRootOwner, } from './root-authority.js';
26
+ import { migrateSqliteContextOffloadDatabase, SQLITE_CONTEXT_OFFLOAD_SCHEMA_VERSION, } from './sqlite-context-offload-schema.js';
27
+ import { CONTEXT_OFFLOAD_DATABASE_NAME, CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME, } from './sqlite-context-offload-store.js';
28
+ import { syncDirectoryChain, syncFile } from './stable-storage.js';
29
+ import { SQLITE_SESSION_MESSAGE_CHUNK_MARKER } from './sqlite-session-metadata-schema.js';
30
+ /**
31
+ * Existing artifact-only snapshots keep their old admission contract. Context
32
+ * snapshots require the root owner: a Session gate does not fence global GC.
33
+ * The callback must recheck absence before publishing an artifact-only snapshot.
34
+ */
35
+ export async function withOfflineContextSnapshot(root, operation) {
36
+ if (!(await exists(join(root, CONTEXT_OFFLOAD_DATABASE_NAME))))
37
+ return operation(false);
38
+ const capability = await discoverMarkedStorageRoot({ path: root });
39
+ const owner = await tryAcquireInteractiveRootOwner(capability);
40
+ if (!owner)
41
+ throw new Error('Context snapshot requires an offline Storage Root; stop the Runtime Host first');
42
+ try {
43
+ return await runWithStorageRootLease(owner.lease, 'interactive', 'write', () => operation(true));
44
+ }
45
+ finally {
46
+ await owner.close();
47
+ }
48
+ }
49
+ /** Copies under the offline owner and the caller's Artifact lock; never mutates the source DB. */
50
+ export async function copyContextSnapshot(sourceRoot, targetRoot, contextLocked, sessionId) {
51
+ const sourcePath = join(sourceRoot, CONTEXT_OFFLOAD_DATABASE_NAME);
52
+ if (!(await exists(sourcePath)))
53
+ return false;
54
+ if (!contextLocked)
55
+ throw new Error('Context storage appeared during snapshot; retry with the Runtime Host stopped');
56
+ await assertRegularPath(sourceRoot, CONTEXT_OFFLOAD_DATABASE_NAME);
57
+ const targetPath = join(targetRoot, CONTEXT_OFFLOAD_DATABASE_NAME);
58
+ const source = new DatabaseSync(sourcePath, { readOnly: true });
59
+ try {
60
+ await backup(source, targetPath);
61
+ }
62
+ finally {
63
+ source.close();
64
+ }
65
+ await chmod(targetPath, 0o600);
66
+ const target = new DatabaseSync(targetPath);
67
+ try {
68
+ target.exec('PRAGMA foreign_keys = ON');
69
+ migrateSqliteContextOffloadDatabase(target);
70
+ target.exec('BEGIN IMMEDIATE');
71
+ if (sessionId !== undefined)
72
+ target.prepare('DELETE FROM context_refs WHERE session_id <> ?').run(sessionId);
73
+ target.exec(`
74
+ DELETE FROM context_gc_candidates;
75
+ DELETE FROM context_file_deletions;
76
+ DELETE FROM context_blobs WHERE NOT EXISTS (
77
+ SELECT 1 FROM context_refs WHERE context_refs.blob_id = context_blobs.blob_id
78
+ );
79
+ DELETE FROM context_session_usage;
80
+ INSERT INTO context_session_usage
81
+ SELECT r.session_id, count(*), sum(b.size_bytes)
82
+ FROM context_refs r JOIN context_blobs b USING(blob_id) GROUP BY r.session_id;
83
+ UPDATE context_store_usage SET
84
+ blob_count = (SELECT count(*) FROM context_blobs),
85
+ physical_bytes = (SELECT coalesce(sum(size_bytes), 0) FROM context_blobs)
86
+ WHERE singleton = 1;
87
+ COMMIT;
88
+ PRAGMA journal_mode = DELETE;
89
+ VACUUM;
90
+ `);
91
+ // VACUUM on the private destination removes other Sessions' deleted bytes,
92
+ // including SQLite free pages. It is never run on the live source.
93
+ for (const row of target
94
+ .prepare("SELECT blob_id, payload, size_bytes FROM context_blobs WHERE storage_kind = 'managed_file'")
95
+ .iterate()) {
96
+ const path = managedPath(row.blob_id, row.payload);
97
+ await assertRegularPath(sourceRoot, path);
98
+ const destination = join(targetRoot, path);
99
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
100
+ await copyFile(join(sourceRoot, path), destination);
101
+ await chmod(destination, 0o600);
102
+ await syncFile(destination);
103
+ await syncDirectoryChain(dirname(destination), targetRoot);
104
+ }
105
+ }
106
+ finally {
107
+ target.close();
108
+ }
109
+ await syncFile(targetPath);
110
+ await syncDirectoryChain(targetRoot, targetRoot);
111
+ return true;
112
+ }
113
+ export async function planContextSnapshotFiles(root, sessionId) {
114
+ const path = join(root, CONTEXT_OFFLOAD_DATABASE_NAME);
115
+ if (!(await exists(path)))
116
+ return [];
117
+ await assertRegularPath(root, CONTEXT_OFFLOAD_DATABASE_NAME);
118
+ const database = new DatabaseSync(path, { readOnly: true });
119
+ try {
120
+ const version = Number(database.prepare('PRAGMA user_version').get()?.user_version);
121
+ if (![1, 2, SQLITE_CONTEXT_OFFLOAD_SCHEMA_VERSION].includes(version))
122
+ throw new Error('Unsupported context snapshot schema');
123
+ const files = [CONTEXT_OFFLOAD_DATABASE_NAME];
124
+ if (version < 3)
125
+ return files;
126
+ for (const row of database
127
+ .prepare(`SELECT DISTINCT b.blob_id, b.payload FROM context_refs r
128
+ JOIN context_blobs b ON b.blob_id = r.blob_id
129
+ WHERE r.session_id = ? AND b.storage_kind = 'managed_file' ORDER BY b.blob_id`)
130
+ .iterate(sessionId)) {
131
+ const file = managedPath(row.blob_id, row.payload);
132
+ await assertRegularPath(root, file);
133
+ files.push(file);
134
+ }
135
+ return files;
136
+ }
137
+ finally {
138
+ database.close();
139
+ }
140
+ }
141
+ /** Verifies both payload integrity and typed ledger/message references before publication. */
142
+ export async function validateContextSnapshot(root) {
143
+ let context;
144
+ const contextPath = join(root, CONTEXT_OFFLOAD_DATABASE_NAME);
145
+ try {
146
+ if (await exists(contextPath)) {
147
+ await assertRegularPath(root, CONTEXT_OFFLOAD_DATABASE_NAME);
148
+ context = new DatabaseSync(contextPath, { readOnly: true });
149
+ if (context.prepare('PRAGMA user_version').get()?.user_version !==
150
+ SQLITE_CONTEXT_OFFLOAD_SCHEMA_VERSION)
151
+ throw new Error('Unsupported context snapshot schema');
152
+ if (context.prepare('PRAGMA integrity_check').get()?.integrity_check !== 'ok' ||
153
+ context.prepare('PRAGMA foreign_key_check').get())
154
+ throw new Error('Invalid context snapshot database');
155
+ for (const row of context
156
+ .prepare('SELECT blob_id, storage_kind, payload, size_bytes FROM context_blobs')
157
+ .iterate()) {
158
+ const digest = blobHash(row.blob_id);
159
+ if (!Number.isSafeInteger(row.size_bytes) || Number(row.size_bytes) < 0)
160
+ throw new Error('Invalid context snapshot size');
161
+ if (row.storage_kind === 'managed_file') {
162
+ const path = managedPath(row.blob_id, row.payload);
163
+ await assertRegularPath(root, path);
164
+ const info = await lstat(join(root, path));
165
+ if (info.size !== row.size_bytes || (await hashFile(join(root, path))) !== digest) {
166
+ throw new Error('Context snapshot payload size/hash mismatch');
167
+ }
168
+ }
169
+ else if (row.storage_kind !== 'inline' ||
170
+ !(row.payload instanceof Uint8Array) ||
171
+ row.payload.byteLength !== row.size_bytes ||
172
+ createHash('sha256').update(row.payload).digest('hex') !== digest) {
173
+ throw new Error('Context snapshot inline payload size/hash mismatch');
174
+ }
175
+ }
176
+ const actual = context
177
+ .prepare('SELECT count(*) AS n, coalesce(sum(size_bytes), 0) AS bytes FROM context_blobs')
178
+ .get();
179
+ const usage = context
180
+ .prepare('SELECT blob_count, physical_bytes FROM context_store_usage WHERE singleton = 1')
181
+ .get();
182
+ if (usage?.blob_count !== actual.n || usage.physical_bytes !== actual.bytes)
183
+ throw new Error('Context snapshot usage mismatch');
184
+ if (context
185
+ .prepare(`SELECT 1 FROM (
186
+ SELECT r.session_id, count(*) AS reference_count, sum(b.size_bytes) AS logical_bytes
187
+ FROM context_refs r JOIN context_blobs b USING(blob_id) GROUP BY r.session_id
188
+ EXCEPT SELECT session_id, reference_count, logical_bytes FROM context_session_usage
189
+ ) LIMIT 1`)
190
+ .get())
191
+ throw new Error('Context snapshot Session usage mismatch');
192
+ }
193
+ validateLedgerContextRefs(root, context);
194
+ }
195
+ finally {
196
+ context?.close();
197
+ }
198
+ }
199
+ function validateLedgerContextRefs(root, context) {
200
+ const runtime = new DatabaseSync(join(root, 'runtime.sqlite'), { readOnly: true });
201
+ const find = context?.prepare('SELECT 1 FROM context_refs WHERE session_id = ? AND ref_id = ?');
202
+ const check = (value, sessionId) => {
203
+ const ref = record(value);
204
+ if (ref.kind !== 'session_context')
205
+ return;
206
+ if (!isCanonicalStorageRef(value) ||
207
+ ref.sessionId !== sessionId ||
208
+ !find?.get(sessionId, String(ref.refId)))
209
+ throw new Error('Snapshot has a missing or cross-Session context reference');
210
+ };
211
+ const content = (value, sessionId) => {
212
+ const item = record(value);
213
+ if (item.kind === 'image')
214
+ check(item.ref, sessionId);
215
+ };
216
+ const attachments = (value, sessionId) => {
217
+ const item = record(value);
218
+ if (Array.isArray(item.attachments)) {
219
+ for (const attachment of item.attachments)
220
+ check(record(attachment).ref, sessionId);
221
+ }
222
+ };
223
+ const projection = (value, sessionId) => {
224
+ const item = record(value);
225
+ if (item.kind === 'content' && Array.isArray(item.parts)) {
226
+ for (const part of item.parts) {
227
+ const entry = record(part);
228
+ if (entry.kind === 'artifact')
229
+ check(entry.ref, sessionId);
230
+ }
231
+ }
232
+ };
233
+ try {
234
+ for (const row of runtime
235
+ .prepare('SELECT session_id, payload_json FROM runtime_events')
236
+ .iterate()) {
237
+ const event = record(JSON.parse(String(row.payload_json)));
238
+ const item = record(event.content);
239
+ const sessionId = String(row.session_id);
240
+ if (item.kind === 'text')
241
+ attachments(item, sessionId);
242
+ if (item.kind === 'function_response') {
243
+ content(item.result, sessionId);
244
+ projection(item.modelProjection, sessionId);
245
+ }
246
+ }
247
+ for (const row of runtime
248
+ .prepare("SELECT session_id, record_json FROM core_agent_run_events WHERE event_type = 'model_projection_transition_recorded'")
249
+ .iterate()) {
250
+ const event = record(JSON.parse(String(row.record_json)));
251
+ projection(record(record(event.data).transition).replacement, String(row.session_id));
252
+ }
253
+ const chunks = runtime.prepare('SELECT data FROM session_message_chunks WHERE session_id = ? AND sequence = ? ORDER BY chunk_index');
254
+ for (const row of runtime
255
+ .prepare('SELECT session_id, sequence, record_json FROM session_messages')
256
+ .iterate()) {
257
+ const encoded = row.record_json === SQLITE_SESSION_MESSAGE_CHUNK_MARKER
258
+ ? Buffer.concat(chunks.all(row.session_id, row.sequence).map((chunk) => {
259
+ if (!(chunk.data instanceof Uint8Array))
260
+ throw new Error('Invalid snapshot message chunk');
261
+ return Buffer.from(chunk.data);
262
+ })).toString('utf8')
263
+ : String(row.record_json);
264
+ const message = record(JSON.parse(encoded));
265
+ const sessionId = String(row.session_id);
266
+ if (message.type === 'user')
267
+ attachments(message, sessionId);
268
+ if (message.type === 'tool_result')
269
+ content(message.content, sessionId);
270
+ }
271
+ }
272
+ finally {
273
+ runtime.close();
274
+ }
275
+ }
276
+ function record(value) {
277
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
278
+ ? value
279
+ : {};
280
+ }
281
+ function blobHash(value) {
282
+ if (!(value instanceof Uint8Array) || value.byteLength !== 32)
283
+ throw new Error('Invalid context snapshot blob identity');
284
+ return Buffer.from(value).toString('hex');
285
+ }
286
+ function managedPath(blobId, payload) {
287
+ const digest = blobHash(blobId);
288
+ const expected = `sha256/${digest.slice(0, 2)}/${digest}`;
289
+ if (!(payload instanceof Uint8Array) || !Buffer.from(payload).equals(Buffer.from(expected))) {
290
+ throw new Error('Invalid context snapshot managed locator');
291
+ }
292
+ return `${CONTEXT_OFFLOAD_VALUES_DIRECTORY_NAME}/${expected}`;
293
+ }
294
+ async function assertRegularPath(root, relativePath) {
295
+ const canonical = await realpath(root);
296
+ const parts = relativePath.split('/');
297
+ let path = canonical;
298
+ for (const [index, part] of parts.entries()) {
299
+ path = join(path, part);
300
+ const info = await lstat(path);
301
+ if (info.isSymbolicLink() ||
302
+ (index === parts.length - 1 ? !info.isFile() : !info.isDirectory())) {
303
+ throw new Error('Context snapshot path must not contain symlinks or special files');
304
+ }
305
+ }
306
+ if ((await realpath(path)) !== resolve(canonical, relativePath))
307
+ throw new Error('Context snapshot path escaped its root');
308
+ }
309
+ async function hashFile(path) {
310
+ const hash = createHash('sha256');
311
+ for await (const chunk of createReadStream(path))
312
+ hash.update(chunk);
313
+ return hash.digest('hex');
314
+ }
315
+ async function exists(path) {
316
+ try {
317
+ await lstat(path);
318
+ return true;
319
+ }
320
+ catch (error) {
321
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
322
+ return false;
323
+ throw error;
324
+ }
325
+ }
@@ -29,7 +29,7 @@ const executionStoresReaderKinds = new WeakMap();
29
29
  const executionStoresWritersByLease = new WeakMap();
30
30
  const executionStoresWritersOpeningByLease = new WeakMap();
31
31
  export { normalizeRootTurnAdmissionPayload, rootTurnAdmissionRecordFits, } from './agent-run-store.js';
32
- export { isSessionNotFoundError, SessionReadMarkerMessageNotFoundError, } from './session-store.js';
32
+ export { isSessionNotFoundError } from './session-store.js';
33
33
  export { SessionMetadataConflictError, SessionMetadataVersionConflictError, } from './sqlite-session-metadata-store.js';
34
34
  export { submittedTurnIntentsEqual } from './submitted-turn-intent.js';
35
35
  export function authenticateExecutionStoresWriter(stores, expectedKind) {
@@ -140,6 +140,7 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
140
140
  readSandboxBoundaryRequest: (sessionId, requestId) => run(() => sessionStore.readSandboxBoundaryRequest(sessionId, requestId)),
141
141
  listPendingSandboxBoundaryRequests: (sessionId) => run(() => sessionStore.listPendingSandboxBoundaryRequests(sessionId)),
142
142
  listSandboxBoundaryRestartClosures: (sessionId) => run(() => sessionStore.listSandboxBoundaryRestartClosures(sessionId)),
143
+ hasExplicitSandboxBoundaryDenial: (identities) => run(() => sessionStore.hasExplicitSandboxBoundaryDenial(identities)),
143
144
  settleSandboxBoundaryRequest: (input) => run(() => sessionStore.settleSandboxBoundaryRequest(input)),
144
145
  setExecutionBoundaryKind: (sessionId, boundaryKind, projection) => run(() => sessionStore.setExecutionBoundaryKind(sessionId, boundaryKind, projection)),
145
146
  list: (filter) => run(() => sessionStore.list(filter)),
@@ -151,19 +152,16 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
151
152
  readCatalogRecord: (sessionId) => run(() => sessionStore.readCatalogRecord(sessionId)),
152
153
  probeSessionRemoval: (sessionId) => run(() => sessionStore.probeSessionRemoval(sessionId)),
153
154
  readMessagesSnapshot: (sessionId) => run(() => sessionStore.readMessagesSnapshot(sessionId)),
154
- readTranscriptPageSnapshot: (sessionId, request) => run(() => sessionStore.readTranscriptPageSnapshot(sessionId, request)),
155
- readTranscriptRecordsSnapshot: (sessionId, request) => run(() => sessionStore.readTranscriptRecordsSnapshot(sessionId, request)),
156
155
  readTranscriptMessagesSnapshot: (sessionId, request) => run(() => sessionStore.readTranscriptMessagesSnapshot(sessionId, request)),
157
156
  readTranscriptHighWaterSnapshot: (sessionId) => run(() => sessionStore.readTranscriptHighWaterSnapshot(sessionId)),
158
- readTurnContributionsSnapshot: (sessionId, throughSequence, position, maxContributions) => run(() => sessionStore.readTurnContributionsSnapshot(sessionId, throughSequence, position, maxContributions)),
159
- readTurnLandmarksSnapshot: (sessionId, maxLandmarks) => run(() => sessionStore.readTurnLandmarksSnapshot(sessionId, maxLandmarks)),
160
- readMessagesForRecovery: (sessionId) => run(() => sessionStore.readMessagesForRecovery(sessionId)),
161
157
  listTurnsSnapshot: (sessionId) => run(() => sessionStore.listTurnsSnapshot(sessionId)),
162
158
  readHeader: (sessionId) => run(() => sessionStore.readHeader(sessionId)),
163
159
  readMessages: (sessionId) => run(() => sessionStore.readMessages(sessionId)),
160
+ readMessagesAfter: (sessionId, request) => run(() => sessionStore.readMessagesAfter(sessionId, request)),
164
161
  listTurns: (sessionId) => run(() => sessionStore.listTurns(sessionId)),
165
162
  appendMessage: (sessionId, message) => run(() => sessionStore.appendMessage(sessionId, message)),
166
163
  appendMessages: (sessionId, messages) => run(() => sessionStore.appendMessages(sessionId, messages)),
164
+ commitMessageCatalogProjection: (sessionId, message) => run(() => sessionStore.commitMessageCatalogProjection(sessionId, message)),
167
165
  commitMessageAdmission: (admission) => run(() => sessionStore.commitMessageAdmission(admission)),
168
166
  readMessageAdmission: (sessionId, messageId) => run(() => sessionStore.readMessageAdmission(sessionId, messageId)),
169
167
  hasCancelledMessageAdmission: (sessionId, messageId) => run(() => sessionStore.hasCancelledMessageAdmission(sessionId, messageId)),
@@ -177,7 +175,6 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
177
175
  updateHeader: (sessionId, patch) => run(() => sessionStore.updateHeader(sessionId, patch)),
178
176
  updateHeaderVersioned: (sessionId, patch, expectedRevision) => run(() => sessionStore.updateHeaderVersioned(sessionId, patch, expectedRevision)),
179
177
  updateSessionConfiguration: (sessionId, input) => run(() => sessionStore.updateSessionConfiguration(sessionId, input)),
180
- markSessionReadThroughMessage: (sessionId, messageId) => run(() => sessionStore.markSessionReadThroughMessage(sessionId, messageId)),
181
178
  setFlagged: (sessionId, isFlagged) => run(() => sessionStore.setFlagged(sessionId, isFlagged)),
182
179
  rename: (sessionId, name) => run(() => sessionStore.rename(sessionId, name)),
183
180
  setGeneratedTitleIfAbsent: (sessionId, title) => run(() => sessionStore.setGeneratedTitleIfAbsent(sessionId, title)),
@@ -236,6 +233,10 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
236
233
  readInvocation: (sessionId, invocationId) => run(() => runtimeEventStore.readInvocation(sessionId, invocationId)),
237
234
  readSessionRuntimeEvents: (sessionId) => run(() => runtimeEventStore.readSessionRuntimeEvents(sessionId)),
238
235
  readSessionRuntimeEventEntries: (sessionId) => run(() => runtimeEventStore.readSessionRuntimeEventEntries(sessionId)),
236
+ resequenceSessionEventOrdinals: (sessionId) => run(() => runtimeEventStore.resequenceSessionEventOrdinals(sessionId)),
237
+ readTranscriptHighWater: (sessionId) => run(() => runtimeEventStore.readTranscriptHighWater(sessionId)),
238
+ readTranscriptInvocations: (sessionId, request) => run(() => runtimeEventStore.readTranscriptInvocations(sessionId, request)),
239
+ readTranscriptLandmarks: (sessionId, throughOrdinal, limit) => run(() => runtimeEventStore.readTranscriptLandmarks(sessionId, throughOrdinal, limit)),
239
240
  claimContinuation: (input) => run(() => runtimeEventStore.claimContinuation(input)),
240
241
  readContinuationClaimByBoundary: (boundaryDigest) => run(() => runtimeEventStore.readContinuationClaimByBoundary(boundaryDigest)),
241
242
  readContinuationClaimStateByBoundary: (boundaryDigest) => run(() => runtimeEventStore.readContinuationClaimStateByBoundary(boundaryDigest)),
@@ -316,6 +317,7 @@ async function openExecutionStoresForRead(lease, kind, extension) {
316
317
  listSessionInvocationsPage: (sessionId, input) => run(() => runtimeEventStore.listSessionInvocationsPage(sessionId, input)),
317
318
  readInvocation: (sessionId, invocationId) => run(() => runtimeEventStore.readInvocation(sessionId, invocationId)),
318
319
  readSessionRuntimeEvents: (sessionId) => run(() => runtimeEventStore.readSessionRuntimeEvents(sessionId)),
320
+ readSessionRuntimeEventEntries: (sessionId) => run(() => runtimeEventStore.readSessionRuntimeEventEntries(sessionId)),
319
321
  },
320
322
  };
321
323
  freezeExecutionStoresFacade(stores);