maka-agent 0.2.0-dev.34.20260915 → 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/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
|
@@ -18,26 +18,18 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { resolve } from 'node:path';
|
|
20
20
|
import { isDeepStrictEqual } from 'node:util';
|
|
21
|
-
import { clientCapabilityScopeIdentity,
|
|
22
|
-
import { decodeInteractionCanonicalOutcome,
|
|
21
|
+
import { clientCapabilityScopeIdentity, } from '@maka/core/client-capability-grant';
|
|
22
|
+
import { decodeInteractionCanonicalOutcome, interactionCanonicalOutcomesEquivalent, isInteractionCanonicalOutcomeValidForRequest, } from '@maka/core/interaction';
|
|
23
23
|
import { assertStorageRootLease, runWithStorageRootLease, StorageRootAuthorityError, } from './root-authority.js';
|
|
24
24
|
import { acquireOperationalStateDatabase, } from './operational-state-store.js';
|
|
25
|
-
import {
|
|
26
|
-
|
|
27
|
-
export const STORED_INTERACTION_REQUEST_MAX_BYTES = 20 * 1024;
|
|
28
|
-
export const STORED_INTERACTION_OUTCOME_MAX_BYTES = 12 * 1024;
|
|
29
|
-
export const STORED_CLIENT_CAPABILITY_SESSION_GRANT_MAX_BYTES = 12 * 1024;
|
|
30
|
-
export class InteractionStoreError extends Error {
|
|
31
|
-
code;
|
|
32
|
-
constructor(code, message, options) {
|
|
33
|
-
super(message, options);
|
|
34
|
-
this.code = code;
|
|
35
|
-
this.name = 'InteractionStoreError';
|
|
36
|
-
}
|
|
37
|
-
}
|
|
25
|
+
import { STORED_INTERACTION_REQUEST_MAX_BYTES, STORED_INTERACTION_OUTCOME_MAX_BYTES, STORED_CLIENT_CAPABILITY_SESSION_GRANT_MAX_BYTES, InteractionStoreError, sameGrantAuthority, sortPending, normalizeRequest, normalizeOutcome, decodeGrant, decodeGrantKey, decodeClientCapabilityOutcome, identity, assertId, parseJsonRecord, decodeFailure, encode, failure, normalizeFilter, matches, deepFreeze, } from './interaction-store-contract.js';
|
|
26
|
+
export * from './interaction-store-contract.js';
|
|
38
27
|
const readers = new WeakSet();
|
|
39
28
|
const writers = new WeakSet();
|
|
29
|
+
const successfullyClosedWriters = new WeakSet();
|
|
40
30
|
const sqliteWritersByLease = new WeakMap();
|
|
31
|
+
const backendByLease = new WeakMap();
|
|
32
|
+
const retainedByExecution = new WeakSet();
|
|
41
33
|
const sqliteWriterOpeningsByLease = new WeakMap();
|
|
42
34
|
const sqliteFacadeClosers = new WeakMap();
|
|
43
35
|
export function authenticateInteractionStoreReader(store) {
|
|
@@ -67,18 +59,56 @@ export async function openSqliteInteractiveInteractionStoreForRead(lease) {
|
|
|
67
59
|
sqliteFacadeClosers.set(facade, () => store.close());
|
|
68
60
|
return facade;
|
|
69
61
|
}
|
|
70
|
-
export async function openSqliteInteractiveInteractionStoreForWrite(lease) {
|
|
62
|
+
export async function openSqliteInteractiveInteractionStoreForWrite(lease, storeFactory, backendIdentity = storeFactory ?? createSqliteInteractionStore, retainUntilGroupClose) {
|
|
71
63
|
await assertStorageRootLease(lease, 'interactive', 'write');
|
|
64
|
+
// Child close revokes access; the group retains the authority until every
|
|
65
|
+
// backend handle has closed successfully, including on a failed close.
|
|
66
|
+
if (retainUntilGroupClose && !retainedByExecution.has(lease)) {
|
|
67
|
+
retainedByExecution.add(lease);
|
|
68
|
+
retainUntilGroupClose(() => {
|
|
69
|
+
retainedByExecution.delete(lease);
|
|
70
|
+
const cached = sqliteWritersByLease.get(lease);
|
|
71
|
+
if (!cached || successfullyClosedWriters.has(cached)) {
|
|
72
|
+
sqliteWritersByLease.delete(lease);
|
|
73
|
+
backendByLease.delete(lease);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
72
77
|
const existing = sqliteWritersByLease.get(lease);
|
|
78
|
+
if ((existing && !writers.has(existing)) ||
|
|
79
|
+
(!existing && retainedByExecution.has(lease) && !retainUntilGroupClose)) {
|
|
80
|
+
throw new StorageRootAuthorityError('invalid_lease', 'Interaction authority is owned by its execution group');
|
|
81
|
+
}
|
|
82
|
+
if (storeFactory && backendByLease.has(lease) && backendByLease.get(lease) !== backendIdentity) {
|
|
83
|
+
throw new StorageRootAuthorityError('invalid_lease', 'Interaction authority is already composed for this lease');
|
|
84
|
+
}
|
|
73
85
|
if (existing)
|
|
74
86
|
return existing;
|
|
75
87
|
const opening = sqliteWriterOpeningsByLease.get(lease);
|
|
76
88
|
if (opening)
|
|
77
89
|
return opening;
|
|
90
|
+
backendByLease.set(lease, backendIdentity);
|
|
78
91
|
const pending = Promise.resolve().then(async () => {
|
|
79
|
-
const store =
|
|
80
|
-
|
|
81
|
-
|
|
92
|
+
const store = (storeFactory ?? createSqliteInteractionStore)(lease.canonicalPath);
|
|
93
|
+
try {
|
|
94
|
+
await store.ready?.();
|
|
95
|
+
await assertStorageRootLease(lease, 'interactive', 'write');
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
store.close();
|
|
99
|
+
backendByLease.delete(lease);
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
let closed = false;
|
|
103
|
+
const run = (operation) => {
|
|
104
|
+
if (closed)
|
|
105
|
+
return Promise.reject(invalidFacade('write'));
|
|
106
|
+
return runWithStorageRootLease(lease, 'interactive', 'write', () => {
|
|
107
|
+
if (closed)
|
|
108
|
+
throw invalidFacade('write');
|
|
109
|
+
return operation();
|
|
110
|
+
});
|
|
111
|
+
};
|
|
82
112
|
const recoveredExisting = sqliteWritersByLease.get(lease);
|
|
83
113
|
if (recoveredExisting) {
|
|
84
114
|
store.close();
|
|
@@ -98,7 +128,16 @@ export async function openSqliteInteractiveInteractionStoreForWrite(lease) {
|
|
|
98
128
|
});
|
|
99
129
|
writers.add(facade);
|
|
100
130
|
sqliteWritersByLease.set(lease, facade);
|
|
101
|
-
sqliteFacadeClosers.set(facade, () =>
|
|
131
|
+
sqliteFacadeClosers.set(facade, () => {
|
|
132
|
+
closed = true;
|
|
133
|
+
writers.delete(facade);
|
|
134
|
+
store.close();
|
|
135
|
+
successfullyClosedWriters.add(facade);
|
|
136
|
+
if (sqliteWritersByLease.get(lease) === facade && !retainedByExecution.has(lease)) {
|
|
137
|
+
sqliteWritersByLease.delete(lease);
|
|
138
|
+
backendByLease.delete(lease);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
102
141
|
return facade;
|
|
103
142
|
});
|
|
104
143
|
sqliteWriterOpeningsByLease.set(lease, pending);
|
|
@@ -118,6 +157,9 @@ export function closeSqliteInteractionStoreFacade(store) {
|
|
|
118
157
|
sqliteFacadeClosers.delete(store);
|
|
119
158
|
close();
|
|
120
159
|
}
|
|
160
|
+
export function createSqliteInteractionStore(root) {
|
|
161
|
+
return new SqliteInteractionStore(root);
|
|
162
|
+
}
|
|
121
163
|
class SqliteInteractionStore {
|
|
122
164
|
#lease;
|
|
123
165
|
constructor(root) {
|
|
@@ -367,14 +409,6 @@ class SqliteInteractionStore {
|
|
|
367
409
|
this.#lease.close();
|
|
368
410
|
}
|
|
369
411
|
}
|
|
370
|
-
function sameGrantAuthority(left, right) {
|
|
371
|
-
return (left.sessionId === right.sessionId &&
|
|
372
|
-
left.providerId === right.providerId &&
|
|
373
|
-
left.contractId === right.contractId &&
|
|
374
|
-
left.capability === right.capability &&
|
|
375
|
-
left.scope.kind === right.scope.kind &&
|
|
376
|
-
clientCapabilityScopeIdentity(left.scope) === clientCapabilityScopeIdentity(right.scope));
|
|
377
|
-
}
|
|
378
412
|
function readSqliteInteraction(lease, requestId) {
|
|
379
413
|
const row = lease.database
|
|
380
414
|
.prepare(`
|
|
@@ -400,195 +434,6 @@ function readSqliteInteraction(lease, requestId) {
|
|
|
400
434
|
: decodeFailure('record', 'Invalid SQLite Interaction outcome');
|
|
401
435
|
return deepFreeze({ request, ...(outcome ? { outcome } : {}) });
|
|
402
436
|
}
|
|
403
|
-
function sortPending(requests) {
|
|
404
|
-
return requests.sort((a, b) => a.createdAt - b.createdAt || a.requestId.localeCompare(b.requestId));
|
|
405
|
-
}
|
|
406
|
-
function normalizeRequest(value, source) {
|
|
407
|
-
const record = closedRecord(value, ['sessionId', 'turnId', 'runId', 'requestId', 'createdAt', 'request'], ['rememberScopeId'], source);
|
|
408
|
-
const createdAt = record.createdAt;
|
|
409
|
-
if (!Number.isSafeInteger(createdAt) || createdAt < 0)
|
|
410
|
-
decodeFailure(source, 'createdAt must be a non-negative safe integer');
|
|
411
|
-
let request;
|
|
412
|
-
try {
|
|
413
|
-
request = decodeInteractionRequest(record.request);
|
|
414
|
-
if (request.kind === 'question') {
|
|
415
|
-
const canonical = projectInteractionQuestionRequest({
|
|
416
|
-
toolUseId: request.toolUseId,
|
|
417
|
-
questions: request.questions,
|
|
418
|
-
});
|
|
419
|
-
if (!isDeepStrictEqual(request, canonical))
|
|
420
|
-
decodeFailure(source, 'Interaction question request is not canonical safe text');
|
|
421
|
-
request = canonical;
|
|
422
|
-
}
|
|
423
|
-
else if (request.kind === 'form') {
|
|
424
|
-
const canonical = projectInteractionFormRequest({
|
|
425
|
-
toolUseId: request.toolUseId,
|
|
426
|
-
message: request.message,
|
|
427
|
-
requester: request.requester,
|
|
428
|
-
fields: request.fields,
|
|
429
|
-
});
|
|
430
|
-
if (!isDeepStrictEqual(request, canonical)) {
|
|
431
|
-
decodeFailure(source, 'Interaction form request is not canonical');
|
|
432
|
-
}
|
|
433
|
-
request = canonical;
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
catch (error) {
|
|
437
|
-
if (error instanceof InteractionStoreError)
|
|
438
|
-
throw error;
|
|
439
|
-
decodeFailure(source, 'Invalid Interaction request', error);
|
|
440
|
-
}
|
|
441
|
-
const rememberScopeId = record.rememberScopeId === undefined
|
|
442
|
-
? undefined
|
|
443
|
-
: assertRememberScopeId(record.rememberScopeId, source);
|
|
444
|
-
if (rememberScopeId !== undefined && !isRememberScopeEligible(request))
|
|
445
|
-
decodeFailure(source, 'rememberScopeId requires a rememberable tool permission request');
|
|
446
|
-
return {
|
|
447
|
-
sessionId: assertId(record.sessionId, source),
|
|
448
|
-
turnId: assertId(record.turnId, source),
|
|
449
|
-
runId: assertId(record.runId, source),
|
|
450
|
-
requestId: assertId(record.requestId, source),
|
|
451
|
-
createdAt: createdAt,
|
|
452
|
-
request,
|
|
453
|
-
...(rememberScopeId === undefined ? {} : { rememberScopeId }),
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
function normalizeOutcome(value, request) {
|
|
457
|
-
const record = closedRecord(value, ['sessionId', 'turnId', 'runId', 'requestId', 'outcome'], [], 'record');
|
|
458
|
-
const storedIdentity = {
|
|
459
|
-
sessionId: assertId(record.sessionId, 'record'),
|
|
460
|
-
turnId: assertId(record.turnId, 'record'),
|
|
461
|
-
runId: assertId(record.runId, 'record'),
|
|
462
|
-
requestId: assertId(record.requestId, 'record'),
|
|
463
|
-
};
|
|
464
|
-
if (!isDeepStrictEqual(storedIdentity, identity(request)))
|
|
465
|
-
throw new InteractionStoreError('invalid_record', 'Outcome identity does not match request');
|
|
466
|
-
let outcome;
|
|
467
|
-
try {
|
|
468
|
-
outcome = decodeInteractionCanonicalOutcome(record.outcome);
|
|
469
|
-
}
|
|
470
|
-
catch (error) {
|
|
471
|
-
decodeFailure('record', 'Invalid stored Interaction outcome', error);
|
|
472
|
-
}
|
|
473
|
-
if (!isInteractionCanonicalOutcomeValidForRequest(request.request, outcome))
|
|
474
|
-
throw new InteractionStoreError('invalid_record', 'Stored outcome is invalid for request');
|
|
475
|
-
return { ...identity(request), outcome };
|
|
476
|
-
}
|
|
477
|
-
function decodeGrant(value, source) {
|
|
478
|
-
try {
|
|
479
|
-
return decodeClientCapabilitySessionGrant(value);
|
|
480
|
-
}
|
|
481
|
-
catch (error) {
|
|
482
|
-
decodeFailure(source, 'Invalid Client Capability Session Grant', error);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
function decodeGrantKey(value, source) {
|
|
486
|
-
try {
|
|
487
|
-
return decodeClientCapabilitySessionGrantKey(value);
|
|
488
|
-
}
|
|
489
|
-
catch (error) {
|
|
490
|
-
decodeFailure(source, 'Invalid Client Capability Session Grant key', error);
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
function decodeClientCapabilityOutcome(value) {
|
|
494
|
-
let outcome;
|
|
495
|
-
try {
|
|
496
|
-
outcome = decodeInteractionCanonicalOutcome(value);
|
|
497
|
-
}
|
|
498
|
-
catch (error) {
|
|
499
|
-
decodeFailure('input', 'Invalid Client Capability Interaction outcome', error);
|
|
500
|
-
}
|
|
501
|
-
if (outcome.kind !== 'client_capability_decision' && outcome.kind !== 'closure') {
|
|
502
|
-
decodeFailure('input', 'Invalid Client Capability Interaction outcome kind');
|
|
503
|
-
}
|
|
504
|
-
return outcome;
|
|
505
|
-
}
|
|
506
|
-
function identity(value) {
|
|
507
|
-
return {
|
|
508
|
-
sessionId: value.sessionId,
|
|
509
|
-
turnId: value.turnId,
|
|
510
|
-
runId: value.runId,
|
|
511
|
-
requestId: value.requestId,
|
|
512
|
-
};
|
|
513
|
-
}
|
|
514
|
-
function assertId(value, source = 'input', message = 'Invalid Interaction identity') {
|
|
515
|
-
if (!isSafeStorageId(value))
|
|
516
|
-
decodeFailure(source, message);
|
|
517
|
-
return value;
|
|
518
|
-
}
|
|
519
|
-
function assertRememberScopeId(value, source) {
|
|
520
|
-
if (typeof value !== 'string' || !REMEMBER_SCOPE_ID.test(value))
|
|
521
|
-
decodeFailure(source, 'rememberScopeId must be a lowercase 64-character SHA-256 digest');
|
|
522
|
-
return value;
|
|
523
|
-
}
|
|
524
|
-
function isRememberScopeEligible(request) {
|
|
525
|
-
return (request.kind === 'permission' &&
|
|
526
|
-
request.prompt.kind === 'tool_permission' &&
|
|
527
|
-
request.prompt.rememberForTurnAllowed);
|
|
528
|
-
}
|
|
529
|
-
function closedRecord(value, required, optional, source) {
|
|
530
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
531
|
-
decodeFailure(source, 'Stored Interaction request must be a plain object');
|
|
532
|
-
const prototype = Object.getPrototypeOf(value);
|
|
533
|
-
if (prototype !== Object.prototype && prototype !== null)
|
|
534
|
-
decodeFailure(source, 'Stored Interaction request must be a plain object');
|
|
535
|
-
const record = value;
|
|
536
|
-
const allowed = new Set([...required, ...optional]);
|
|
537
|
-
if (Reflect.ownKeys(record).some((key) => {
|
|
538
|
-
if (typeof key !== 'string' || !allowed.has(key))
|
|
539
|
-
return true;
|
|
540
|
-
const descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
541
|
-
return descriptor === undefined || !('value' in descriptor);
|
|
542
|
-
}) ||
|
|
543
|
-
required.some((key) => !Object.hasOwn(record, key)))
|
|
544
|
-
decodeFailure(source, 'Stored Interaction request has invalid fields');
|
|
545
|
-
return record;
|
|
546
|
-
}
|
|
547
|
-
function parseJsonRecord(serialized, context) {
|
|
548
|
-
try {
|
|
549
|
-
return JSON.parse(serialized);
|
|
550
|
-
}
|
|
551
|
-
catch (error) {
|
|
552
|
-
throw new InteractionStoreError('invalid_record', `Invalid stored Interaction ${context}`, {
|
|
553
|
-
cause: error,
|
|
554
|
-
});
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
function decodeFailure(source, message, cause) {
|
|
558
|
-
throw new InteractionStoreError(source === 'input' ? 'invalid_input' : 'invalid_record', message, {
|
|
559
|
-
cause,
|
|
560
|
-
});
|
|
561
|
-
}
|
|
562
|
-
function encode(value, limit) {
|
|
563
|
-
const bytes = Buffer.from(`${JSON.stringify(value)}\n`);
|
|
564
|
-
if (bytes.length > limit)
|
|
565
|
-
throw new InteractionStoreError('invalid_input', 'Interaction document exceeds size limit');
|
|
566
|
-
return bytes;
|
|
567
|
-
}
|
|
568
|
-
function failure(error, message) {
|
|
569
|
-
return error instanceof InteractionStoreError
|
|
570
|
-
? error
|
|
571
|
-
: new InteractionStoreError('io_failed', message, { cause: error });
|
|
572
|
-
}
|
|
573
|
-
function normalizeFilter(filter) {
|
|
574
|
-
for (const value of [filter.sessionId, filter.turnId, filter.runId])
|
|
575
|
-
if (value !== undefined)
|
|
576
|
-
assertId(value);
|
|
577
|
-
}
|
|
578
|
-
function matches(request, filter) {
|
|
579
|
-
return ((filter.sessionId === undefined || filter.sessionId === request.sessionId) &&
|
|
580
|
-
(filter.turnId === undefined || filter.turnId === request.turnId) &&
|
|
581
|
-
(filter.runId === undefined || filter.runId === request.runId) &&
|
|
582
|
-
(filter.kind === undefined || filter.kind === request.request.kind));
|
|
583
|
-
}
|
|
584
|
-
function deepFreeze(value) {
|
|
585
|
-
if (!value || typeof value !== 'object' || Object.isFrozen(value))
|
|
586
|
-
return value;
|
|
587
|
-
Object.freeze(value);
|
|
588
|
-
for (const nested of Object.values(value))
|
|
589
|
-
deepFreeze(nested);
|
|
590
|
-
return value;
|
|
591
|
-
}
|
|
592
437
|
function invalidFacade(access) {
|
|
593
438
|
return new StorageRootAuthorityError('invalid_lease', `Expected authentic interactive ${access} Interaction Store`);
|
|
594
439
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Licensed to the Apache Software Foundation (ASF) under one
|
|
3
|
+
* or more contributor license agreements. See the NOTICE file
|
|
4
|
+
* distributed with this work for additional information
|
|
5
|
+
* regarding copyright ownership. The ASF licenses this file
|
|
6
|
+
* to you under the Apache License, Version 2.0 (the
|
|
7
|
+
* "License"); you may not use this file except in compliance
|
|
8
|
+
* with the License. You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing,
|
|
13
|
+
* software distributed under the License is distributed on an
|
|
14
|
+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
15
|
+
* KIND, either express or implied. See the License for the
|
|
16
|
+
* specific language governing permissions and limitations
|
|
17
|
+
* under the License.
|
|
18
|
+
*/
|
|
19
|
+
import { createSessionStore } from './session-store.js';
|
|
20
|
+
import { createSqliteAgentRunStore } from './agent-run-store.js';
|
|
21
|
+
import { openRuntimeEventPersistence } from './runtime-event-persistence.js';
|
|
22
|
+
import { createConversationOperationalStateStore } from './conversation-operational-state.js';
|
|
23
|
+
import { createAgentGraphControlStore } from './agent-graph-control-store.js';
|
|
24
|
+
import { createSqliteGoalAuthority } from './goal-authority.js';
|
|
25
|
+
import { createSqliteInteractionStore } from './interaction-store.js';
|
|
26
|
+
export const localExecutionPersistenceProvider = Object.freeze({
|
|
27
|
+
async open({ canonicalPath }) {
|
|
28
|
+
const closes = [];
|
|
29
|
+
let closing;
|
|
30
|
+
const close = () => (closing ??= (async () => {
|
|
31
|
+
const errors = [];
|
|
32
|
+
for (const dispose of [...closes].reverse()) {
|
|
33
|
+
try {
|
|
34
|
+
await dispose();
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
errors.push(error);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (errors.length)
|
|
41
|
+
throw new AggregateError(errors, 'Unable to close local execution persistence');
|
|
42
|
+
})());
|
|
43
|
+
try {
|
|
44
|
+
const sessionStore = createSessionStore(canonicalPath);
|
|
45
|
+
closes.push(() => sessionStore.close?.());
|
|
46
|
+
const agentRunStore = createSqliteAgentRunStore(canonicalPath);
|
|
47
|
+
closes.push(() => agentRunStore.close?.());
|
|
48
|
+
const runtime = await openRuntimeEventPersistence({ workspaceRoot: canonicalPath });
|
|
49
|
+
closes.push(() => runtime.close());
|
|
50
|
+
const operational = createConversationOperationalStateStore(canonicalPath);
|
|
51
|
+
closes.push(() => operational.close());
|
|
52
|
+
const graphControlStore = createAgentGraphControlStore(canonicalPath);
|
|
53
|
+
closes.push(() => graphControlStore.close());
|
|
54
|
+
const goalStore = createSqliteGoalAuthority(canonicalPath);
|
|
55
|
+
closes.push(() => goalStore.close());
|
|
56
|
+
const interactionStore = createSqliteInteractionStore(canonicalPath);
|
|
57
|
+
closes.push(() => interactionStore.close());
|
|
58
|
+
await Promise.all([sessionStore.ready(), agentRunStore.ready?.(), interactionStore.ready()]);
|
|
59
|
+
return {
|
|
60
|
+
sessionStore,
|
|
61
|
+
agentRunStore,
|
|
62
|
+
runtimeEventStore: runtime.runtimeEventStore,
|
|
63
|
+
graphControlStore,
|
|
64
|
+
goalStore,
|
|
65
|
+
interactionStore,
|
|
66
|
+
purgeConversationOperationalState: (sessionId) => operational.purge(sessionId),
|
|
67
|
+
close,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
try {
|
|
72
|
+
await close();
|
|
73
|
+
}
|
|
74
|
+
catch (closeError) {
|
|
75
|
+
throw new AggregateError([error, closeError], 'Unable to open local execution persistence');
|
|
76
|
+
}
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
});
|
|
@@ -391,6 +391,10 @@ export async function prepareArtifactWriterLockAuthorityForMarkedRoot(path) {
|
|
|
391
391
|
export async function tryAcquireInteractiveRootReader(capability) {
|
|
392
392
|
return withAuthorityFailure('lock_failed', 'Unable to acquire the interactive storage root reader lock', () => acquireStateRootLock(capability, 'read'));
|
|
393
393
|
}
|
|
394
|
+
/** Synchronous capability/liveness check only; I/O still requires the full lease guard. */
|
|
395
|
+
export function assertStorageRootLeaseActive(lease, expectedKind, expectedAccess) {
|
|
396
|
+
requireLease(lease, expectedKind, expectedAccess);
|
|
397
|
+
}
|
|
394
398
|
export async function assertStorageRootLease(lease, expectedKind, expectedAccess) {
|
|
395
399
|
const record = requireLease(lease, expectedKind, expectedAccess);
|
|
396
400
|
await assertRootIdentity(record);
|
|
@@ -0,0 +1,19 @@
|
|
|
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
|
+
export {};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Licensed to the Apache Software Foundation (ASF) under one
|
|
3
|
+
* or more contributor license agreements. See the NOTICE file
|
|
4
|
+
* distributed with this work for additional information
|
|
5
|
+
* regarding copyright ownership. The ASF licenses this file
|
|
6
|
+
* to you under the Apache License, Version 2.0 (the
|
|
7
|
+
* "License"); you may not use this file except in compliance
|
|
8
|
+
* with the License. You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing,
|
|
13
|
+
* software distributed under the License is distributed on an
|
|
14
|
+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
15
|
+
* KIND, either express or implied. See the License for the
|
|
16
|
+
* specific language governing permissions and limitations
|
|
17
|
+
* under the License.
|
|
18
|
+
*/
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
20
|
+
export function mergeRuntimePartialSnapshots(immutableEvents, snapshots) {
|
|
21
|
+
const { leading, afterEvent } = groupRuntimePartialSnapshots(snapshots);
|
|
22
|
+
const merged = leading.sort(compareRuntimePartialSnapshots).map(({ event }) => event);
|
|
23
|
+
for (const event of immutableEvents) {
|
|
24
|
+
merged.push(event);
|
|
25
|
+
const anchored = afterEvent.get(event.id);
|
|
26
|
+
if (!anchored)
|
|
27
|
+
continue;
|
|
28
|
+
merged.push(...anchored.sort(compareRuntimePartialSnapshots).map((snapshot) => snapshot.event));
|
|
29
|
+
afterEvent.delete(event.id);
|
|
30
|
+
}
|
|
31
|
+
for (const orphaned of afterEvent.values()) {
|
|
32
|
+
merged.push(...orphaned.sort(compareRuntimePartialSnapshots).map((snapshot) => snapshot.event));
|
|
33
|
+
}
|
|
34
|
+
return merged;
|
|
35
|
+
}
|
|
36
|
+
export function groupRuntimePartialSnapshots(snapshots) {
|
|
37
|
+
const leading = [];
|
|
38
|
+
const afterEvent = new Map();
|
|
39
|
+
for (const snapshot of snapshots) {
|
|
40
|
+
if (!snapshot.afterEventId) {
|
|
41
|
+
leading.push(snapshot);
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const grouped = afterEvent.get(snapshot.afterEventId) ?? [];
|
|
45
|
+
grouped.push(snapshot);
|
|
46
|
+
afterEvent.set(snapshot.afterEventId, grouped);
|
|
47
|
+
}
|
|
48
|
+
return { leading, afterEvent };
|
|
49
|
+
}
|
|
50
|
+
export function compareRuntimePartialSnapshots(left, right) {
|
|
51
|
+
return left.event.ts - right.event.ts || left.event.id.localeCompare(right.event.id);
|
|
52
|
+
}
|
|
53
|
+
export function partialRuntimeStream(event) {
|
|
54
|
+
if (!event.partial || event.status !== undefined || event.actions)
|
|
55
|
+
return undefined;
|
|
56
|
+
const content = event.content;
|
|
57
|
+
let identity;
|
|
58
|
+
let text = '';
|
|
59
|
+
if (content?.kind === 'text' &&
|
|
60
|
+
content.attachments === undefined &&
|
|
61
|
+
event.refs?.providerEventId &&
|
|
62
|
+
hasOnlyKeys(event.refs, ['providerEventId'])) {
|
|
63
|
+
identity = `${content.kind}:provider:${event.refs.providerEventId}`;
|
|
64
|
+
text = content.text;
|
|
65
|
+
}
|
|
66
|
+
else if (content?.kind === 'thinking' &&
|
|
67
|
+
content.signature === undefined &&
|
|
68
|
+
event.refs?.providerEventId &&
|
|
69
|
+
hasOnlyKeys(event.refs, ['providerEventId'])) {
|
|
70
|
+
identity = `${content.kind}:provider:${event.refs.providerEventId}`;
|
|
71
|
+
text = content.text;
|
|
72
|
+
}
|
|
73
|
+
else if (!content && event.refs?.toolCallId && hasOnlyKeys(event.refs, ['toolCallId'])) {
|
|
74
|
+
identity = `tool:call:${event.refs.toolCallId}`;
|
|
75
|
+
}
|
|
76
|
+
if (!identity)
|
|
77
|
+
return undefined;
|
|
78
|
+
const key = runtimePartialStreamKey(identity, event);
|
|
79
|
+
const snapshot = content?.kind === 'text' || content?.kind === 'thinking'
|
|
80
|
+
? { ...event, content: { ...content, text: '' } }
|
|
81
|
+
: event;
|
|
82
|
+
return { key, snapshot, text };
|
|
83
|
+
}
|
|
84
|
+
export function completedPartialRuntimeStreamKey(event) {
|
|
85
|
+
if (event.partial)
|
|
86
|
+
return undefined;
|
|
87
|
+
const content = event.content;
|
|
88
|
+
let identity;
|
|
89
|
+
if ((content?.kind === 'text' || content?.kind === 'thinking') && event.refs?.providerEventId) {
|
|
90
|
+
identity = `${content.kind}:provider:${event.refs.providerEventId}`;
|
|
91
|
+
}
|
|
92
|
+
else if (content?.kind === 'function_response' && event.refs?.toolCallId) {
|
|
93
|
+
identity = `tool:call:${event.refs.toolCallId}`;
|
|
94
|
+
}
|
|
95
|
+
return identity ? runtimePartialStreamKey(identity, event) : undefined;
|
|
96
|
+
}
|
|
97
|
+
export function runtimePartialStreamKey(identity, event) {
|
|
98
|
+
return createHash('sha256')
|
|
99
|
+
.update(JSON.stringify([
|
|
100
|
+
identity,
|
|
101
|
+
event.sessionId,
|
|
102
|
+
event.invocationId,
|
|
103
|
+
event.runId,
|
|
104
|
+
event.turnId,
|
|
105
|
+
event.branch ?? null,
|
|
106
|
+
event.role,
|
|
107
|
+
event.author,
|
|
108
|
+
]))
|
|
109
|
+
.digest('hex');
|
|
110
|
+
}
|
|
111
|
+
export function hasOnlyKeys(value, allowed) {
|
|
112
|
+
const allowedSet = new Set(allowed);
|
|
113
|
+
return Object.keys(value).every((key) => allowedSet.has(key));
|
|
114
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
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
|
+
export class SessionMetadataConflictError extends Error {
|
|
20
|
+
name = 'SessionMetadataConflictError';
|
|
21
|
+
}
|
|
22
|
+
export class AgentGraphIntentClaimConflictError extends SessionMetadataConflictError {
|
|
23
|
+
name = 'AgentGraphIntentClaimConflictError';
|
|
24
|
+
}
|
|
25
|
+
export class AgentGraphScheduleUpdateConflictError extends SessionMetadataConflictError {
|
|
26
|
+
name = 'AgentGraphScheduleUpdateConflictError';
|
|
27
|
+
}
|
|
28
|
+
export class SessionMetadataVersionConflictError extends SessionMetadataConflictError {
|
|
29
|
+
sessionId;
|
|
30
|
+
expectedVersion;
|
|
31
|
+
actualVersion;
|
|
32
|
+
name = 'SessionMetadataVersionConflictError';
|
|
33
|
+
constructor(sessionId, expectedVersion, actualVersion) {
|
|
34
|
+
super(`Session metadata version conflict for ${sessionId}: expected ${expectedVersion}, found ${actualVersion}`);
|
|
35
|
+
this.sessionId = sessionId;
|
|
36
|
+
this.expectedVersion = expectedVersion;
|
|
37
|
+
this.actualVersion = actualVersion;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
41
|
+
export function isSafeSessionId(sessionId) {
|
|
42
|
+
return SESSION_ID_PATTERN.test(sessionId);
|
|
43
|
+
}
|
|
44
|
+
export function assertSafeSessionId(sessionId) {
|
|
45
|
+
if (!isSafeSessionId(sessionId))
|
|
46
|
+
throw new Error(`Invalid Session id: ${sessionId}`);
|
|
47
|
+
}
|
|
48
|
+
export class SessionNotFoundError extends Error {
|
|
49
|
+
sessionId;
|
|
50
|
+
name = 'SessionNotFoundError';
|
|
51
|
+
code = 'session_not_found';
|
|
52
|
+
constructor(sessionId) {
|
|
53
|
+
super(`Session metadata not found: ${sessionId}`);
|
|
54
|
+
this.sessionId = sessionId;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export function isSessionNotFoundError(error) {
|
|
58
|
+
return error instanceof SessionNotFoundError;
|
|
59
|
+
}
|
|
60
|
+
export const EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_SOURCE_IDS = 256;
|
|
61
|
+
export const EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_RECENT_SESSION_IDS = 16;
|