maka-agent 0.2.0-dev.47.20260922 → 0.2.0-dev.49.20260924
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/session-event-mapper.js +1 -4
- package/dist/onboarding-catalog.js +20 -4
- package/dist/pi-transcript.js +0 -8
- package/dist/pi-tui-pickers.js +1 -1
- package/dist/pi-tui-runner.js +6 -4
- package/dist/runtime-host-capability-provider-command.js +25 -6
- package/dist/runtime-host-onboarding.js +5 -3
- package/dist/runtime-host-session-channel.js +9 -3
- package/dist/tui-mcp-control.js +37 -24
- package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
- package/node_modules/@maka/acp-executor-plugin/dist/acp-errors.js +26 -0
- package/node_modules/@maka/acp-executor-plugin/dist/acp-filesystem.js +103 -0
- package/node_modules/@maka/acp-executor-plugin/dist/acp-process.js +119 -0
- package/node_modules/@maka/acp-executor-plugin/dist/acp-projection.js +146 -0
- package/node_modules/@maka/acp-executor-plugin/dist/index.js +653 -0
- package/node_modules/@maka/acp-executor-plugin/dist/plugin.mjs +24446 -0
- package/node_modules/@maka/acp-executor-plugin/package.json +15 -0
- package/node_modules/@maka/antigravity-acp-plugin/dist/index.js +88 -0
- package/node_modules/@maka/antigravity-acp-plugin/dist/model-presentation.js +53 -0
- package/node_modules/@maka/antigravity-acp-plugin/dist/plugin.mjs +115 -0
- package/node_modules/@maka/antigravity-acp-plugin/package.json +15 -0
- package/node_modules/@maka/core/dist/events.js +13 -0
- package/node_modules/@maka/core/dist/executor-catalog.js +106 -0
- package/node_modules/@maka/core/dist/llm-connections.js +2 -5
- package/node_modules/@maka/core/dist/mcp.js +4 -1
- package/node_modules/@maka/core/dist/model-facts.js +2 -4
- package/node_modules/@maka/core/dist/model-metadata.generated.js +345 -248
- package/node_modules/@maka/core/dist/model-metadata.js +28 -1
- package/node_modules/@maka/core/dist/model-thinking.js +17 -17
- package/node_modules/@maka/core/dist/model-web-search.js +7 -9
- package/node_modules/@maka/core/dist/models-dev-projection.js +1 -1
- package/node_modules/@maka/core/dist/onboarding.js +1 -4
- package/node_modules/@maka/core/dist/provider-registry.js +60 -86
- package/node_modules/@maka/core/dist/runtime-event-store.js +25 -0
- package/node_modules/@maka/core/dist/runtime-event.js +2 -2
- package/node_modules/@maka/core/dist/runtime-invocation.js +5 -0
- package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +28 -16
- package/node_modules/@maka/core/dist/runtime-policy/credential-vault-codec.js +6 -0
- package/node_modules/@maka/core/dist/runtime-policy/policy-codec.js +21 -0
- package/node_modules/@maka/core/dist/runtime-policy.js +1 -1
- package/node_modules/@maka/core/dist/session.js +25 -9
- package/node_modules/@maka/core/dist/settings.js +1 -0
- package/node_modules/@maka/core/dist/tool-ledger-scanner.js +365 -104
- package/node_modules/@maka/core/dist/transcript-search.js +1 -0
- package/node_modules/@maka/core/dist/turn-origin.js +14 -0
- package/node_modules/@maka/core/dist/usage-stats/types.js +1 -0
- package/node_modules/@maka/core/package.json +2 -0
- package/node_modules/@maka/eval/dist/harbor-maka-subject.js +3 -0
- package/node_modules/@maka/eval/dist/maka-subject.js +8 -1
- package/node_modules/@maka/mcp/dist/credential-coordinator.js +6 -1
- package/node_modules/@maka/mcp/dist/index.js +31 -5
- package/node_modules/@maka/mcp/dist/oauth.js +54 -6
- package/node_modules/@maka/runtime/dist/agent-run-inspect.js +1 -1
- package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +1 -11
- package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +2 -12
- package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +3 -71
- package/node_modules/@maka/runtime/dist/conversation-copy.js +58 -3
- package/node_modules/@maka/runtime/dist/local-web-fetch.js +23 -11
- package/node_modules/@maka/runtime/dist/mcp-tools.js +9 -2
- package/node_modules/@maka/runtime/dist/model-adapter.js +10 -5
- package/node_modules/@maka/runtime/dist/model-factory.js +33 -30
- package/node_modules/@maka/runtime/dist/model-fetcher.js +4 -1
- package/node_modules/@maka/runtime/dist/model-runtime.js +3 -9
- package/node_modules/@maka/runtime/dist/plugin-executor-backend.js +116 -3
- package/node_modules/@maka/runtime/dist/plugin-executor-service.js +212 -16
- package/node_modules/@maka/runtime/dist/read-page.js +11 -8
- package/node_modules/@maka/runtime/dist/recovery-resolver.js +47 -20
- package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +1 -0
- package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +2 -2
- package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +39 -8
- package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +3 -0
- package/node_modules/@maka/runtime/dist/session-manager.js +182 -127
- package/node_modules/@maka/runtime/dist/shell-run-manager.js +3 -0
- package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +29 -4
- package/node_modules/@maka/runtime/dist/telemetry/model-pricing.generated.js +141 -134
- package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +3 -3
- package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +7 -6
- package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +28 -62
- package/node_modules/@maka/runtime-host/dist/candidate-entry.js +8 -5
- package/node_modules/@maka/runtime-host/dist/client/hosted-execution-target.js +7 -1
- package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
- package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +8 -1
- package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +6 -1
- package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +3 -0
- package/node_modules/@maka/runtime-host/dist/composition-identity.js +19 -0
- package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +6 -3
- package/node_modules/@maka/runtime-host/dist/protocol/index.js +14 -2
- package/node_modules/@maka/runtime-host/dist/protocol/operations.js +4 -1
- package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +34 -0
- package/node_modules/@maka/runtime-host/dist/protocol/prompt-suggestions.js +61 -0
- package/node_modules/@maka/runtime-host/dist/protocol/runtime-policy.js +4 -1
- package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +40 -2
- package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +2 -1
- package/node_modules/@maka/runtime-host/dist/server/builtin-external-agent-plugins.js +188 -0
- package/node_modules/@maka/runtime-host/dist/server/candidate.js +12 -7
- package/node_modules/@maka/runtime-host/dist/server/client-capability-recovery.js +44 -46
- package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +3 -0
- package/node_modules/@maka/runtime-host/dist/server/context-coordinator.js +2 -0
- package/node_modules/@maka/runtime-host/dist/server/execution-composition-factory.js +1 -1
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +212 -24
- package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +41 -2
- package/node_modules/@maka/runtime-host/dist/server/extension-bundle.js +4 -0
- package/node_modules/@maka/runtime-host/dist/server/generated-text.js +39 -0
- package/node_modules/@maka/runtime-host/dist/server/host-composition-source.js +47 -0
- package/node_modules/@maka/runtime-host/dist/server/host-composition.js +1 -29
- package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +2 -9
- package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +75 -9
- package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +12 -0
- package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +45 -0
- package/node_modules/@maka/runtime-host/dist/server/jev-routing-model.js +157 -0
- package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -2
- package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +4 -0
- package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +11 -1
- package/node_modules/@maka/runtime-host/dist/server/process-lifecycle.js +1 -1
- package/node_modules/@maka/runtime-host/dist/server/process-termination-error.js +27 -0
- package/node_modules/@maka/runtime-host/dist/server/prompt-suggestion.js +179 -0
- package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +93 -14
- package/node_modules/@maka/runtime-host/dist/server/runtime-policy-coordinator.js +2 -0
- package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +99 -12
- package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +48 -16
- package/node_modules/@maka/runtime-host/dist/server/session-effect-coordinator.js +12 -6
- package/node_modules/@maka/runtime-host/dist/server/session-title.js +3 -16
- package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +71 -3
- package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +3 -0
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +6 -13
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +39 -11
- package/node_modules/@maka/runtime-host/dist/server/workhub-result-coordinator.js +173 -0
- package/node_modules/@maka/runtime-host/dist/server/workhub-result-runtime.js +293 -0
- package/node_modules/@maka/runtime-host/package.json +2 -0
- package/node_modules/@maka/storage/dist/agent-run-store-contract.js +8 -0
- package/node_modules/@maka/storage/dist/config-transfer.js +14 -8
- package/node_modules/@maka/storage/dist/execution-stores.js +19 -6
- package/node_modules/@maka/storage/dist/interaction-store.js +13 -0
- package/node_modules/@maka/storage/dist/mcp-config-store.js +91 -2
- package/node_modules/@maka/storage/dist/operational-state-store.js +15 -1
- package/node_modules/@maka/storage/dist/plan-authority.js +2 -0
- package/node_modules/@maka/storage/dist/plan-store.js +30 -0
- package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
- package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +28 -17
- package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +9 -3
- package/node_modules/@maka/storage/dist/runtime-policy/credential-vault-document.js +4 -1
- package/node_modules/@maka/storage/dist/runtime-policy/legacy-custom-connection.js +65 -0
- package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +10 -5
- package/node_modules/@maka/storage/dist/runtime-policy/policy-document.js +2 -0
- package/node_modules/@maka/storage/dist/session-bundle-policy.js +11 -0
- package/node_modules/@maka/storage/dist/session-store-values.js +16 -4
- package/node_modules/@maka/storage/dist/session-store.js +29 -6
- package/node_modules/@maka/storage/dist/shell-run-authority.js +1 -0
- package/node_modules/@maka/storage/dist/shell-run-store.js +15 -0
- package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +3 -0
- package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +74 -1
- package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +849 -91
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +21 -3
- package/node_modules/@maka/storage/dist/usage-screen.js +138 -108
- package/package.json +1 -1
|
@@ -24,11 +24,12 @@ import { assertHandoffClaimSource } from '@maka/core/runtime-handoff';
|
|
|
24
24
|
import { buildWorkspaceBaselineAuthorityEvents, buildWorkspaceSuccessorAuthorityEvent, scanWorkspaceBaselineAuthority, WORKSPACE_AUTHORITY_SESSION_ID, WORKSPACE_VERSION_AUTHORITY_CAPABILITY_V1, } from '@maka/core/workspace-version-authority';
|
|
25
25
|
import { decodeRuntimeEvent, decodeRuntimeInvocationOpened, isPartialRuntimeEvent, isTerminalRuntimeEvent, runtimeEventInvocationOpening, } from '@maka/core/runtime-event';
|
|
26
26
|
import { RunSealedError, RUNTIME_CONTINUATION_AUTHORITY_V1, TOOL_RECOVERY_BUNDLE_CAPABILITY_V1, } from '@maka/core/runtime-event-store';
|
|
27
|
+
import { mayBeTranscriptLedgerInvocationId, } from '@maka/core/runtime-invocation';
|
|
27
28
|
import { stableJsonStringify } from '@maka/core/tool-args-identity';
|
|
28
29
|
import { mergeRuntimePartialSnapshots, groupRuntimePartialSnapshots, compareRuntimePartialSnapshots, partialRuntimeStream, completedPartialRuntimeStreamKey, } from './runtime-partial-values.js';
|
|
29
30
|
import { assertPreparedInput, assertOutcomeInput, assertPreparedIdentity, assertOutcomeIdentity, } from './tool-commit-validation.js';
|
|
30
31
|
import { encodeCanonicalRuntimeEvent } from '@maka/core/canonical-runtime-event';
|
|
31
|
-
import { scanToolLedger, ToolLedgerCorruptionError, ToolLedgerRejectionError, validateGenericToolLedgerAppend,
|
|
32
|
+
import { scanToolLedger, referencedToolOperationIds, ToolLedgerReducer, ToolLedgerCorruptionError, ToolLedgerRejectionError, validateGenericToolLedgerAppend, validateIncrementalToolLedgerTransition, } from '@maka/core/tool-ledger-scanner';
|
|
32
33
|
import { buildImmutableRuntimePrefix, buildImmutableRuntimePrefixProof, continuationStartEventMatchesClaim, decodeContinuationClaim, } from '@maka/core/runtime-boundary';
|
|
33
34
|
import { assertToolRecoveryEventBundle, interpretScannedToolRecovery, } from '@maka/core/tool-recovery-bundle';
|
|
34
35
|
import { configureSqliteRuntimeDatabase, migrateSqliteRuntimeDatabase, readUserVersion, RUNTIME_RECOVERY_AUTHORITY_CAPABILITY, RUNTIME_RECOVERY_AUTHORITY_CAPABILITY_VERSION, RUNTIME_CONTINUATION_AUTHORITY_CAPABILITY, RUNTIME_CONTINUATION_AUTHORITY_CAPABILITY_VERSION, RUNTIME_WORKSPACE_VERSION_AUTHORITY_CAPABILITY, RUNTIME_WORKSPACE_VERSION_AUTHORITY_CAPABILITY_VERSION, runtimeEventKind, SQLITE_RUNTIME_SCHEMA_VERSION, } from './sqlite-runtime-schema.js';
|
|
@@ -41,6 +42,24 @@ import { rebuildTranscriptTurnExtents, recordTranscriptTurnExtent, RuntimeTransc
|
|
|
41
42
|
export { SQLITE_RUNTIME_SCHEMA_VERSION } from './sqlite-runtime-schema.js';
|
|
42
43
|
const RUNTIME_EVENT_SCAN_BATCH_SIZE = 128;
|
|
43
44
|
const RUNTIME_PARTIAL_SEGMENT_TARGET_BYTES = 64 * 1024;
|
|
45
|
+
const RECOVERY_MESSAGE_QUERY_BATCH_SIZE = 400;
|
|
46
|
+
const TOOL_LEDGER_CACHE_EVENT_OVERHEAD_BYTES = 1024;
|
|
47
|
+
const DEFAULT_TOOL_LEDGER_CACHE_BUDGET = {
|
|
48
|
+
maxEntries: 32,
|
|
49
|
+
maxEstimatedBytes: 16 * 1024 * 1024,
|
|
50
|
+
maxSingleEntryEstimatedBytes: 8 * 1024 * 1024,
|
|
51
|
+
};
|
|
52
|
+
const IMMUTABLE_STEERING_SQL_PREDICATE = `
|
|
53
|
+
event_kind = 'text'
|
|
54
|
+
AND CASE
|
|
55
|
+
WHEN json_valid(payload_json)
|
|
56
|
+
THEN json_extract(payload_json, '$.partial')
|
|
57
|
+
END = 0
|
|
58
|
+
AND CASE
|
|
59
|
+
WHEN json_valid(payload_json)
|
|
60
|
+
THEN json_extract(payload_json, '$.content.steering')
|
|
61
|
+
END = 1
|
|
62
|
+
`;
|
|
44
63
|
function assertRuntimeEventScanBudget(budget) {
|
|
45
64
|
for (const [name, value] of Object.entries(budget)) {
|
|
46
65
|
if (!Number.isSafeInteger(value) || value < 1) {
|
|
@@ -61,6 +80,19 @@ function requireRuntimeEventScanCount(value) {
|
|
|
61
80
|
}
|
|
62
81
|
return value;
|
|
63
82
|
}
|
|
83
|
+
function normalizeToolLedgerCacheBudget(override) {
|
|
84
|
+
const budget = { ...DEFAULT_TOOL_LEDGER_CACHE_BUDGET, ...override };
|
|
85
|
+
for (const [name, value] of Object.entries(budget)) {
|
|
86
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
87
|
+
throw new Error(`Invalid tool ledger cache ${name}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return budget;
|
|
91
|
+
}
|
|
92
|
+
function estimateToolLedgerCacheBytes(storedPayloadBytes, eventCount) {
|
|
93
|
+
const estimate = storedPayloadBytes * 2 + eventCount * TOOL_LEDGER_CACHE_EVENT_OVERHEAD_BYTES;
|
|
94
|
+
return Number.isSafeInteger(estimate) ? estimate : Number.MAX_SAFE_INTEGER;
|
|
95
|
+
}
|
|
64
96
|
const require = createRequire(import.meta.url);
|
|
65
97
|
function loadDatabaseSync() {
|
|
66
98
|
return require('node:sqlite').DatabaseSync;
|
|
@@ -82,12 +114,26 @@ export class SqliteRuntimeStore {
|
|
|
82
114
|
workspaceVersionAuthorityCapability = WORKSPACE_VERSION_AUTHORITY_CAPABILITY_V1;
|
|
83
115
|
db;
|
|
84
116
|
databaseLease;
|
|
85
|
-
|
|
117
|
+
toolLedgerCacheBudget;
|
|
118
|
+
toolLedgerCache = new Map();
|
|
119
|
+
toolLedgerCacheEstimatedBytes = 0;
|
|
120
|
+
toolLedgerCacheEventCount = 0;
|
|
121
|
+
toolLedgerCacheMetrics = {
|
|
122
|
+
hits: 0,
|
|
123
|
+
misses: 0,
|
|
124
|
+
budgetEvictions: 0,
|
|
125
|
+
terminalEvictions: 0,
|
|
126
|
+
transientEntries: 0,
|
|
127
|
+
};
|
|
128
|
+
uncommittedToolLedgerStates = new Map();
|
|
129
|
+
toolLedgerCacheVersion;
|
|
130
|
+
localCommittedWriteRevision = 0;
|
|
86
131
|
closed = false;
|
|
87
132
|
uncommittedEventSessions = new Set();
|
|
88
133
|
eventCommitListeners = new Set();
|
|
89
134
|
constructor(path, options = {}) {
|
|
90
135
|
this.options = options;
|
|
136
|
+
this.toolLedgerCacheBudget = normalizeToolLedgerCacheBudget(options.toolLedgerCacheBudget);
|
|
91
137
|
if (options.readOnly && options.databaseLease) {
|
|
92
138
|
throw new Error('Operational state database leases cannot be opened read-only');
|
|
93
139
|
}
|
|
@@ -102,7 +148,6 @@ export class SqliteRuntimeStore {
|
|
|
102
148
|
registerRecallFoldFunction(this.db);
|
|
103
149
|
if (!options.readOnly) {
|
|
104
150
|
this.registerWorkspaceBaselineAuthorityWriter();
|
|
105
|
-
this.refreshToolLedgerHealth();
|
|
106
151
|
}
|
|
107
152
|
return;
|
|
108
153
|
}
|
|
@@ -128,7 +173,6 @@ export class SqliteRuntimeStore {
|
|
|
128
173
|
registerRecallFoldFunction(this.db);
|
|
129
174
|
if (!options.readOnly) {
|
|
130
175
|
this.registerWorkspaceBaselineAuthorityWriter();
|
|
131
|
-
this.refreshToolLedgerHealth();
|
|
132
176
|
}
|
|
133
177
|
}
|
|
134
178
|
catch (error) {
|
|
@@ -152,6 +196,8 @@ export class SqliteRuntimeStore {
|
|
|
152
196
|
if (this.closed)
|
|
153
197
|
return;
|
|
154
198
|
this.closed = true;
|
|
199
|
+
this.clearToolLedgerCache();
|
|
200
|
+
this.uncommittedToolLedgerStates.clear();
|
|
155
201
|
if (this.databaseLease)
|
|
156
202
|
this.databaseLease.close();
|
|
157
203
|
else
|
|
@@ -195,6 +241,7 @@ export class SqliteRuntimeStore {
|
|
|
195
241
|
existing.at(-1)?.id !== canonicalEvent.id) {
|
|
196
242
|
throw new Error('Terminal RuntimeEvent must be the immutable ledger tail');
|
|
197
243
|
}
|
|
244
|
+
this.invalidateToolLedgerCacheForInvocation(canonicalEvent.invocationId);
|
|
198
245
|
return;
|
|
199
246
|
}
|
|
200
247
|
const existingTerminal = existing.find(isTerminalRuntimeEvent);
|
|
@@ -223,7 +270,11 @@ export class SqliteRuntimeStore {
|
|
|
223
270
|
if (events.some(isToolLedgerBearingEvent)) {
|
|
224
271
|
this.assertToolLedgerTransition(events, 'generic_append');
|
|
225
272
|
}
|
|
226
|
-
|
|
273
|
+
// Batch imports preserve already-persisted history, including legacy
|
|
274
|
+
// terminal/tool gaps that recovery will classify when projections are
|
|
275
|
+
// rebuilt. New terminal writes through appendRuntimeEvent must obey the
|
|
276
|
+
// unsettled-operation invariant below.
|
|
277
|
+
const created = events.map((event) => this.importRuntimeEventSync(event, true));
|
|
227
278
|
return { created };
|
|
228
279
|
});
|
|
229
280
|
}
|
|
@@ -334,6 +385,202 @@ export class SqliteRuntimeStore {
|
|
|
334
385
|
assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
|
|
335
386
|
return this.readTransaction(() => this.readInvocationOpeningsSync(sessionId, { direction: 'asc' }).map((row) => this.completeInvocationRecordSync(row)));
|
|
336
387
|
}
|
|
388
|
+
async listInvocationRecoveryInventory(sessionIds) {
|
|
389
|
+
const selectedSessionIds = [...new Set(sessionIds)];
|
|
390
|
+
for (const sessionId of selectedSessionIds) {
|
|
391
|
+
assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
|
|
392
|
+
}
|
|
393
|
+
if (selectedSessionIds.length === 0)
|
|
394
|
+
return [];
|
|
395
|
+
const selectedJson = JSON.stringify(selectedSessionIds);
|
|
396
|
+
return this.readTransaction(() => {
|
|
397
|
+
const eventRows = this.db
|
|
398
|
+
.prepare(`
|
|
399
|
+
WITH selected(session_id) AS (SELECT value FROM json_each(?))
|
|
400
|
+
SELECT
|
|
401
|
+
opening.rowid AS opening_rowid,
|
|
402
|
+
opening.session_id AS session_id,
|
|
403
|
+
opening.invocation_id AS invocation_id,
|
|
404
|
+
1 AS from_events,
|
|
405
|
+
NULL AS run_id,
|
|
406
|
+
NULL AS turn_id,
|
|
407
|
+
NULL AS opened_at,
|
|
408
|
+
(
|
|
409
|
+
SELECT terminal.rowid
|
|
410
|
+
FROM runtime_events AS terminal INDEXED BY runtime_events_terminal
|
|
411
|
+
WHERE terminal.invocation_id = opening.invocation_id
|
|
412
|
+
AND ${TERMINAL_RUNTIME_EVENT_SQL.replaceAll('payload_json', 'terminal.payload_json')}
|
|
413
|
+
ORDER BY terminal.event_seq
|
|
414
|
+
LIMIT 1
|
|
415
|
+
) AS terminal_rowid
|
|
416
|
+
FROM selected
|
|
417
|
+
JOIN runtime_events AS opening INDEXED BY runtime_events_by_session_kind
|
|
418
|
+
ON opening.session_id = selected.session_id
|
|
419
|
+
AND opening.event_kind = 'invocation_opened'
|
|
420
|
+
`)
|
|
421
|
+
.all(selectedJson);
|
|
422
|
+
const legacyRows = this.db
|
|
423
|
+
.prepare(`
|
|
424
|
+
WITH selected(session_id) AS (SELECT value FROM json_each(?))
|
|
425
|
+
SELECT
|
|
426
|
+
NULL AS opening_rowid,
|
|
427
|
+
legacy.session_id AS session_id,
|
|
428
|
+
legacy.invocation_id AS invocation_id,
|
|
429
|
+
legacy.run_id AS run_id,
|
|
430
|
+
legacy.turn_id AS turn_id,
|
|
431
|
+
legacy.opened_at AS opened_at,
|
|
432
|
+
0 AS from_events,
|
|
433
|
+
(
|
|
434
|
+
SELECT terminal.rowid
|
|
435
|
+
FROM runtime_events AS terminal INDEXED BY runtime_events_terminal
|
|
436
|
+
WHERE terminal.invocation_id = legacy.invocation_id
|
|
437
|
+
AND ${TERMINAL_RUNTIME_EVENT_SQL.replaceAll('payload_json', 'terminal.payload_json')}
|
|
438
|
+
ORDER BY terminal.event_seq
|
|
439
|
+
LIMIT 1
|
|
440
|
+
) AS terminal_rowid
|
|
441
|
+
FROM selected
|
|
442
|
+
JOIN runtime_legacy_invocation_openings AS legacy
|
|
443
|
+
ON legacy.session_id = selected.session_id
|
|
444
|
+
WHERE NOT EXISTS (
|
|
445
|
+
SELECT 1 FROM runtime_events AS opening
|
|
446
|
+
WHERE opening.invocation_id = legacy.invocation_id
|
|
447
|
+
AND opening.event_kind = 'invocation_opened'
|
|
448
|
+
)
|
|
449
|
+
`)
|
|
450
|
+
.all(selectedJson);
|
|
451
|
+
const handoffRows = this.db
|
|
452
|
+
.prepare(`
|
|
453
|
+
WITH selected(session_id) AS (SELECT value FROM json_each(?))
|
|
454
|
+
SELECT
|
|
455
|
+
terminal.rowid AS terminal_rowid,
|
|
456
|
+
terminal.event_id AS event_id,
|
|
457
|
+
terminal.session_id AS session_id,
|
|
458
|
+
terminal.invocation_id AS invocation_id,
|
|
459
|
+
terminal.run_id AS run_id,
|
|
460
|
+
terminal.turn_id AS turn_id,
|
|
461
|
+
terminal.payload_json AS payload_json
|
|
462
|
+
FROM selected
|
|
463
|
+
JOIN runtime_events AS terminal INDEXED BY runtime_events_by_session_kind
|
|
464
|
+
ON terminal.session_id = selected.session_id
|
|
465
|
+
AND terminal.event_kind = 'invocation_end'
|
|
466
|
+
WHERE CASE
|
|
467
|
+
WHEN json_valid(terminal.payload_json)
|
|
468
|
+
THEN json_type(terminal.payload_json, '$.actions.handoffPause')
|
|
469
|
+
END IS NOT NULL
|
|
470
|
+
`)
|
|
471
|
+
.all(selectedJson);
|
|
472
|
+
const handoffByRowId = new Map(handoffRows.map((row) => [row.terminal_rowid, row]));
|
|
473
|
+
const eventIdentity = this.db.prepare(`
|
|
474
|
+
SELECT event_id, session_id, invocation_id, run_id, turn_id, committed_at
|
|
475
|
+
FROM runtime_events
|
|
476
|
+
WHERE rowid = ?
|
|
477
|
+
`);
|
|
478
|
+
const eventCandidate = this.db.prepare(`
|
|
479
|
+
SELECT event_id, session_id, invocation_id, run_id, turn_id, committed_at, payload_json
|
|
480
|
+
FROM runtime_events
|
|
481
|
+
WHERE rowid = ?
|
|
482
|
+
`);
|
|
483
|
+
const legacyCandidate = this.db.prepare(`
|
|
484
|
+
SELECT opening_json
|
|
485
|
+
FROM runtime_legacy_invocation_openings
|
|
486
|
+
WHERE invocation_id = ?
|
|
487
|
+
`);
|
|
488
|
+
return [...eventRows, ...legacyRows]
|
|
489
|
+
.sort((a, b) => a.session_id.localeCompare(b.session_id) ||
|
|
490
|
+
a.invocation_id.localeCompare(b.invocation_id))
|
|
491
|
+
.map((row) => {
|
|
492
|
+
const base = { sessionId: row.session_id, invocationId: row.invocation_id };
|
|
493
|
+
const handoff = row.terminal_rowid === null ? undefined : handoffByRowId.get(row.terminal_rowid);
|
|
494
|
+
const needsCandidate = row.terminal_rowid === null || handoff !== undefined;
|
|
495
|
+
const needsIdentity = needsCandidate || mayBeTranscriptLedgerInvocationId(row.invocation_id);
|
|
496
|
+
if (!needsIdentity)
|
|
497
|
+
return base;
|
|
498
|
+
let identity;
|
|
499
|
+
let openingJson;
|
|
500
|
+
let openingEventId;
|
|
501
|
+
if (row.from_events === 1) {
|
|
502
|
+
if (row.opening_rowid === null) {
|
|
503
|
+
throw new Error(`Runtime invocation opening row is missing: ${row.invocation_id}`);
|
|
504
|
+
}
|
|
505
|
+
const detail = (needsCandidate ? eventCandidate : eventIdentity).get(row.opening_rowid);
|
|
506
|
+
if (!detail ||
|
|
507
|
+
detail.session_id !== row.session_id ||
|
|
508
|
+
detail.invocation_id !== row.invocation_id) {
|
|
509
|
+
throw new Error(`Runtime invocation opening identity changed: ${row.invocation_id}`);
|
|
510
|
+
}
|
|
511
|
+
identity = {
|
|
512
|
+
sessionId: detail.session_id,
|
|
513
|
+
invocationId: detail.invocation_id,
|
|
514
|
+
runId: detail.run_id,
|
|
515
|
+
turnId: detail.turn_id,
|
|
516
|
+
openedAt: detail.committed_at,
|
|
517
|
+
};
|
|
518
|
+
openingEventId = detail.event_id;
|
|
519
|
+
openingJson = detail.payload_json;
|
|
520
|
+
}
|
|
521
|
+
else {
|
|
522
|
+
if (row.run_id === null || row.turn_id === null || row.opened_at === null) {
|
|
523
|
+
throw new Error(`Legacy invocation opening identity is incomplete: ${row.invocation_id}`);
|
|
524
|
+
}
|
|
525
|
+
identity = {
|
|
526
|
+
sessionId: row.session_id,
|
|
527
|
+
invocationId: row.invocation_id,
|
|
528
|
+
runId: row.run_id,
|
|
529
|
+
turnId: row.turn_id,
|
|
530
|
+
openedAt: row.opened_at,
|
|
531
|
+
};
|
|
532
|
+
if (needsCandidate) {
|
|
533
|
+
openingJson = legacyCandidate.get(row.invocation_id)?.opening_json;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (!needsCandidate)
|
|
537
|
+
return { ...base, identity };
|
|
538
|
+
if (typeof openingJson !== 'string') {
|
|
539
|
+
throw new Error(`Runtime invocation opening payload is missing: ${row.invocation_id}`);
|
|
540
|
+
}
|
|
541
|
+
let opening;
|
|
542
|
+
if (row.from_events === 1) {
|
|
543
|
+
const event = decodeRuntimeEventStorageRow({
|
|
544
|
+
event_id: openingEventId ?? '',
|
|
545
|
+
session_id: identity.sessionId,
|
|
546
|
+
invocation_id: identity.invocationId,
|
|
547
|
+
run_id: identity.runId,
|
|
548
|
+
turn_id: identity.turnId,
|
|
549
|
+
payload_json: openingJson,
|
|
550
|
+
});
|
|
551
|
+
const decoded = runtimeEventInvocationOpening(event);
|
|
552
|
+
if (!decoded) {
|
|
553
|
+
throw new Error(`RuntimeEvent ${event.id} is indexed as an opening fact but is not one`);
|
|
554
|
+
}
|
|
555
|
+
opening = decoded;
|
|
556
|
+
}
|
|
557
|
+
else {
|
|
558
|
+
opening = decodeRuntimeInvocationOpened(JSON.parse(openingJson));
|
|
559
|
+
}
|
|
560
|
+
let terminalEvent;
|
|
561
|
+
if (handoff) {
|
|
562
|
+
if (handoff.session_id !== identity.sessionId ||
|
|
563
|
+
handoff.invocation_id !== identity.invocationId ||
|
|
564
|
+
handoff.run_id !== identity.runId ||
|
|
565
|
+
handoff.turn_id !== identity.turnId) {
|
|
566
|
+
throw new Error(`Runtime handoff terminal identity changed: ${row.invocation_id}`);
|
|
567
|
+
}
|
|
568
|
+
terminalEvent = decodeRuntimeEventStorageRow(handoff);
|
|
569
|
+
if (!isTerminalRuntimeEvent(terminalEvent)) {
|
|
570
|
+
throw new Error(`Runtime handoff fact is not terminal: ${terminalEvent.id}`);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
...base,
|
|
575
|
+
candidate: {
|
|
576
|
+
...identity,
|
|
577
|
+
opening,
|
|
578
|
+
...(terminalEvent ? { terminalEvent } : {}),
|
|
579
|
+
},
|
|
580
|
+
};
|
|
581
|
+
});
|
|
582
|
+
});
|
|
583
|
+
}
|
|
337
584
|
async readRunInvocation(sessionId, runId) {
|
|
338
585
|
assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
|
|
339
586
|
assertRuntimeStorageSafeId(runId, 'Invalid run id');
|
|
@@ -964,6 +1211,51 @@ export class SqliteRuntimeStore {
|
|
|
964
1211
|
const row = this.readContinuationClaimRow('boundary_digest = ?', boundaryDigest);
|
|
965
1212
|
return row ? this.decodeContinuationClaimStateRow(row) : undefined;
|
|
966
1213
|
}
|
|
1214
|
+
async listUnsettledContinuationClaimsForRecovery(sessionIds) {
|
|
1215
|
+
const selectedSessionIds = [...new Set(sessionIds)];
|
|
1216
|
+
for (const sessionId of selectedSessionIds) {
|
|
1217
|
+
assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
|
|
1218
|
+
}
|
|
1219
|
+
if (selectedSessionIds.length === 0)
|
|
1220
|
+
return [];
|
|
1221
|
+
const rows = this.db
|
|
1222
|
+
.prepare(`
|
|
1223
|
+
WITH selected(session_id) AS (SELECT value FROM json_each(?))
|
|
1224
|
+
SELECT
|
|
1225
|
+
claim.claim_id,
|
|
1226
|
+
claim.source_session_id,
|
|
1227
|
+
claim.source_invocation_id,
|
|
1228
|
+
claim.source_run_id,
|
|
1229
|
+
claim.source_turn_id,
|
|
1230
|
+
claim.source_event_high_water,
|
|
1231
|
+
claim.source_prefix_digest,
|
|
1232
|
+
claim.boundary_digest,
|
|
1233
|
+
claim.boundary_json,
|
|
1234
|
+
claim.provider_projection_version,
|
|
1235
|
+
claim.provider_replay_digest,
|
|
1236
|
+
claim.target_session_id,
|
|
1237
|
+
claim.target_invocation_id,
|
|
1238
|
+
claim.target_run_id,
|
|
1239
|
+
claim.target_turn_id,
|
|
1240
|
+
claim.target_opening_json,
|
|
1241
|
+
claim.claimed_at,
|
|
1242
|
+
claim.start_event_id,
|
|
1243
|
+
claim.start_kind,
|
|
1244
|
+
claim.protocol_version
|
|
1245
|
+
FROM selected
|
|
1246
|
+
JOIN runtime_continuation_claims AS claim
|
|
1247
|
+
ON claim.target_session_id = selected.session_id
|
|
1248
|
+
WHERE NOT EXISTS (
|
|
1249
|
+
SELECT 1
|
|
1250
|
+
FROM runtime_events AS terminal INDEXED BY runtime_events_terminal
|
|
1251
|
+
WHERE terminal.invocation_id = claim.target_invocation_id
|
|
1252
|
+
AND ${TERMINAL_RUNTIME_EVENT_SQL.replaceAll('payload_json', 'terminal.payload_json')}
|
|
1253
|
+
)
|
|
1254
|
+
ORDER BY claim.claimed_at ASC, claim.claim_id ASC
|
|
1255
|
+
`)
|
|
1256
|
+
.all(JSON.stringify(selectedSessionIds));
|
|
1257
|
+
return rows.map((row) => this.decodeContinuationClaimStateRow(row));
|
|
1258
|
+
}
|
|
967
1259
|
async listContinuationClaimsForRecovery(sessionId) {
|
|
968
1260
|
const rows = this.db
|
|
969
1261
|
.prepare(`
|
|
@@ -1041,25 +1333,119 @@ export class SqliteRuntimeStore {
|
|
|
1041
1333
|
async readImmutableSteeringMessageProof(sessionId, messageId) {
|
|
1042
1334
|
assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
|
|
1043
1335
|
assertRuntimeStorageSafeId(messageId, 'Invalid message id');
|
|
1044
|
-
const matches = this.
|
|
1336
|
+
const matches = this.readImmutableSteeringMessageEvents(sessionId, messageId);
|
|
1045
1337
|
if (matches.length > 1) {
|
|
1046
1338
|
throw new Error(`Immutable steering message identity conflict: ${messageId}`);
|
|
1047
1339
|
}
|
|
1048
1340
|
return matches[0] ? Object.freeze({ event: matches[0] }) : undefined;
|
|
1049
1341
|
}
|
|
1050
|
-
async
|
|
1051
|
-
assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1342
|
+
async readRecoveryMessageEvents(input) {
|
|
1343
|
+
assertRuntimeStorageSafeId(input.sessionId, 'Invalid session id');
|
|
1344
|
+
assertEvidenceReadBudget(input.budget);
|
|
1345
|
+
const turnIds = distinctSafeRuntimeIds(input.turnIds, 'Invalid recovery Turn id');
|
|
1346
|
+
const eventIds = distinctSafeRuntimeIds(input.eventIds, 'Invalid recovery event id');
|
|
1347
|
+
const selectedEventIds = new Set();
|
|
1348
|
+
const measuredRows = [];
|
|
1349
|
+
const measureEventsById = (ids) => {
|
|
1350
|
+
for (const batch of batches(ids, RECOVERY_MESSAGE_QUERY_BATCH_SIZE)) {
|
|
1351
|
+
const placeholders = batch.map(() => '?').join(', ');
|
|
1352
|
+
const rows = this.db
|
|
1353
|
+
.prepare(`
|
|
1354
|
+
SELECT event_id, session_id,
|
|
1355
|
+
length(CAST(payload_json AS BLOB)) AS stored_bytes
|
|
1356
|
+
FROM runtime_events
|
|
1357
|
+
WHERE event_id IN (${placeholders})
|
|
1358
|
+
`)
|
|
1359
|
+
.all(...batch);
|
|
1360
|
+
for (const row of rows) {
|
|
1361
|
+
if (typeof row.event_id !== 'string' || typeof row.session_id !== 'string') {
|
|
1362
|
+
throw new Error('Invalid recovery RuntimeEvent measurement row');
|
|
1363
|
+
}
|
|
1364
|
+
if (row.session_id !== input.sessionId || selectedEventIds.has(row.event_id))
|
|
1365
|
+
continue;
|
|
1366
|
+
selectedEventIds.add(row.event_id);
|
|
1367
|
+
measuredRows.push({ event_id: row.event_id, stored_bytes: row.stored_bytes });
|
|
1368
|
+
if (measuredRows.length > input.budget.maxRecords)
|
|
1369
|
+
return false;
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
return true;
|
|
1373
|
+
};
|
|
1374
|
+
if (!measureEventsById(eventIds))
|
|
1375
|
+
return { status: 'limit_exceeded' };
|
|
1376
|
+
const additionalTurnEventIds = new Set();
|
|
1377
|
+
for (const batch of batches(turnIds, RECOVERY_MESSAGE_QUERY_BATCH_SIZE)) {
|
|
1378
|
+
const placeholders = batch.map(() => '?').join(', ');
|
|
1379
|
+
const rows = this.db
|
|
1380
|
+
.prepare(`
|
|
1381
|
+
SELECT event_id
|
|
1382
|
+
FROM runtime_events
|
|
1383
|
+
WHERE session_id = ?
|
|
1384
|
+
AND turn_id IN (${placeholders})
|
|
1385
|
+
AND event_kind = 'text'
|
|
1386
|
+
AND CASE
|
|
1387
|
+
WHEN json_valid(payload_json)
|
|
1388
|
+
THEN json_extract(payload_json, '$.partial')
|
|
1389
|
+
END = 0
|
|
1390
|
+
AND CASE
|
|
1391
|
+
WHEN json_valid(payload_json)
|
|
1392
|
+
THEN json_extract(payload_json, '$.role')
|
|
1393
|
+
END = 'user'
|
|
1394
|
+
AND coalesce(CASE
|
|
1395
|
+
WHEN json_valid(payload_json)
|
|
1396
|
+
THEN json_extract(payload_json, '$.content.steering')
|
|
1397
|
+
END, 0) = 0
|
|
1398
|
+
LIMIT ?
|
|
1399
|
+
`)
|
|
1400
|
+
.all(input.sessionId, ...batch, input.budget.maxRecords + 1);
|
|
1401
|
+
for (const row of rows) {
|
|
1402
|
+
if (typeof row.event_id !== 'string') {
|
|
1403
|
+
throw new Error('Invalid recovery RuntimeEvent identity row');
|
|
1404
|
+
}
|
|
1405
|
+
if (!selectedEventIds.has(row.event_id))
|
|
1406
|
+
additionalTurnEventIds.add(row.event_id);
|
|
1407
|
+
if (selectedEventIds.size + additionalTurnEventIds.size > input.budget.maxRecords) {
|
|
1408
|
+
return { status: 'limit_exceeded' };
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
if (!measureEventsById([...additionalTurnEventIds]))
|
|
1413
|
+
return { status: 'limit_exceeded' };
|
|
1414
|
+
const measurement = measureEvidenceRows(measuredRows, input.budget, 'Invalid recovery RuntimeEvent evidence measurement row');
|
|
1415
|
+
if (!measurement)
|
|
1416
|
+
return { status: 'limit_exceeded' };
|
|
1417
|
+
const storedBytesById = new Map(measuredRows.map((row) => [row.event_id, requireRuntimeEventScanCount(row.stored_bytes)]));
|
|
1418
|
+
const events = new Map();
|
|
1419
|
+
for (const batch of batches([...selectedEventIds], RECOVERY_MESSAGE_QUERY_BATCH_SIZE)) {
|
|
1420
|
+
const placeholders = batch.map(() => '?').join(', ');
|
|
1421
|
+
const rows = this.db
|
|
1422
|
+
.prepare(`
|
|
1423
|
+
SELECT event_id, session_id, invocation_id, run_id, turn_id, payload_json,
|
|
1424
|
+
length(CAST(payload_json AS BLOB)) AS stored_bytes
|
|
1425
|
+
FROM runtime_events
|
|
1426
|
+
WHERE event_id IN (${placeholders})
|
|
1427
|
+
`)
|
|
1428
|
+
.all(...batch);
|
|
1429
|
+
for (const row of rows) {
|
|
1430
|
+
const event = decodeRuntimeEventStorageRow(row);
|
|
1431
|
+
if (event.sessionId !== input.sessionId)
|
|
1432
|
+
continue;
|
|
1433
|
+
if (storedBytesById.get(event.id) !== requireRuntimeEventScanCount(row.stored_bytes)) {
|
|
1434
|
+
throw new Error('Recovery RuntimeEvent evidence changed while reading');
|
|
1435
|
+
}
|
|
1436
|
+
events.set(event.id, event);
|
|
1060
1437
|
}
|
|
1061
|
-
messages.set(messageId, event);
|
|
1062
1438
|
}
|
|
1439
|
+
if (events.size !== selectedEventIds.size) {
|
|
1440
|
+
throw new Error('Recovery RuntimeEvent evidence changed while reading');
|
|
1441
|
+
}
|
|
1442
|
+
return {
|
|
1443
|
+
status: 'complete',
|
|
1444
|
+
records: [...events.values()].sort((left, right) => left.ts - right.ts ||
|
|
1445
|
+
left.runId.localeCompare(right.runId) ||
|
|
1446
|
+
left.id.localeCompare(right.id)),
|
|
1447
|
+
...measurement,
|
|
1448
|
+
};
|
|
1063
1449
|
}
|
|
1064
1450
|
/**
|
|
1065
1451
|
* Narrows recall to the Sessions whose ledger could project a message
|
|
@@ -2235,25 +2621,37 @@ export class SqliteRuntimeStore {
|
|
|
2235
2621
|
async readToolOperation(operationId) {
|
|
2236
2622
|
return this.readToolOperationSync(operationId);
|
|
2237
2623
|
}
|
|
2238
|
-
async listUnsettledToolOperations(
|
|
2624
|
+
async listUnsettledToolOperations(sessionIds) {
|
|
2625
|
+
const selectedSessionIds = sessionIds === undefined
|
|
2626
|
+
? undefined
|
|
2627
|
+
: [...new Set(typeof sessionIds === 'string' ? [sessionIds] : sessionIds)];
|
|
2628
|
+
if (selectedSessionIds?.length === 0)
|
|
2629
|
+
return [];
|
|
2239
2630
|
const query = `
|
|
2240
|
-
SELECT
|
|
2241
|
-
|
|
2242
|
-
|
|
2631
|
+
SELECT call_event.session_id,
|
|
2632
|
+
tool_operations.operation_id, tool_operations.invocation_id,
|
|
2633
|
+
tool_operations.run_id, tool_operations.turn_id,
|
|
2634
|
+
tool_operations.provider_tool_call_id, tool_operations.tool_name,
|
|
2635
|
+
tool_operations.canonical_args_hash, tool_operations.recovery_mode,
|
|
2636
|
+
tool_operations.current_state, tool_operations.call_event_id,
|
|
2637
|
+
tool_operations.dispatch_event_id, tool_operations.result_event_id,
|
|
2638
|
+
tool_operations.version
|
|
2243
2639
|
FROM tool_operations
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2640
|
+
JOIN runtime_events AS call_event
|
|
2641
|
+
ON call_event.event_id = tool_operations.call_event_id
|
|
2642
|
+
WHERE tool_operations.current_state = 'prepared'
|
|
2643
|
+
AND tool_operations.result_event_id IS NULL
|
|
2644
|
+
AND tool_operations.dispatch_event_id IS NOT NULL
|
|
2645
|
+
${selectedSessionIds === undefined
|
|
2248
2646
|
? ''
|
|
2249
|
-
: 'AND
|
|
2250
|
-
ORDER BY invocation_id ASC, operation_id ASC
|
|
2647
|
+
: 'AND call_event.session_id IN (SELECT value FROM json_each(?))'}
|
|
2648
|
+
ORDER BY tool_operations.invocation_id ASC, tool_operations.operation_id ASC
|
|
2251
2649
|
`;
|
|
2252
2650
|
const statement = this.db.prepare(query);
|
|
2253
|
-
const rows = (
|
|
2651
|
+
const rows = (selectedSessionIds === undefined
|
|
2254
2652
|
? statement.all()
|
|
2255
|
-
: statement.all(
|
|
2256
|
-
return rows.map(toolOperationFromRow);
|
|
2653
|
+
: statement.all(JSON.stringify(selectedSessionIds)));
|
|
2654
|
+
return rows.map((row) => ({ sessionId: row.session_id, ...toolOperationFromRow(row) }));
|
|
2257
2655
|
}
|
|
2258
2656
|
async readToolJournal(operationId) {
|
|
2259
2657
|
const rows = this.db
|
|
@@ -2268,9 +2666,69 @@ export class SqliteRuntimeStore {
|
|
|
2268
2666
|
.all(operationId);
|
|
2269
2667
|
return rows.map(toolJournalRecordFromRow);
|
|
2270
2668
|
}
|
|
2669
|
+
/** Explicit full-workspace integrity audit and disposable projection rebuild. */
|
|
2271
2670
|
async rebuildToolProjectionsFromRuntimeEvents() {
|
|
2272
2671
|
return this.transaction(() => this.rebuildToolProjectionsFromRuntimeEventsSync());
|
|
2273
2672
|
}
|
|
2673
|
+
/** Rebuild one Session's disposable tool projections while its owner holds a fence. */
|
|
2674
|
+
async rebuildToolProjectionsForSession(sessionId) {
|
|
2675
|
+
await this.transaction(() => this.rebuildToolProjectionsFromRuntimeEventsSync(sessionId));
|
|
2676
|
+
}
|
|
2677
|
+
/**
|
|
2678
|
+
* Repair terminal projections for unsettled tools without decoding the
|
|
2679
|
+
* Session's full RuntimeEvent history. Bundle export is a compatibility
|
|
2680
|
+
* boundary: unrelated historical payloads may be byte-preserved and newer
|
|
2681
|
+
* or older than the RuntimeEvent schema understood by this build.
|
|
2682
|
+
*/
|
|
2683
|
+
async rebuildTerminalToolProjectionsForSessions(sessionIds) {
|
|
2684
|
+
const operations = await this.listUnsettledToolOperations(sessionIds);
|
|
2685
|
+
if (operations.length === 0)
|
|
2686
|
+
return;
|
|
2687
|
+
this.transaction(() => {
|
|
2688
|
+
const dispatchSequence = this.db.prepare(`
|
|
2689
|
+
SELECT event_seq
|
|
2690
|
+
FROM runtime_events
|
|
2691
|
+
WHERE event_id = ? AND session_id = ? AND invocation_id = ?
|
|
2692
|
+
`);
|
|
2693
|
+
const firstTerminal = this.db.prepare(`
|
|
2694
|
+
SELECT event_id, event_seq, committed_at
|
|
2695
|
+
FROM runtime_events
|
|
2696
|
+
WHERE session_id = ? AND invocation_id = ?
|
|
2697
|
+
AND ${TERMINAL_RUNTIME_EVENT_SQL}
|
|
2698
|
+
ORDER BY event_seq ASC, event_id ASC
|
|
2699
|
+
LIMIT 1
|
|
2700
|
+
`);
|
|
2701
|
+
const insertJournal = this.db.prepare(`
|
|
2702
|
+
INSERT INTO tool_journal_events (
|
|
2703
|
+
journal_event_id, operation_id, invocation_id, run_id, turn_id, state,
|
|
2704
|
+
runtime_event_id, canonical_args_hash, recovery_mode, committed_at
|
|
2705
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2706
|
+
`);
|
|
2707
|
+
const updateOperation = this.db.prepare(`
|
|
2708
|
+
UPDATE tool_operations
|
|
2709
|
+
SET current_state = ?, version = version + 1
|
|
2710
|
+
WHERE operation_id = ? AND current_state = 'prepared' AND result_event_id IS NULL
|
|
2711
|
+
`);
|
|
2712
|
+
for (const operation of operations) {
|
|
2713
|
+
if (!operation.dispatchEventId)
|
|
2714
|
+
continue;
|
|
2715
|
+
const dispatch = dispatchSequence.get(operation.dispatchEventId, operation.sessionId, operation.invocationId);
|
|
2716
|
+
if (!dispatch)
|
|
2717
|
+
continue;
|
|
2718
|
+
const terminal = firstTerminal.get(operation.sessionId, operation.invocationId);
|
|
2719
|
+
if (!terminal || terminal.event_seq <= dispatch.event_seq)
|
|
2720
|
+
continue;
|
|
2721
|
+
const state = operation.toolName === 'AskUserQuestion' && operation.recoveryMode === 'never_auto_retry'
|
|
2722
|
+
? 'abandoned'
|
|
2723
|
+
: 'interrupted_unknown';
|
|
2724
|
+
insertJournal.run(journalEventIdFor(operation.operationId, terminal.event_id, state), operation.operationId, operation.invocationId, operation.runId, operation.turnId, state, terminal.event_id, operation.canonicalArgsHash, operation.recoveryMode, terminal.committed_at);
|
|
2725
|
+
const updated = updateOperation.run(state, operation.operationId);
|
|
2726
|
+
if (updated.changes !== 1) {
|
|
2727
|
+
throw new Error(`Tool operation projection changed during export: ${operation.operationId}`);
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
});
|
|
2731
|
+
}
|
|
2274
2732
|
rebuildToolProjectionsFromRuntimeEventsSync(sessionId) {
|
|
2275
2733
|
const statement = this.db.prepare(`
|
|
2276
2734
|
SELECT event_id, session_id, invocation_id, run_id, turn_id,
|
|
@@ -2284,6 +2742,14 @@ export class SqliteRuntimeStore {
|
|
|
2284
2742
|
: statement.all(sessionId));
|
|
2285
2743
|
const events = rows.map(decodeRuntimeEventStorageRow);
|
|
2286
2744
|
const eventOrder = new Map(events.map((event, index) => [event.id, index]));
|
|
2745
|
+
const runtimeInvocationKey = (event) => JSON.stringify([event.sessionId, event.invocationId]);
|
|
2746
|
+
const terminalEventsByInvocation = new Map();
|
|
2747
|
+
for (const event of events) {
|
|
2748
|
+
if (isTerminalRuntimeEvent(event) &&
|
|
2749
|
+
!terminalEventsByInvocation.has(runtimeInvocationKey(event))) {
|
|
2750
|
+
terminalEventsByInvocation.set(runtimeInvocationKey(event), event);
|
|
2751
|
+
}
|
|
2752
|
+
}
|
|
2287
2753
|
const committedAt = new Map(rows.map((row, index) => [events[index].id, row.committed_at]));
|
|
2288
2754
|
const scan = scanToolLedger(events);
|
|
2289
2755
|
if (scan.hasCorruption) {
|
|
@@ -2341,6 +2807,21 @@ export class SqliteRuntimeStore {
|
|
|
2341
2807
|
}
|
|
2342
2808
|
const reconcileEvent = recovery.kind === 'valid' ? recovery.reconcileEvent : undefined;
|
|
2343
2809
|
const decisionEvent = recovery.kind === 'valid' ? recovery.decisionEvent : undefined;
|
|
2810
|
+
const decision = recovery.kind === 'valid' ? recovery.decision : undefined;
|
|
2811
|
+
const terminalEvent = terminalEventsByInvocation.get(runtimeInvocationKey(event));
|
|
2812
|
+
const terminalAfterDispatch = terminalEvent !== undefined &&
|
|
2813
|
+
requireRuntimeEventOrder(eventOrder, terminalEvent.id) >
|
|
2814
|
+
requireRuntimeEventOrder(eventOrder, event.id);
|
|
2815
|
+
const abandoned = !decision &&
|
|
2816
|
+
!operation.responseEvent &&
|
|
2817
|
+
dispatch.toolName === 'AskUserQuestion' &&
|
|
2818
|
+
dispatch.recoveryMode === 'never_auto_retry' &&
|
|
2819
|
+
terminalAfterDispatch;
|
|
2820
|
+
// A terminal invocation closes the tool's execution window, but does not
|
|
2821
|
+
// prove whether an external side effect completed. Preserve that
|
|
2822
|
+
// uncertainty in the query projection without rewriting the immutable
|
|
2823
|
+
// RuntimeEvent history.
|
|
2824
|
+
const interruptedUnknown = !decision && !operation.responseEvent && !abandoned && terminalAfterDispatch;
|
|
2344
2825
|
this.db
|
|
2345
2826
|
.prepare(`
|
|
2346
2827
|
INSERT INTO tool_journal_events (
|
|
@@ -2351,14 +2832,17 @@ export class SqliteRuntimeStore {
|
|
|
2351
2832
|
.run(`${dispatch.operationId}_prepared`, dispatch.operationId, event.invocationId, event.runId, event.turnId, event.id, dispatch.canonicalArgsHash, dispatch.recoveryMode, committedAt.get(event.id) ?? event.ts);
|
|
2352
2833
|
journalEvents += 1;
|
|
2353
2834
|
const response = operation.responseEvent;
|
|
2354
|
-
const decision = recovery.kind === 'valid' ? recovery.decision : undefined;
|
|
2355
2835
|
const currentState = decision
|
|
2356
2836
|
? decision.disposition === 'completed'
|
|
2357
2837
|
? 'recovery_completed'
|
|
2358
2838
|
: 'recovery_parked'
|
|
2359
2839
|
: response
|
|
2360
2840
|
? 'outcome_committed'
|
|
2361
|
-
:
|
|
2841
|
+
: abandoned
|
|
2842
|
+
? 'abandoned'
|
|
2843
|
+
: interruptedUnknown
|
|
2844
|
+
? 'interrupted_unknown'
|
|
2845
|
+
: 'prepared';
|
|
2362
2846
|
const tail = [
|
|
2363
2847
|
...(reconcileEvent
|
|
2364
2848
|
? [{ event: reconcileEvent, state: 'reconcile_observed' }]
|
|
@@ -2374,6 +2858,12 @@ export class SqliteRuntimeStore {
|
|
|
2374
2858
|
},
|
|
2375
2859
|
]
|
|
2376
2860
|
: []),
|
|
2861
|
+
...(abandoned && terminalEvent
|
|
2862
|
+
? [{ event: terminalEvent, state: 'abandoned' }]
|
|
2863
|
+
: []),
|
|
2864
|
+
...(interruptedUnknown && terminalEvent
|
|
2865
|
+
? [{ event: terminalEvent, state: 'interrupted_unknown' }]
|
|
2866
|
+
: []),
|
|
2377
2867
|
].sort((a, b) => requireRuntimeEventOrder(eventOrder, a.event.id) -
|
|
2378
2868
|
requireRuntimeEventOrder(eventOrder, b.event.id));
|
|
2379
2869
|
this.db
|
|
@@ -2393,7 +2883,7 @@ export class SqliteRuntimeStore {
|
|
|
2393
2883
|
runtime_event_id, canonical_args_hash, recovery_mode, metadata_json, committed_at
|
|
2394
2884
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2395
2885
|
`)
|
|
2396
|
-
.run(journalEventIdFor(dispatch.operationId, item.event, item.state), dispatch.operationId, item.event.invocationId, item.event.runId, item.event.turnId, item.state, item.event.id, dispatch.canonicalArgsHash, dispatch.recoveryMode, item.event.actions?.toolRecovery
|
|
2886
|
+
.run(journalEventIdFor(dispatch.operationId, item.event.id, item.state), dispatch.operationId, item.event.invocationId, item.event.runId, item.event.turnId, item.state, item.event.id, dispatch.canonicalArgsHash, dispatch.recoveryMode, item.event.actions?.toolRecovery
|
|
2397
2887
|
? JSON.stringify(item.event.actions.toolRecovery)
|
|
2398
2888
|
: null, committedAt.get(item.event.id) ?? item.event.ts);
|
|
2399
2889
|
journalEvents += 1;
|
|
@@ -2529,8 +3019,16 @@ export class SqliteRuntimeStore {
|
|
|
2529
3019
|
}
|
|
2530
3020
|
}
|
|
2531
3021
|
transaction(operation) {
|
|
2532
|
-
if (this.databaseLease)
|
|
2533
|
-
|
|
3022
|
+
if (this.databaseLease) {
|
|
3023
|
+
const nested = this.db.isTransaction;
|
|
3024
|
+
return this.databaseLease.transaction('write', () => {
|
|
3025
|
+
// A sibling lease may have changed the shared transaction view since
|
|
3026
|
+
// this store last used its reconstructible cache.
|
|
3027
|
+
if (nested)
|
|
3028
|
+
this.clearToolLedgerCache();
|
|
3029
|
+
return operation();
|
|
3030
|
+
});
|
|
3031
|
+
}
|
|
2534
3032
|
this.db.exec('BEGIN IMMEDIATE');
|
|
2535
3033
|
let result;
|
|
2536
3034
|
try {
|
|
@@ -2544,10 +3042,17 @@ export class SqliteRuntimeStore {
|
|
|
2544
3042
|
catch {
|
|
2545
3043
|
// Preserve the protocol failure that caused rollback.
|
|
2546
3044
|
}
|
|
3045
|
+
// Reducers may have loaded rows written earlier in this transaction as
|
|
3046
|
+
// their immutable base. Bump the local view even on rollback so the next
|
|
3047
|
+
// admission discards that phantom base before retrying.
|
|
3048
|
+
this.localCommittedWriteRevision += 1;
|
|
2547
3049
|
this.settleEventCommits(false);
|
|
3050
|
+
this.settleToolLedgerStates(false);
|
|
2548
3051
|
throw error;
|
|
2549
3052
|
}
|
|
3053
|
+
this.localCommittedWriteRevision += 1;
|
|
2550
3054
|
this.settleEventCommits(true);
|
|
3055
|
+
this.settleToolLedgerStates(true);
|
|
2551
3056
|
return result;
|
|
2552
3057
|
}
|
|
2553
3058
|
noteEventCommit(sessionId) {
|
|
@@ -2765,64 +3270,268 @@ export class SqliteRuntimeStore {
|
|
|
2765
3270
|
}
|
|
2766
3271
|
}
|
|
2767
3272
|
assertToolLedgerTransition(candidateEvents, expectedTransition) {
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
const
|
|
2773
|
-
|
|
3273
|
+
const canonicalEncodings = candidateEvents.map(encodeCanonicalRuntimeEvent);
|
|
3274
|
+
const canonicalEvents = canonicalEncodings.map(({ event }) => event);
|
|
3275
|
+
const entry = this.toolLedgerCacheEntry(canonicalEvents);
|
|
3276
|
+
const appendedEncodings = canonicalEncodings.filter(({ event }) => entry.reducer.event(event.id) === undefined);
|
|
3277
|
+
const validation = validateIncrementalToolLedgerTransition({
|
|
3278
|
+
reducer: entry.reducer,
|
|
3279
|
+
candidateEvents: canonicalEvents,
|
|
3280
|
+
expectedTransition,
|
|
3281
|
+
});
|
|
3282
|
+
if (!validation.ok) {
|
|
3283
|
+
if (validation.source === 'existing') {
|
|
3284
|
+
throw new ToolLedgerCorruptionError(validation.code, validation.eventId);
|
|
3285
|
+
}
|
|
3286
|
+
throw new ToolLedgerRejectionError(validation.code, validation.eventId);
|
|
3287
|
+
}
|
|
3288
|
+
if (validation.appendedEvents === 0)
|
|
3289
|
+
return;
|
|
3290
|
+
this.noteToolLedgerState(entry, validation.checkpoint, canonicalEvents.map((event) => event.invocationId), {
|
|
3291
|
+
eventCount: validation.appendedEvents,
|
|
3292
|
+
estimatedBytes: estimateToolLedgerCacheBytes(appendedEncodings.reduce((bytes, encoding) => bytes + Buffer.byteLength(encoding.json, 'utf8'), 0), validation.appendedEvents),
|
|
3293
|
+
});
|
|
3294
|
+
}
|
|
3295
|
+
toolLedgerCacheEntry(candidateEvents) {
|
|
3296
|
+
const currentVersion = this.currentToolLedgerCacheVersion();
|
|
3297
|
+
if (this.toolLedgerCacheVersion !== currentVersion)
|
|
3298
|
+
this.refreshToolLedgerCacheVersion();
|
|
3299
|
+
const directInvocationIds = new Set(candidateEvents.map((event) => event.invocationId));
|
|
3300
|
+
const directOperationIds = referencedToolOperationIds(candidateEvents);
|
|
3301
|
+
for (const invocationId of this.toolLedgerOperationInvocations(directOperationIds)) {
|
|
3302
|
+
directInvocationIds.add(invocationId);
|
|
3303
|
+
}
|
|
3304
|
+
for (const [key, entry] of this.toolLedgerCache) {
|
|
3305
|
+
if (entry.seedInvocationIds.size === directInvocationIds.size &&
|
|
3306
|
+
[...directInvocationIds].every((invocationId) => entry.seedInvocationIds.has(invocationId))) {
|
|
3307
|
+
this.toolLedgerCacheMetrics.hits += 1;
|
|
3308
|
+
this.touchToolLedgerCacheEntry(key, entry);
|
|
3309
|
+
return entry;
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
this.toolLedgerCacheMetrics.misses += 1;
|
|
3313
|
+
const invocationIds = new Set(directInvocationIds);
|
|
3314
|
+
const operationIds = new Set(directOperationIds);
|
|
3315
|
+
const resolvedOperationIds = new Set();
|
|
3316
|
+
const loadedInvocationIds = new Set();
|
|
3317
|
+
const scopedEvents = [];
|
|
3318
|
+
let storedPayloadBytes = 0;
|
|
2774
3319
|
const readInvocation = this.db.prepare(`
|
|
2775
|
-
SELECT event_id, session_id, invocation_id, run_id, turn_id, payload_json
|
|
3320
|
+
SELECT event_id, session_id, invocation_id, run_id, turn_id, event_seq, payload_json,
|
|
3321
|
+
length(CAST(payload_json AS BLOB)) AS stored_bytes
|
|
2776
3322
|
FROM runtime_events
|
|
2777
3323
|
WHERE invocation_id = ?
|
|
2778
3324
|
ORDER BY event_seq ASC, event_id ASC
|
|
2779
3325
|
`);
|
|
2780
|
-
|
|
2781
|
-
|
|
3326
|
+
while (true) {
|
|
3327
|
+
const pendingOperationIds = [...operationIds].filter((operationId) => !resolvedOperationIds.has(operationId));
|
|
3328
|
+
if (pendingOperationIds.length > 0) {
|
|
3329
|
+
for (const operationId of pendingOperationIds)
|
|
3330
|
+
resolvedOperationIds.add(operationId);
|
|
3331
|
+
for (const invocationId of this.toolLedgerOperationInvocations(pendingOperationIds)) {
|
|
3332
|
+
invocationIds.add(invocationId);
|
|
3333
|
+
}
|
|
3334
|
+
}
|
|
3335
|
+
const pendingInvocationIds = [...invocationIds]
|
|
3336
|
+
.filter((invocationId) => !loadedInvocationIds.has(invocationId))
|
|
3337
|
+
.sort();
|
|
3338
|
+
if (pendingInvocationIds.length === 0 && pendingOperationIds.length === 0)
|
|
3339
|
+
break;
|
|
3340
|
+
for (const invocationId of pendingInvocationIds) {
|
|
3341
|
+
loadedInvocationIds.add(invocationId);
|
|
3342
|
+
const rows = readInvocation.all(invocationId);
|
|
3343
|
+
for (const row of rows) {
|
|
3344
|
+
storedPayloadBytes += requireRuntimeEventScanCount(row.stored_bytes);
|
|
3345
|
+
const event = decodeRuntimeEventStorageRow(row);
|
|
3346
|
+
scopedEvents.push({ event, eventSeq: row.event_seq });
|
|
3347
|
+
if (event.refs?.parentOperationId)
|
|
3348
|
+
operationIds.add(event.refs.parentOperationId);
|
|
3349
|
+
}
|
|
3350
|
+
}
|
|
2782
3351
|
}
|
|
2783
|
-
const
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
3352
|
+
const sortedSeedInvocationIds = [...directInvocationIds].sort();
|
|
3353
|
+
const sortedInvocationIds = [...invocationIds].sort();
|
|
3354
|
+
const key = JSON.stringify([sortedSeedInvocationIds, sortedInvocationIds]);
|
|
3355
|
+
const existing = this.toolLedgerCache.get(key);
|
|
3356
|
+
if (existing) {
|
|
3357
|
+
this.touchToolLedgerCacheEntry(key, existing);
|
|
3358
|
+
return existing;
|
|
3359
|
+
}
|
|
3360
|
+
scopedEvents.sort((left, right) => left.event.invocationId.localeCompare(right.event.invocationId) ||
|
|
3361
|
+
left.eventSeq - right.eventSeq ||
|
|
3362
|
+
left.event.id.localeCompare(right.event.id));
|
|
3363
|
+
const entry = {
|
|
3364
|
+
reducer: new ToolLedgerReducer(scopedEvents.map(({ event }) => event)),
|
|
3365
|
+
seedInvocationIds: new Set(sortedSeedInvocationIds),
|
|
3366
|
+
invocationIds: new Set(sortedInvocationIds),
|
|
3367
|
+
eventCount: scopedEvents.length,
|
|
3368
|
+
estimatedBytes: estimateToolLedgerCacheBytes(storedPayloadBytes, scopedEvents.length),
|
|
3369
|
+
};
|
|
3370
|
+
if (this.toolLedgerEntryExceedsAdmissionBudget(entry)) {
|
|
3371
|
+
this.toolLedgerCacheMetrics.transientEntries += 1;
|
|
3372
|
+
return entry;
|
|
3373
|
+
}
|
|
3374
|
+
this.retainToolLedgerCacheEntry(key, entry);
|
|
3375
|
+
this.trimToolLedgerCache();
|
|
3376
|
+
return entry;
|
|
3377
|
+
}
|
|
3378
|
+
toolLedgerOperationInvocations(operationIds) {
|
|
3379
|
+
const ids = [...new Set(operationIds)].sort();
|
|
3380
|
+
if (ids.length === 0)
|
|
3381
|
+
return new Set();
|
|
3382
|
+
const placeholders = ids.map(() => '?').join(', ');
|
|
3383
|
+
const rows = this.db
|
|
3384
|
+
.prepare(`
|
|
3385
|
+
SELECT DISTINCT invocation_id
|
|
3386
|
+
FROM runtime_events
|
|
3387
|
+
WHERE event_kind = 'tool_dispatch'
|
|
3388
|
+
AND CASE
|
|
3389
|
+
WHEN json_valid(payload_json)
|
|
3390
|
+
THEN json_extract(payload_json, '$.actions.toolDispatch.operationId')
|
|
3391
|
+
END IN (${placeholders})
|
|
3392
|
+
`)
|
|
3393
|
+
.all(...ids);
|
|
3394
|
+
return new Set(rows.map((row) => row.invocation_id));
|
|
3395
|
+
}
|
|
3396
|
+
noteToolLedgerState(entry, checkpoint, invocationIds, delta) {
|
|
3397
|
+
const reducer = entry.reducer;
|
|
3398
|
+
const existing = this.uncommittedToolLedgerStates.get(reducer);
|
|
3399
|
+
if (existing) {
|
|
3400
|
+
for (const invocationId of invocationIds)
|
|
3401
|
+
existing.changedInvocationIds.add(invocationId);
|
|
3402
|
+
this.adjustToolLedgerCacheEntry(entry, delta);
|
|
3403
|
+
return;
|
|
3404
|
+
}
|
|
3405
|
+
if (this.uncommittedToolLedgerStates.size === 0 && this.databaseLease) {
|
|
3406
|
+
this.databaseLease.onTransactionSettled((committed) => this.settleToolLedgerStates(committed));
|
|
2790
3407
|
}
|
|
3408
|
+
this.uncommittedToolLedgerStates.set(reducer, {
|
|
3409
|
+
checkpoint,
|
|
3410
|
+
changedInvocationIds: new Set(invocationIds),
|
|
3411
|
+
entry,
|
|
3412
|
+
estimatedBytesBefore: entry.estimatedBytes,
|
|
3413
|
+
eventCountBefore: entry.eventCount,
|
|
3414
|
+
});
|
|
3415
|
+
this.adjustToolLedgerCacheEntry(entry, delta);
|
|
2791
3416
|
}
|
|
2792
|
-
|
|
2793
|
-
const
|
|
2794
|
-
|
|
2795
|
-
|
|
3417
|
+
settleToolLedgerStates(committed) {
|
|
3418
|
+
const states = [...this.uncommittedToolLedgerStates.entries()];
|
|
3419
|
+
this.uncommittedToolLedgerStates.clear();
|
|
3420
|
+
if (states.length === 0)
|
|
3421
|
+
return;
|
|
3422
|
+
if (!committed) {
|
|
3423
|
+
for (const [reducer, state] of states.reverse()) {
|
|
3424
|
+
reducer.rollback(state.checkpoint);
|
|
3425
|
+
this.restoreToolLedgerCacheEntry(state);
|
|
3426
|
+
}
|
|
3427
|
+
this.trimToolLedgerCache();
|
|
3428
|
+
return;
|
|
3429
|
+
}
|
|
3430
|
+
const retained = new Set(states.map(([reducer]) => reducer));
|
|
3431
|
+
const changedInvocationIds = new Set(states.flatMap(([, state]) => [...state.changedInvocationIds]));
|
|
3432
|
+
for (const [key, entry] of this.toolLedgerCache) {
|
|
3433
|
+
if (retained.has(entry.reducer))
|
|
3434
|
+
continue;
|
|
3435
|
+
if ([...entry.invocationIds].some((id) => changedInvocationIds.has(id))) {
|
|
3436
|
+
this.deleteToolLedgerCacheEntry(key);
|
|
3437
|
+
}
|
|
2796
3438
|
}
|
|
2797
|
-
const
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
3439
|
+
for (const [reducer, state] of states)
|
|
3440
|
+
reducer.commit(state.checkpoint);
|
|
3441
|
+
this.toolLedgerCacheVersion = this.currentToolLedgerCacheVersion();
|
|
3442
|
+
this.trimToolLedgerCache();
|
|
3443
|
+
}
|
|
3444
|
+
refreshToolLedgerCacheVersion() {
|
|
3445
|
+
if (this.uncommittedToolLedgerStates.size > 0) {
|
|
3446
|
+
throw new Error('Cannot invalidate tool ledger state during an open write transaction');
|
|
3447
|
+
}
|
|
3448
|
+
this.clearToolLedgerCache();
|
|
3449
|
+
this.toolLedgerCacheVersion = this.currentToolLedgerCacheVersion();
|
|
3450
|
+
}
|
|
3451
|
+
retainToolLedgerCacheEntry(key, entry) {
|
|
3452
|
+
entry.cacheKey = key;
|
|
3453
|
+
this.toolLedgerCache.set(key, entry);
|
|
3454
|
+
this.toolLedgerCacheEstimatedBytes += entry.estimatedBytes;
|
|
3455
|
+
this.toolLedgerCacheEventCount += entry.eventCount;
|
|
3456
|
+
}
|
|
3457
|
+
touchToolLedgerCacheEntry(key, entry) {
|
|
3458
|
+
this.toolLedgerCache.delete(key);
|
|
3459
|
+
this.toolLedgerCache.set(key, entry);
|
|
3460
|
+
}
|
|
3461
|
+
adjustToolLedgerCacheEntry(entry, delta) {
|
|
3462
|
+
entry.estimatedBytes += delta.estimatedBytes;
|
|
3463
|
+
entry.eventCount += delta.eventCount;
|
|
3464
|
+
if (entry.cacheKey && this.toolLedgerCache.get(entry.cacheKey) === entry) {
|
|
3465
|
+
this.toolLedgerCacheEstimatedBytes += delta.estimatedBytes;
|
|
3466
|
+
this.toolLedgerCacheEventCount += delta.eventCount;
|
|
2807
3467
|
}
|
|
2808
3468
|
}
|
|
2809
|
-
|
|
2810
|
-
const
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
SELECT event_id, session_id, invocation_id, run_id, turn_id, payload_json
|
|
2815
|
-
FROM runtime_events
|
|
2816
|
-
ORDER BY invocation_id ASC, event_seq ASC, event_id ASC
|
|
2817
|
-
`)
|
|
2818
|
-
.all();
|
|
2819
|
-
const scan = scanToolLedger(rows.map(decodeRuntimeEventStorageRow));
|
|
2820
|
-
this.toolLedgerHealth = { dataVersion, issue: scan.issues[0] };
|
|
3469
|
+
restoreToolLedgerCacheEntry(state) {
|
|
3470
|
+
const entry = state.entry;
|
|
3471
|
+
if (entry.cacheKey && this.toolLedgerCache.get(entry.cacheKey) === entry) {
|
|
3472
|
+
this.toolLedgerCacheEstimatedBytes += state.estimatedBytesBefore - entry.estimatedBytes;
|
|
3473
|
+
this.toolLedgerCacheEventCount += state.eventCountBefore - entry.eventCount;
|
|
2821
3474
|
}
|
|
2822
|
-
|
|
2823
|
-
|
|
3475
|
+
entry.estimatedBytes = state.estimatedBytesBefore;
|
|
3476
|
+
entry.eventCount = state.eventCountBefore;
|
|
3477
|
+
}
|
|
3478
|
+
deleteToolLedgerCacheEntry(key, reason) {
|
|
3479
|
+
const entry = this.toolLedgerCache.get(key);
|
|
3480
|
+
if (!entry)
|
|
3481
|
+
return;
|
|
3482
|
+
this.toolLedgerCache.delete(key);
|
|
3483
|
+
if (entry.cacheKey === key)
|
|
3484
|
+
entry.cacheKey = undefined;
|
|
3485
|
+
this.toolLedgerCacheEstimatedBytes -= entry.estimatedBytes;
|
|
3486
|
+
this.toolLedgerCacheEventCount -= entry.eventCount;
|
|
3487
|
+
if (reason === 'budget')
|
|
3488
|
+
this.toolLedgerCacheMetrics.budgetEvictions += 1;
|
|
3489
|
+
if (reason === 'terminal')
|
|
3490
|
+
this.toolLedgerCacheMetrics.terminalEvictions += 1;
|
|
3491
|
+
}
|
|
3492
|
+
clearToolLedgerCache() {
|
|
3493
|
+
for (const entry of this.toolLedgerCache.values())
|
|
3494
|
+
entry.cacheKey = undefined;
|
|
3495
|
+
this.toolLedgerCache.clear();
|
|
3496
|
+
this.toolLedgerCacheEstimatedBytes = 0;
|
|
3497
|
+
this.toolLedgerCacheEventCount = 0;
|
|
3498
|
+
}
|
|
3499
|
+
invalidateToolLedgerCacheForInvocation(invocationId) {
|
|
3500
|
+
for (const [key, entry] of this.toolLedgerCache) {
|
|
3501
|
+
if (entry.invocationIds.has(invocationId)) {
|
|
3502
|
+
this.deleteToolLedgerCacheEntry(key, 'terminal');
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
toolLedgerEntryExceedsAdmissionBudget(entry) {
|
|
3507
|
+
return entry.estimatedBytes > this.toolLedgerCacheBudget.maxSingleEntryEstimatedBytes;
|
|
3508
|
+
}
|
|
3509
|
+
toolLedgerCacheExceedsBudget() {
|
|
3510
|
+
return (this.toolLedgerCache.size > this.toolLedgerCacheBudget.maxEntries ||
|
|
3511
|
+
this.toolLedgerCacheEstimatedBytes > this.toolLedgerCacheBudget.maxEstimatedBytes);
|
|
3512
|
+
}
|
|
3513
|
+
trimToolLedgerCache() {
|
|
3514
|
+
for (;;) {
|
|
3515
|
+
let victim;
|
|
3516
|
+
for (const [key, entry] of this.toolLedgerCache) {
|
|
3517
|
+
if (this.uncommittedToolLedgerStates.has(entry.reducer))
|
|
3518
|
+
continue;
|
|
3519
|
+
if (this.toolLedgerEntryExceedsAdmissionBudget(entry)) {
|
|
3520
|
+
victim = key;
|
|
3521
|
+
break;
|
|
3522
|
+
}
|
|
3523
|
+
}
|
|
3524
|
+
if (!victim && this.toolLedgerCacheExceedsBudget()) {
|
|
3525
|
+
victim = [...this.toolLedgerCache].find(([, entry]) => !this.uncommittedToolLedgerStates.has(entry.reducer))?.[0];
|
|
3526
|
+
}
|
|
3527
|
+
if (!victim)
|
|
3528
|
+
return;
|
|
3529
|
+
this.deleteToolLedgerCacheEntry(victim, 'budget');
|
|
2824
3530
|
}
|
|
2825
3531
|
}
|
|
3532
|
+
currentToolLedgerCacheVersion() {
|
|
3533
|
+
return `${this.runtimeDataVersion()}:${this.databaseLease?.writeViewRevision() ?? this.localCommittedWriteRevision}`;
|
|
3534
|
+
}
|
|
2826
3535
|
runtimeDataVersion() {
|
|
2827
3536
|
const row = this.db.prepare('PRAGMA data_version').get();
|
|
2828
3537
|
return row.data_version;
|
|
@@ -2942,7 +3651,7 @@ export class SqliteRuntimeStore {
|
|
|
2942
3651
|
throw new RunSealedError(event.runId);
|
|
2943
3652
|
}
|
|
2944
3653
|
}
|
|
2945
|
-
importRuntimeEventSync(event) {
|
|
3654
|
+
importRuntimeEventSync(event, allowLegacyTerminalWithUnsettledOperation = false) {
|
|
2946
3655
|
const canonicalEvent = canonicalizeRuntimeEventForStorage(event);
|
|
2947
3656
|
this.assertInvocationIdentity([canonicalEvent]);
|
|
2948
3657
|
const partial = partialRuntimeStream(canonicalEvent);
|
|
@@ -2961,6 +3670,21 @@ export class SqliteRuntimeStore {
|
|
|
2961
3670
|
// consult either.
|
|
2962
3671
|
if (!existing) {
|
|
2963
3672
|
this.assertContinuationAuthorityAllowsEvent(canonicalEvent);
|
|
3673
|
+
if (isTerminalRuntimeEvent(canonicalEvent) && !allowLegacyTerminalWithUnsettledOperation) {
|
|
3674
|
+
const unresolved = this.db
|
|
3675
|
+
.prepare(`
|
|
3676
|
+
SELECT operation_id FROM tool_operations
|
|
3677
|
+
WHERE invocation_id = ?
|
|
3678
|
+
AND current_state = 'prepared'
|
|
3679
|
+
AND result_event_id IS NULL
|
|
3680
|
+
AND dispatch_event_id IS NOT NULL
|
|
3681
|
+
LIMIT 1
|
|
3682
|
+
`)
|
|
3683
|
+
.get(canonicalEvent.invocationId);
|
|
3684
|
+
if (unresolved && typeof unresolved.operation_id === 'string') {
|
|
3685
|
+
throw new Error(`Cannot terminalize invocation ${canonicalEvent.invocationId} with unsettled tool operation ${unresolved.operation_id}`);
|
|
3686
|
+
}
|
|
3687
|
+
}
|
|
2964
3688
|
this.assertRunNotSealed(canonicalEvent);
|
|
2965
3689
|
}
|
|
2966
3690
|
if (isToolLedgerBearingEvent(canonicalEvent)) {
|
|
@@ -3005,21 +3729,28 @@ export class SqliteRuntimeStore {
|
|
|
3005
3729
|
const messageId = immutableSteeringMessageId(event);
|
|
3006
3730
|
if (!messageId)
|
|
3007
3731
|
return;
|
|
3008
|
-
const matches = this.
|
|
3732
|
+
const matches = this.readImmutableSteeringMessageEvents(event.sessionId, messageId);
|
|
3009
3733
|
if (matches.some((candidate) => !isDeepStrictEqual(candidate, event))) {
|
|
3010
3734
|
throw new Error(`Immutable steering message identity conflict: ${messageId}`);
|
|
3011
3735
|
}
|
|
3012
3736
|
}
|
|
3013
|
-
|
|
3737
|
+
readImmutableSteeringMessageEvents(sessionId, messageId) {
|
|
3014
3738
|
const rows = this.db
|
|
3015
3739
|
.prepare(`
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3740
|
+
SELECT event_id, session_id, invocation_id, run_id, turn_id, payload_json
|
|
3741
|
+
FROM runtime_events
|
|
3742
|
+
WHERE session_id = ?
|
|
3743
|
+
AND ${IMMUTABLE_STEERING_SQL_PREDICATE}
|
|
3744
|
+
AND CASE
|
|
3745
|
+
WHEN json_valid(payload_json)
|
|
3746
|
+
THEN json_extract(payload_json, '$.refs.providerEventId')
|
|
3747
|
+
END = ?
|
|
3748
|
+
ORDER BY committed_at ASC, event_id ASC
|
|
3749
|
+
`)
|
|
3750
|
+
.all(sessionId, messageId);
|
|
3751
|
+
return rows
|
|
3752
|
+
.map(decodeRuntimeEventStorageRow)
|
|
3753
|
+
.filter((event) => immutableSteeringMessageId(event) === messageId);
|
|
3023
3754
|
}
|
|
3024
3755
|
insertRuntimeEvent(event, committedAt, allowExactDuplicate, authorizedPendingContinuationClaimId) {
|
|
3025
3756
|
const encoding = encodeCanonicalRuntimeEvent(event);
|
|
@@ -3035,6 +3766,9 @@ export class SqliteRuntimeStore {
|
|
|
3035
3766
|
if (!allowExactDuplicate) {
|
|
3036
3767
|
throw new Error(`RuntimeEvent ${canonicalEvent.id} already exists outside this tool transaction`);
|
|
3037
3768
|
}
|
|
3769
|
+
if (isTerminalRuntimeEvent(canonicalEvent)) {
|
|
3770
|
+
this.invalidateToolLedgerCacheForInvocation(canonicalEvent.invocationId);
|
|
3771
|
+
}
|
|
3038
3772
|
return this.runtimeEventSeq(canonicalEvent.id);
|
|
3039
3773
|
}
|
|
3040
3774
|
this.assertContinuationAuthorityAllowsEvent(canonicalEvent, authorizedPendingContinuationClaimId);
|
|
@@ -3068,6 +3802,9 @@ export class SqliteRuntimeStore {
|
|
|
3068
3802
|
recordTranscriptTurnExtent(this.db, { ...canonicalEvent, kind: runtimeEventKind(canonicalEvent) }, ordinal);
|
|
3069
3803
|
this.noteEventCommit(canonicalEvent.sessionId);
|
|
3070
3804
|
this.deleteCompletedPartialSnapshot(canonicalEvent);
|
|
3805
|
+
if (isTerminalRuntimeEvent(canonicalEvent)) {
|
|
3806
|
+
this.invalidateToolLedgerCacheForInvocation(canonicalEvent.invocationId);
|
|
3807
|
+
}
|
|
3071
3808
|
return next;
|
|
3072
3809
|
}
|
|
3073
3810
|
deleteCompletedPartialSnapshot(event) {
|
|
@@ -3320,8 +4057,16 @@ function requireRuntimeEventOrder(eventOrder, eventId) {
|
|
|
3320
4057
|
throw new Error(`Missing RuntimeEvent order for ${eventId}`);
|
|
3321
4058
|
return order;
|
|
3322
4059
|
}
|
|
3323
|
-
function journalEventIdFor(operationId,
|
|
3324
|
-
|
|
4060
|
+
function journalEventIdFor(operationId, eventId, state) {
|
|
4061
|
+
if (state === 'outcome_committed')
|
|
4062
|
+
return `${operationId}_outcome`;
|
|
4063
|
+
if (state === 'abandoned' || state === 'interrupted_unknown') {
|
|
4064
|
+
// One invocation terminal can close multiple tool operations. Its journal
|
|
4065
|
+
// fact is therefore unique per operation, unlike per-operation recovery
|
|
4066
|
+
// events whose RuntimeEvent ids are already distinct.
|
|
4067
|
+
return `${operationId}_${eventId}_journal`;
|
|
4068
|
+
}
|
|
4069
|
+
return `${eventId}_journal`;
|
|
3325
4070
|
}
|
|
3326
4071
|
function assertRecoveryAuthorityCapability(db) {
|
|
3327
4072
|
const row = db
|
|
@@ -3348,6 +4093,19 @@ function assertRuntimeStorageSafeId(value, message) {
|
|
|
3348
4093
|
if (!isRuntimeStorageSafeId(value))
|
|
3349
4094
|
throw new Error(message);
|
|
3350
4095
|
}
|
|
4096
|
+
function distinctSafeRuntimeIds(values, message) {
|
|
4097
|
+
const result = new Set();
|
|
4098
|
+
for (const value of values) {
|
|
4099
|
+
assertRuntimeStorageSafeId(value, message);
|
|
4100
|
+
result.add(value);
|
|
4101
|
+
}
|
|
4102
|
+
return [...result];
|
|
4103
|
+
}
|
|
4104
|
+
function* batches(values, size) {
|
|
4105
|
+
for (let offset = 0; offset < values.length; offset += size) {
|
|
4106
|
+
yield values.slice(offset, offset + size);
|
|
4107
|
+
}
|
|
4108
|
+
}
|
|
3351
4109
|
function assertInvocationSearchLimit(limit) {
|
|
3352
4110
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 256) {
|
|
3353
4111
|
throw new RangeError('Runtime invocation search limit must be an integer between 1 and 256');
|