maka-agent 0.2.0-dev.32.20260914 → 0.2.0-dev.35.20260915
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/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
- package/node_modules/@maka/eval/dist/metering-checkpoint.js +4 -4
- package/node_modules/@maka/eval/harbor/relay_agent.py +1 -2
- package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +2 -18
- package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +1 -2
- package/node_modules/@maka/runtime/dist/provider-error-classification.js +29 -38
- package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +4 -1
- package/node_modules/@maka/runtime-host/dist/client/wait-for-ready.js +1 -1
- package/node_modules/@maka/runtime-host/dist/control/endpoint.js +7 -6
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +2 -2
- package/node_modules/@maka/runtime-host/dist/server/workhub-message-attachments.js +1 -0
- package/node_modules/@maka/storage/dist/agent-run-store-contract.js +942 -0
- package/node_modules/@maka/storage/dist/agent-run-store.js +3 -923
- package/node_modules/@maka/storage/dist/artifact-store.js +63 -7
- package/node_modules/@maka/storage/dist/execution-persistence-provider.js +54 -0
- package/node_modules/@maka/storage/dist/execution-stores.js +181 -58
- package/node_modules/@maka/storage/dist/goal-authority.js +39 -8
- package/node_modules/@maka/storage/dist/graph-control-values.js +126 -0
- package/node_modules/@maka/storage/dist/interaction-store-contract.js +231 -0
- package/node_modules/@maka/storage/dist/interaction-store.js +62 -217
- package/node_modules/@maka/storage/dist/local-execution-persistence.js +80 -0
- package/node_modules/@maka/storage/dist/root-authority.js +4 -0
- package/node_modules/@maka/storage/dist/runtime-event-store-contract.js +19 -0
- package/node_modules/@maka/storage/dist/runtime-partial-values.js +114 -0
- package/node_modules/@maka/storage/dist/session-store-contract.js +61 -0
- package/node_modules/@maka/storage/dist/session-store-values.js +342 -0
- package/node_modules/@maka/storage/dist/session-store.js +7 -351
- package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +4 -185
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +9 -129
- package/node_modules/@maka/storage/dist/storage-writer-composition.js +2 -3
- package/node_modules/@maka/storage/dist/tool-commit-validation.js +111 -0
- package/node_modules/@maka/storage/package.json +1 -0
- package/package.json +1 -1
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* under the License.
|
|
18
18
|
*/
|
|
19
19
|
import { createHash, randomUUID } from 'node:crypto';
|
|
20
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
20
21
|
import { constants as fsConstants } from 'node:fs';
|
|
21
22
|
import { access, copyFile, lstat, mkdir, open, readFile, realpath, rm, stat, unlink, writeFile, } from 'node:fs/promises';
|
|
22
23
|
import { basename, dirname, join, relative, sep } from 'node:path';
|
|
@@ -172,13 +173,13 @@ class SqliteArtifactStore {
|
|
|
172
173
|
if (!prepared.ok) {
|
|
173
174
|
throw new Error(`Artifact ${record.id} could not be copied: ${prepared.reason}`);
|
|
174
175
|
}
|
|
175
|
-
const created = await this.copyConversationArtifact(prepared, input.targetSessionId, targetId);
|
|
176
|
+
const created = await this.copyConversationArtifact(prepared, input.targetSessionId, targetId, input.existingTarget === 'reuse_verified');
|
|
176
177
|
artifactIds.set(record.id, created.id);
|
|
177
178
|
relativePaths.set(record.relativePath, created.relativePath);
|
|
178
179
|
}
|
|
179
180
|
return { artifactIds, relativePaths };
|
|
180
181
|
}
|
|
181
|
-
copyConversationArtifact(prepared, targetSessionId, targetId) {
|
|
182
|
+
copyConversationArtifact(prepared, targetSessionId, targetId, reuseVerified) {
|
|
182
183
|
const source = prepared.record;
|
|
183
184
|
const name = sanitizeArtifactName(source.name);
|
|
184
185
|
const relativePath = `${targetSessionId}/${targetId}-${name}`;
|
|
@@ -186,16 +187,36 @@ class SqliteArtifactStore {
|
|
|
186
187
|
validateRelativeArtifactPath(relativePath);
|
|
187
188
|
return this.enqueueMutation(async () => {
|
|
188
189
|
await this.prepareMutationUnlocked();
|
|
189
|
-
|
|
190
|
-
throw new Error(`Artifact target already exists: ${targetId}`);
|
|
191
|
-
}
|
|
192
|
-
return this.publishNewArtifactUnlocked({
|
|
190
|
+
const expected = {
|
|
193
191
|
...source,
|
|
194
192
|
id: targetId,
|
|
195
193
|
sessionId: targetSessionId,
|
|
196
194
|
name,
|
|
197
195
|
relativePath,
|
|
198
|
-
}
|
|
196
|
+
};
|
|
197
|
+
const existing = this.records.find((record) => record.id === targetId);
|
|
198
|
+
if (existing) {
|
|
199
|
+
if (!reuseVerified)
|
|
200
|
+
throw new Error(`Artifact target already exists: ${targetId}`);
|
|
201
|
+
// Recheck the source after acquiring the writer lock, not just the
|
|
202
|
+
// selection made before it. Validation and reuse cannot race another
|
|
203
|
+
// Artifact writer's removal/replacement of either record or payload.
|
|
204
|
+
const currentSource = this.records.find((record) => record.id === source.id);
|
|
205
|
+
if (!isDeepStrictEqual(currentSource, source) || !isDeepStrictEqual(existing, expected)) {
|
|
206
|
+
throw artifactReplayConflict(targetId);
|
|
207
|
+
}
|
|
208
|
+
const sourceRead = await this.prepareRecordRead(source, source.sizeBytes);
|
|
209
|
+
const targetRead = await this.prepareRecordRead(existing, existing.sizeBytes);
|
|
210
|
+
if (!sourceRead.ok || !targetRead.ok)
|
|
211
|
+
throw artifactReplayConflict(targetId);
|
|
212
|
+
const sourceDigest = await hashPreparedArtifact(sourceRead);
|
|
213
|
+
const targetDigest = await hashPreparedArtifact(targetRead);
|
|
214
|
+
if (sourceDigest === undefined || sourceDigest !== targetDigest) {
|
|
215
|
+
throw artifactReplayConflict(targetId);
|
|
216
|
+
}
|
|
217
|
+
return { ...existing };
|
|
218
|
+
}
|
|
219
|
+
return this.publishNewArtifactUnlocked(expected, (targetPath) => copyFile(prepared.path, targetPath, fsConstants.COPYFILE_EXCL), source.sizeBytes);
|
|
199
220
|
});
|
|
200
221
|
}
|
|
201
222
|
async publishNewArtifactUnlocked(draft, writeTarget, expectedSize) {
|
|
@@ -645,6 +666,41 @@ async function openRealTarget(path) {
|
|
|
645
666
|
return open(path, fsConstants.O_RDONLY);
|
|
646
667
|
}
|
|
647
668
|
}
|
|
669
|
+
/** Bounded-memory verification of an exact stored payload, including its size. */
|
|
670
|
+
async function hashPreparedArtifact(prepared) {
|
|
671
|
+
let handle;
|
|
672
|
+
try {
|
|
673
|
+
handle = await openRealTarget(prepared.path);
|
|
674
|
+
const before = await handle.stat({ bigint: true });
|
|
675
|
+
if (!before.isFile() || before.size !== BigInt(prepared.record.sizeBytes))
|
|
676
|
+
return undefined;
|
|
677
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
678
|
+
const hash = createHash('sha256');
|
|
679
|
+
let total = 0;
|
|
680
|
+
while (true) {
|
|
681
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, total);
|
|
682
|
+
if (bytesRead === 0)
|
|
683
|
+
break;
|
|
684
|
+
total += bytesRead;
|
|
685
|
+
if (total > prepared.record.sizeBytes)
|
|
686
|
+
return undefined;
|
|
687
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
688
|
+
}
|
|
689
|
+
const after = await handle.stat({ bigint: true });
|
|
690
|
+
if (total !== prepared.record.sizeBytes ||
|
|
691
|
+
before.size !== after.size ||
|
|
692
|
+
before.mtimeNs !== after.mtimeNs ||
|
|
693
|
+
before.ctimeNs !== after.ctimeNs)
|
|
694
|
+
return undefined;
|
|
695
|
+
return hash.digest('hex');
|
|
696
|
+
}
|
|
697
|
+
catch {
|
|
698
|
+
return undefined;
|
|
699
|
+
}
|
|
700
|
+
finally {
|
|
701
|
+
await handle?.close();
|
|
702
|
+
}
|
|
703
|
+
}
|
|
648
704
|
async function readPreparedBytes(prepared) {
|
|
649
705
|
let handle;
|
|
650
706
|
try {
|
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
/** Explicit allowlist: the graph facade must not expose adapter SQL/backup methods. */
|
|
20
|
+
export const EXECUTION_GRAPH_METHODS = [
|
|
21
|
+
'claimAgentGraphIntent',
|
|
22
|
+
'readAgentGraphIntentClaim',
|
|
23
|
+
'listAgentGraphIntentClaims',
|
|
24
|
+
'commitAgentGraphScheduleUpdate',
|
|
25
|
+
'listAgentGraphScheduleUpdates',
|
|
26
|
+
'claimAgentGraphIntentAtScheduleRevision',
|
|
27
|
+
'beginAgentGraphIntentExecutionAtScheduleRevision',
|
|
28
|
+
'cancelAgentGraphIntentExecution',
|
|
29
|
+
'listAgentGraphOperatorProvisions',
|
|
30
|
+
'resolveCurrentAgentGraphEpoch',
|
|
31
|
+
'advanceAgentGraphEpoch',
|
|
32
|
+
'readAgentGraphEpochByGraphId',
|
|
33
|
+
'listAgentGraphEpochPage',
|
|
34
|
+
'listAgentGraphEpochs',
|
|
35
|
+
'claimAgentGraphSupervisorWake',
|
|
36
|
+
'beginAgentGraphSupervisorWakeAttempt',
|
|
37
|
+
'completeAgentGraphSupervisorWakeAttempt',
|
|
38
|
+
'supersedeAgentGraphSupervisorWakes',
|
|
39
|
+
'readAgentGraphSupervisorWake',
|
|
40
|
+
'listAgentGraphSupervisorWakeAttempts',
|
|
41
|
+
'listUnsettledAgentGraphSupervisorWakes',
|
|
42
|
+
'listRetryableAgentGraphSupervisorWakes',
|
|
43
|
+
'recoverAgentGraphSupervisorWakes',
|
|
44
|
+
'commitAgentGraphClientProjection',
|
|
45
|
+
'readAgentGraphClientProjection',
|
|
46
|
+
'readAgentGraphClientOperatorProjection',
|
|
47
|
+
'readAgentGraphClientProjectionWithOperator',
|
|
48
|
+
'listAgentGraphClientTerminalActivities',
|
|
49
|
+
'listAgentGraphClientClaimAdmissions',
|
|
50
|
+
'readAgentGraphTimelineMetadata',
|
|
51
|
+
'listTombstonedSessionIdsAmong',
|
|
52
|
+
'purgeAgentGraphControlState',
|
|
53
|
+
'purgeAgentGraphEpochs',
|
|
54
|
+
];
|
|
@@ -17,11 +17,15 @@
|
|
|
17
17
|
* under the License.
|
|
18
18
|
*/
|
|
19
19
|
import { createSqliteAgentRunStore, } from './agent-run-store.js';
|
|
20
|
-
import { createConversationOperationalStateStore, } from './conversation-operational-state.js';
|
|
21
20
|
import { createSessionStore } from './session-store.js';
|
|
22
|
-
import { assertStorageRootLease, runWithStorageRootLease, StorageRootAuthorityError, } from './root-authority.js';
|
|
23
|
-
import { closeSqliteInteractionStoreFacade, openSqliteInteractiveInteractionStoreForRead, openSqliteInteractiveInteractionStoreForWrite, } from './interaction-store.js';
|
|
24
|
-
import {
|
|
21
|
+
import { assertStorageRootLease, assertStorageRootLeaseActive, runWithStorageRootLease, StorageRootAuthorityError, } from './root-authority.js';
|
|
22
|
+
import { closeSqliteInteractionStoreFacade, openSqliteInteractiveInteractionStoreForRead, openSqliteInteractiveInteractionStoreForWrite, createSqliteInteractionStore, } from './interaction-store.js';
|
|
23
|
+
import { openRuntimeEventReadPersistence } from './runtime-event-persistence.js';
|
|
24
|
+
import { localExecutionPersistenceProvider } from './local-execution-persistence.js';
|
|
25
|
+
import { EXECUTION_GRAPH_METHODS, } from './execution-persistence-provider.js';
|
|
26
|
+
import { openInteractiveGoalAuthorityForWrite, createSqliteGoalAuthority, } from './goal-authority.js';
|
|
27
|
+
const executionStoreProvidersByLease = new WeakMap();
|
|
28
|
+
const failedExecutionLeases = new WeakSet();
|
|
25
29
|
const executionStoresWriterBrand = Symbol('ExecutionStoresWriter');
|
|
26
30
|
const executionStoresReaderBrand = Symbol('ExecutionStoresReader');
|
|
27
31
|
const executionStoresWriterKinds = new WeakMap();
|
|
@@ -29,8 +33,8 @@ const executionStoresReaderKinds = new WeakMap();
|
|
|
29
33
|
const executionStoresWritersByLease = new WeakMap();
|
|
30
34
|
const executionStoresWritersOpeningByLease = new WeakMap();
|
|
31
35
|
export { normalizeRootTurnAdmissionPayload, rootTurnAdmissionRecordFits, } from './agent-run-store.js';
|
|
32
|
-
export { isSessionNotFoundError } from './session-store.js';
|
|
33
|
-
export { SessionMetadataConflictError, SessionMetadataVersionConflictError, } from './
|
|
36
|
+
export { isSessionNotFoundError } from './session-store-contract.js';
|
|
37
|
+
export { SessionMetadataConflictError, SessionMetadataVersionConflictError, } from './session-store-contract.js';
|
|
34
38
|
export { submittedTurnIntentsEqual } from './submitted-turn-intent.js';
|
|
35
39
|
export function authenticateExecutionStoresWriter(stores, expectedKind) {
|
|
36
40
|
if (executionStoresWriterKinds.get(stores) !== expectedKind) {
|
|
@@ -44,74 +48,189 @@ export function authenticateExecutionStoresReader(stores, expectedKind) {
|
|
|
44
48
|
}
|
|
45
49
|
return stores;
|
|
46
50
|
}
|
|
47
|
-
export async function openInteractiveExecutionStoresForWrite(lease) {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
51
|
+
export async function openInteractiveExecutionStoresForWrite(lease, provider = localExecutionPersistenceProvider) {
|
|
52
|
+
await assertStorageRootLease(lease, 'interactive', 'write');
|
|
53
|
+
if (failedExecutionLeases.has(lease)) {
|
|
54
|
+
throw new StorageRootAuthorityError('invalid_lease', 'Execution persistence requires a fresh owner after an uncertain open or close');
|
|
55
|
+
}
|
|
56
|
+
const selected = executionStoreProvidersByLease.get(lease);
|
|
57
|
+
if (selected && selected !== provider) {
|
|
58
|
+
throw new StorageRootAuthorityError('invalid_lease', 'A different execution provider already owns this lease');
|
|
59
|
+
}
|
|
55
60
|
const existing = executionStoresWritersByLease.get(lease);
|
|
56
|
-
if (existing)
|
|
61
|
+
if (existing) {
|
|
62
|
+
if (executionStoresWriterKinds.get(existing) !== 'interactive')
|
|
63
|
+
throw invalidExecutionStores('interactive', 'write');
|
|
57
64
|
return existing;
|
|
65
|
+
}
|
|
58
66
|
const opening = executionStoresWritersOpeningByLease.get(lease);
|
|
59
67
|
if (opening) {
|
|
60
68
|
await opening;
|
|
61
|
-
return
|
|
69
|
+
return openInteractiveExecutionStoresForWrite(lease, provider);
|
|
62
70
|
}
|
|
71
|
+
executionStoreProvidersByLease.set(lease, provider);
|
|
63
72
|
let releaseOpening;
|
|
64
73
|
const openingGate = new Promise((resolve) => {
|
|
65
74
|
releaseOpening = resolve;
|
|
66
75
|
});
|
|
67
76
|
executionStoresWritersOpeningByLease.set(lease, openingGate);
|
|
68
77
|
try {
|
|
69
|
-
return await createExecutionStoresForWrite(lease,
|
|
78
|
+
return await createExecutionStoresForWrite(lease, provider);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (!executionStoresWritersByLease.has(lease) && !failedExecutionLeases.has(lease))
|
|
82
|
+
executionStoreProvidersByLease.delete(lease);
|
|
83
|
+
throw error;
|
|
70
84
|
}
|
|
71
85
|
finally {
|
|
72
86
|
executionStoresWritersOpeningByLease.delete(lease);
|
|
73
87
|
releaseOpening();
|
|
74
88
|
}
|
|
75
89
|
}
|
|
76
|
-
async function createExecutionStoresForWrite(lease,
|
|
77
|
-
const
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
await sessionStore.close?.().catch(() => { });
|
|
86
|
-
agentRunStore.close?.();
|
|
87
|
-
if (interactionStore)
|
|
88
|
-
closeSqliteInteractionStoreFacade(interactionStore);
|
|
90
|
+
async function createExecutionStoresForWrite(lease, provider) {
|
|
91
|
+
const kind = 'interactive';
|
|
92
|
+
const persistence = await runWithStorageRootLease(lease, kind, 'write', () => provider.open({
|
|
93
|
+
rootId: lease.rootId,
|
|
94
|
+
canonicalPath: lease.canonicalPath,
|
|
95
|
+
})).catch((error) => {
|
|
96
|
+
// An unsuccessful factory must clean up its own partial handles. Until a
|
|
97
|
+
// fresh owner is acquired, do not assume an unknown factory failure did so.
|
|
98
|
+
failedExecutionLeases.add(lease);
|
|
89
99
|
throw error;
|
|
90
100
|
});
|
|
91
|
-
|
|
92
|
-
let
|
|
101
|
+
let closed = false;
|
|
102
|
+
let closeTask;
|
|
103
|
+
const active = new Set();
|
|
104
|
+
const subscriptions = new Set();
|
|
105
|
+
const run = (operation) => {
|
|
106
|
+
if (closed)
|
|
107
|
+
return Promise.reject(invalidExecutionStores(kind, 'write'));
|
|
108
|
+
const pending = runWithStorageRootLease(lease, kind, 'write', () => {
|
|
109
|
+
if (closed)
|
|
110
|
+
throw invalidExecutionStores(kind, 'write');
|
|
111
|
+
return operation();
|
|
112
|
+
});
|
|
113
|
+
active.add(pending);
|
|
114
|
+
void pending.finally(() => active.delete(pending)).catch(() => undefined);
|
|
115
|
+
return pending;
|
|
116
|
+
};
|
|
117
|
+
const sessionStore = persistence.sessionStore;
|
|
118
|
+
const agentRunStore = persistence.agentRunStore;
|
|
119
|
+
const runtimeEventStore = persistence.runtimeEventStore;
|
|
120
|
+
const runtimePersistence = { runtimeCommitStore: runtimeEventStore };
|
|
121
|
+
const conversationOperationalStateStore = {
|
|
122
|
+
purge: (sessionId) => persistence.purgeConversationOperationalState(sessionId),
|
|
123
|
+
};
|
|
124
|
+
let interactionStore;
|
|
125
|
+
let goalStore;
|
|
126
|
+
const releaseChildBindings = [];
|
|
127
|
+
const retainUntilGroupClose = (release) => releaseChildBindings.push(release);
|
|
93
128
|
try {
|
|
94
|
-
|
|
129
|
+
await assertStorageRootLease(lease, kind, 'write');
|
|
130
|
+
await sessionStore.ready();
|
|
131
|
+
await agentRunStore.ready?.();
|
|
132
|
+
interactionStore = await openSqliteInteractiveInteractionStoreForWrite(lease, () => new Proxy(persistence.interactionStore, {
|
|
133
|
+
get(target, property, receiver) {
|
|
134
|
+
if (property === 'close')
|
|
135
|
+
return () => { };
|
|
136
|
+
const value = Reflect.get(target, property, receiver);
|
|
137
|
+
return typeof value === 'function'
|
|
138
|
+
? (...args) => run(async () => Reflect.apply(value, target, args))
|
|
139
|
+
: value;
|
|
140
|
+
},
|
|
141
|
+
}), provider === localExecutionPersistenceProvider ? createSqliteInteractionStore : provider, retainUntilGroupClose);
|
|
142
|
+
goalStore = await openInteractiveGoalAuthorityForWrite(lease, () => ({
|
|
143
|
+
list: () => run(async () => persistence.goalStore.list()),
|
|
144
|
+
read: (sessionId) => run(async () => persistence.goalStore.read(sessionId)),
|
|
145
|
+
commit: (input) => run(async () => persistence.goalStore.commit(input)),
|
|
146
|
+
// The group owns the backend handle; closing this facade only revokes it.
|
|
147
|
+
close: () => { },
|
|
148
|
+
}), provider === localExecutionPersistenceProvider ? createSqliteGoalAuthority : provider, retainUntilGroupClose);
|
|
95
149
|
}
|
|
96
150
|
catch (error) {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
151
|
+
closed = true;
|
|
152
|
+
const failures = [error];
|
|
153
|
+
try {
|
|
154
|
+
if (interactionStore)
|
|
155
|
+
closeSqliteInteractionStoreFacade(interactionStore);
|
|
156
|
+
}
|
|
157
|
+
catch (closeError) {
|
|
158
|
+
failures.push(closeError);
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
await goalStore?.close();
|
|
162
|
+
}
|
|
163
|
+
catch (closeError) {
|
|
164
|
+
failures.push(closeError);
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
await persistence.close();
|
|
168
|
+
}
|
|
169
|
+
catch (closeError) {
|
|
170
|
+
failures.push(closeError);
|
|
171
|
+
}
|
|
172
|
+
if (failures.length > 1) {
|
|
173
|
+
failedExecutionLeases.add(lease);
|
|
174
|
+
throw new AggregateError(failures, 'Unable to compose execution persistence');
|
|
175
|
+
}
|
|
176
|
+
for (const release of releaseChildBindings)
|
|
177
|
+
release();
|
|
101
178
|
throw error;
|
|
102
179
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
180
|
+
const close = () => (closeTask ??= (async () => {
|
|
181
|
+
closed = true;
|
|
182
|
+
executionStoresWriterKinds.delete(stores);
|
|
183
|
+
const errors = [];
|
|
184
|
+
for (const unsubscribe of subscriptions) {
|
|
185
|
+
try {
|
|
186
|
+
unsubscribe();
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
errors.push(error);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
subscriptions.clear();
|
|
193
|
+
await Promise.allSettled([...active]);
|
|
194
|
+
try {
|
|
195
|
+
await goalStore.close();
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
errors.push(error);
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
closeSqliteInteractionStoreFacade(interactionStore);
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
errors.push(error);
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
await persistence.close();
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
errors.push(error);
|
|
211
|
+
}
|
|
212
|
+
// Failed close retains the closed owner, so another backend cannot open over it.
|
|
213
|
+
if (errors.length)
|
|
214
|
+
throw new AggregateError(errors, 'Unable to close execution persistence');
|
|
215
|
+
for (const release of releaseChildBindings)
|
|
216
|
+
release();
|
|
217
|
+
if (executionStoresWritersByLease.get(lease) === stores) {
|
|
218
|
+
executionStoresWritersByLease.delete(lease);
|
|
219
|
+
executionStoreProvidersByLease.delete(lease);
|
|
220
|
+
}
|
|
221
|
+
})());
|
|
222
|
+
const graphMethods = Object.fromEntries(EXECUTION_GRAPH_METHODS.map((name) => [
|
|
223
|
+
name,
|
|
224
|
+
(...args) => run(() => Reflect.apply(persistence.graphControlStore[name], persistence.graphControlStore, args)),
|
|
225
|
+
]));
|
|
226
|
+
const graphControlStore = Object.freeze({
|
|
227
|
+
...graphMethods,
|
|
228
|
+
close: () => { },
|
|
110
229
|
});
|
|
111
|
-
const run = (operation) => runWithStorageRootLease(lease, kind, 'write', operation);
|
|
112
|
-
let closeTask;
|
|
113
230
|
const stores = {
|
|
114
|
-
|
|
231
|
+
interactionStore,
|
|
232
|
+
graphControlStore,
|
|
233
|
+
goalStore,
|
|
115
234
|
kind,
|
|
116
235
|
[executionStoresWriterBrand]: kind,
|
|
117
236
|
purgeConversationOperationalState: (sessionId) => run(() => conversationOperationalStateStore.purge(sessionId)),
|
|
@@ -174,7 +293,20 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
|
|
|
174
293
|
updateMessageAdmission: (admission) => run(() => sessionStore.updateMessageAdmission(admission)),
|
|
175
294
|
reorderMessageAdmissions: (sessionId, messageIds, disposition) => run(() => sessionStore.reorderMessageAdmissions(sessionId, messageIds, disposition)),
|
|
176
295
|
cancelMessageAdmissions: (sessionId, messageIds) => run(() => sessionStore.cancelMessageAdmissions(sessionId, messageIds)),
|
|
177
|
-
subscribeTranscriptChanges: (listener) =>
|
|
296
|
+
subscribeTranscriptChanges: (listener) => {
|
|
297
|
+
if (closed)
|
|
298
|
+
throw invalidExecutionStores(kind, 'write');
|
|
299
|
+
assertStorageRootLeaseActive(lease, kind, 'write');
|
|
300
|
+
const unsubscribe = sessionStore.subscribeTranscriptChanges((sessionId) => {
|
|
301
|
+
if (!closed)
|
|
302
|
+
listener(sessionId);
|
|
303
|
+
});
|
|
304
|
+
subscriptions.add(unsubscribe);
|
|
305
|
+
return () => {
|
|
306
|
+
subscriptions.delete(unsubscribe);
|
|
307
|
+
unsubscribe();
|
|
308
|
+
};
|
|
309
|
+
},
|
|
178
310
|
updateHeader: (sessionId, patch) => run(() => sessionStore.updateHeader(sessionId, patch)),
|
|
179
311
|
updateHeaderVersioned: (sessionId, patch, expectedRevision) => run(() => sessionStore.updateHeaderVersioned(sessionId, patch, expectedRevision)),
|
|
180
312
|
updateSessionConfiguration: (sessionId, input) => run(() => sessionStore.updateSessionConfiguration(sessionId, input)),
|
|
@@ -187,16 +319,7 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
|
|
|
187
319
|
reconcileOrphanedAgentGraphRetirements: () => run(() => sessionStore.reconcileOrphanedAgentGraphRetirements()),
|
|
188
320
|
listPendingSessionRetirementCleanupIds: (sessionId) => run(() => sessionStore.listPendingSessionRetirementCleanupIds(sessionId)),
|
|
189
321
|
completeSessionRetirementCleanup: (sessionId) => run(() => sessionStore.completeSessionRetirementCleanup(sessionId)),
|
|
190
|
-
close
|
|
191
|
-
if (executionStoresWritersByLease.get(lease) === stores) {
|
|
192
|
-
executionStoresWritersByLease.delete(lease);
|
|
193
|
-
}
|
|
194
|
-
await closeExecutionStorePersistence(sessionStore, runtimePersistence, {
|
|
195
|
-
agentRunStore,
|
|
196
|
-
conversationOperationalStateStore,
|
|
197
|
-
interactionStore,
|
|
198
|
-
});
|
|
199
|
-
})()),
|
|
322
|
+
close,
|
|
200
323
|
},
|
|
201
324
|
agentRunStore: {
|
|
202
325
|
appendEvent: (sessionId, runId, event, options) => run(() => agentRunStore.appendEvent(sessionId, runId, event, options)),
|
|
@@ -22,7 +22,10 @@ import { assertStorageRootLease, runWithStorageRootLease, StorageRootAuthorityEr
|
|
|
22
22
|
import { assertSafeStorageId } from './storage-id.js';
|
|
23
23
|
const writerBrand = Symbol('InteractiveGoalAuthorityWriter');
|
|
24
24
|
const writers = new WeakSet();
|
|
25
|
+
const successfullyClosedWriters = new WeakSet();
|
|
25
26
|
const writerByLease = new WeakMap();
|
|
27
|
+
const backendByLease = new WeakMap();
|
|
28
|
+
const retainedByExecution = new WeakSet();
|
|
26
29
|
const writerOpeningByLease = new WeakMap();
|
|
27
30
|
export function authenticateInteractiveGoalAuthorityWriter(writer) {
|
|
28
31
|
if (!writers.has(writer)) {
|
|
@@ -30,22 +33,46 @@ export function authenticateInteractiveGoalAuthorityWriter(writer) {
|
|
|
30
33
|
}
|
|
31
34
|
return writer;
|
|
32
35
|
}
|
|
33
|
-
export async function openInteractiveGoalAuthorityForWrite(lease) {
|
|
36
|
+
export async function openInteractiveGoalAuthorityForWrite(lease, repositoryFactory, backendIdentity = repositoryFactory ?? createSqliteGoalAuthority, retainUntilGroupClose) {
|
|
34
37
|
await assertStorageRootLease(lease, 'interactive', 'write');
|
|
38
|
+
// A child may revoke its facade, but only the successfully closed execution
|
|
39
|
+
// group may release its backend binding. Otherwise a legacy accessor could
|
|
40
|
+
// silently create a Local writer alongside a still-live non-Local group.
|
|
41
|
+
if (retainUntilGroupClose && !retainedByExecution.has(lease)) {
|
|
42
|
+
retainedByExecution.add(lease);
|
|
43
|
+
retainUntilGroupClose(() => {
|
|
44
|
+
retainedByExecution.delete(lease);
|
|
45
|
+
const cached = writerByLease.get(lease);
|
|
46
|
+
if (!cached || successfullyClosedWriters.has(cached)) {
|
|
47
|
+
writerByLease.delete(lease);
|
|
48
|
+
backendByLease.delete(lease);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
35
52
|
const existing = writerByLease.get(lease);
|
|
53
|
+
if ((existing && !writers.has(existing)) ||
|
|
54
|
+
(!existing && retainedByExecution.has(lease) && !retainUntilGroupClose)) {
|
|
55
|
+
throw new StorageRootAuthorityError('invalid_lease', 'Goal authority is owned by its execution group');
|
|
56
|
+
}
|
|
57
|
+
if (repositoryFactory &&
|
|
58
|
+
backendByLease.has(lease) &&
|
|
59
|
+
backendByLease.get(lease) !== backendIdentity) {
|
|
60
|
+
throw new StorageRootAuthorityError('invalid_lease', 'Goal authority is already composed for this lease');
|
|
61
|
+
}
|
|
36
62
|
if (existing)
|
|
37
63
|
return existing;
|
|
38
64
|
const opening = writerOpeningByLease.get(lease);
|
|
39
65
|
if (opening)
|
|
40
66
|
return opening;
|
|
67
|
+
backendByLease.set(lease, backendIdentity);
|
|
41
68
|
const pending = Promise.resolve().then(async () => {
|
|
42
69
|
let repository;
|
|
43
70
|
try {
|
|
44
|
-
repository = await runWithStorageRootLease(lease, 'interactive', 'write', async (root) => createSqliteGoalAuthority(root));
|
|
71
|
+
repository = await runWithStorageRootLease(lease, 'interactive', 'write', async (root) => (repositoryFactory ?? createSqliteGoalAuthority)(root));
|
|
45
72
|
await assertStorageRootLease(lease, 'interactive', 'write');
|
|
46
73
|
const raced = writerByLease.get(lease);
|
|
47
74
|
if (raced) {
|
|
48
|
-
repository.close();
|
|
75
|
+
await repository.close();
|
|
49
76
|
return raced;
|
|
50
77
|
}
|
|
51
78
|
const writer = createWriterFacade(lease, repository);
|
|
@@ -54,7 +81,8 @@ export async function openInteractiveGoalAuthorityForWrite(lease) {
|
|
|
54
81
|
return writer;
|
|
55
82
|
}
|
|
56
83
|
catch (error) {
|
|
57
|
-
repository?.close();
|
|
84
|
+
await repository?.close();
|
|
85
|
+
backendByLease.delete(lease);
|
|
58
86
|
throw error;
|
|
59
87
|
}
|
|
60
88
|
});
|
|
@@ -93,11 +121,14 @@ function createWriterFacade(lease, repository) {
|
|
|
93
121
|
close: () => {
|
|
94
122
|
closeTask ??= (async () => {
|
|
95
123
|
closed = true;
|
|
96
|
-
if (writerByLease.get(lease) === writer)
|
|
97
|
-
writerByLease.delete(lease);
|
|
98
124
|
writers.delete(writer);
|
|
99
125
|
await Promise.allSettled([...activeOperations]);
|
|
100
|
-
repository.close();
|
|
126
|
+
await repository.close();
|
|
127
|
+
successfullyClosedWriters.add(writer);
|
|
128
|
+
if (writerByLease.get(lease) === writer && !retainedByExecution.has(lease)) {
|
|
129
|
+
writerByLease.delete(lease);
|
|
130
|
+
backendByLease.delete(lease);
|
|
131
|
+
}
|
|
101
132
|
})();
|
|
102
133
|
return closeTask;
|
|
103
134
|
},
|
|
@@ -163,7 +194,7 @@ class SqliteGoalAuthority {
|
|
|
163
194
|
this.#database.close();
|
|
164
195
|
}
|
|
165
196
|
}
|
|
166
|
-
function createSqliteGoalAuthority(root) {
|
|
197
|
+
export function createSqliteGoalAuthority(root) {
|
|
167
198
|
return new SqliteGoalAuthority(root);
|
|
168
199
|
}
|
|
169
200
|
function normalizeCommitInput(input) {
|