maka-agent 0.2.0-dev.69.20261004 → 0.2.0-dev.74.20261008
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/LICENSE +3 -3
- package/THIRD_PARTY_NOTICES.txt +2 -2
- package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
- package/node_modules/@maka/core/dist/archive-retention.js +109 -0
- package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +8 -4
- package/node_modules/@maka/core/package.json +1 -0
- package/node_modules/@maka/mcp/dist/oauth.js +7 -2
- package/node_modules/@maka/mcp/package.json +1 -1
- package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +11 -2
- package/node_modules/@maka/runtime-host/dist/protocol/index.js +6 -1
- package/node_modules/@maka/runtime-host/dist/protocol/operations.js +5 -1
- package/node_modules/@maka/runtime-host/dist/protocol/storage-retention.js +144 -0
- package/node_modules/@maka/runtime-host/dist/server/archive-retention-coordinator.js +546 -0
- package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +1 -1
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +12 -0
- package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +73 -7
- package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +34 -4
- package/node_modules/@maka/storage/dist/archive-retention-store.js +124 -0
- package/node_modules/@maka/storage/dist/context-offload-store.js +4 -0
- package/node_modules/@maka/storage/dist/execution-stores.js +3 -0
- package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +48 -16
- package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +2 -2
- package/node_modules/@maka/storage/dist/runtime-policy/document-io.js +1 -1
- package/node_modules/@maka/storage/dist/runtime-policy-stores.js +1 -1
- package/node_modules/@maka/storage/dist/session-bundle-policy.js +9 -0
- package/node_modules/@maka/storage/dist/session-store.js +17 -0
- package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +34 -0
- package/node_modules/@maka/storage/dist/sqlite-session-catalog-query.js +48 -5
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +111 -1
- package/node_modules/@maka/storage/dist/sqlite-session-role-scope.js +3 -3
- package/node_modules/@maka/storage/dist/storage-writer-composition.js +2 -0
- package/node_modules/@maka/storage/package.json +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index-D_CiY-T3.d.cts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index-D_QDtbiv.d.mts.map +1 -0
- package/node_modules/@modelcontextprotocol/client/dist/index.cjs +100 -55
- package/node_modules/@modelcontextprotocol/client/dist/index.d.cts.map +1 -1
- package/node_modules/@modelcontextprotocol/client/dist/index.d.mts.map +1 -1
- package/node_modules/@modelcontextprotocol/client/dist/index.mjs +100 -55
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.cjs +1 -1
- package/node_modules/@modelcontextprotocol/client/dist/shimsWorkerd.mjs +1 -1
- package/node_modules/@modelcontextprotocol/client/dist/{src-D0qEN74R.cjs → src-oZBjf3U1.cjs} +21 -4
- package/node_modules/@modelcontextprotocol/client/dist/{src-DDAAhLnO.mjs → src-xKF0PJN-.mjs} +16 -5
- package/node_modules/@modelcontextprotocol/client/dist/stdio.cjs +1 -1
- package/node_modules/@modelcontextprotocol/client/dist/stdio.mjs +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/{auth--n_Yzytt.d.cts.map → auth-Anm-lwWi.d.mts.map} +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/{auth-CGP0BDVq.mjs → auth-BNDyLTqp.mjs} +5 -3
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/{auth-4-zilcqg.cjs → auth-D1CeV_Jr.cjs} +5 -3
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/{auth-YUQV3RRv.d.mts.map → auth-V9XJSCfa.d.cts.map} +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/index.cjs +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/index.mjs +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/internal.cjs +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/dist/internal.mjs +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/package.json +1 -1
- package/node_modules/@modelcontextprotocol/client/package.json +3 -3
- package/package.json +1 -1
- package/node_modules/@modelcontextprotocol/client/dist/index-BCtJi0p5.d.mts.map +0 -1
- package/node_modules/@modelcontextprotocol/client/dist/index-CEk3qkZM.d.cts.map +0 -1
|
@@ -46,6 +46,14 @@ class RetryRemovalPlanResolution extends Error {
|
|
|
46
46
|
class SessionRetirementBusyError extends Error {
|
|
47
47
|
name = 'SessionRetirementBusyError';
|
|
48
48
|
}
|
|
49
|
+
class RetentionHold extends Error {
|
|
50
|
+
reason;
|
|
51
|
+
name = 'RetentionHold';
|
|
52
|
+
constructor(reason) {
|
|
53
|
+
super(`Archive retention kept the task: ${reason}`);
|
|
54
|
+
this.reason = reason;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
49
57
|
/** Host-owned archive, unarchive, remove, and revision-family commit authority. */
|
|
50
58
|
export class HostSessionRetirementCoordinator {
|
|
51
59
|
handlers = {
|
|
@@ -169,7 +177,57 @@ export class HostSessionRetirementCoordinator {
|
|
|
169
177
|
return this.#lifecycleFailure(error);
|
|
170
178
|
}
|
|
171
179
|
}
|
|
172
|
-
|
|
180
|
+
/**
|
|
181
|
+
* Archive retention's removal: `session.remove` for the task the sweep read,
|
|
182
|
+
* with `guard` run inside the removal admission — after the plan is stable,
|
|
183
|
+
* before any retirement work — so a task whose policy, archive or pin state,
|
|
184
|
+
* age or plan changed since the sweep read it is kept rather than deleted.
|
|
185
|
+
* The size is measured once the guard admits the plan, as the batch preview
|
|
186
|
+
* measures it.
|
|
187
|
+
*/
|
|
188
|
+
async removeForRetention(target, guard) {
|
|
189
|
+
let admitted = false;
|
|
190
|
+
let bytes;
|
|
191
|
+
let outcome;
|
|
192
|
+
try {
|
|
193
|
+
outcome = await this.#removeUnder(target, async (plan) => {
|
|
194
|
+
const remove = plan.remove.sessionIds.map((id) => requireFamilyRecord(plan.remove, id));
|
|
195
|
+
const reason = await guard({
|
|
196
|
+
remove,
|
|
197
|
+
archiveSessionIds: plan.archive.sessionIds,
|
|
198
|
+
worktreeCount: this.#reclaimedWorktreeCount(remove.map(({ header }) => header)),
|
|
199
|
+
});
|
|
200
|
+
if (reason)
|
|
201
|
+
throw new RetentionHold(reason);
|
|
202
|
+
admitted = true;
|
|
203
|
+
bytes = await this.#measureRemoved(plan.remove.sessionIds);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
if (error instanceof RetentionHold)
|
|
208
|
+
return { kind: 'held', reason: error.reason };
|
|
209
|
+
return { kind: 'failed' };
|
|
210
|
+
}
|
|
211
|
+
if (outcome.ok) {
|
|
212
|
+
// Removed without this guard admitting it — already gone — is not this sweep's deletion.
|
|
213
|
+
if (outcome.result.kind !== 'removed' || !admitted)
|
|
214
|
+
return { kind: 'skipped' };
|
|
215
|
+
return { kind: 'removed', ...(bytes === undefined ? {} : { bytes }) };
|
|
216
|
+
}
|
|
217
|
+
switch (outcome.error.code) {
|
|
218
|
+
case 'session_busy':
|
|
219
|
+
return { kind: 'busy' };
|
|
220
|
+
case 'not_found':
|
|
221
|
+
case 'operation_conflict':
|
|
222
|
+
return { kind: 'skipped' };
|
|
223
|
+
default:
|
|
224
|
+
return { kind: 'failed' };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
#remove(input) {
|
|
228
|
+
return this.#removeUnder(input);
|
|
229
|
+
}
|
|
230
|
+
async #removeUnder(input, guard) {
|
|
173
231
|
let probe;
|
|
174
232
|
try {
|
|
175
233
|
probe = await this.#stores.probeSessionRemoval(input.sessionId);
|
|
@@ -206,6 +264,7 @@ export class HostSessionRetirementCoordinator {
|
|
|
206
264
|
return removeOutcome({ kind: 'too_recent', sessionId: input.sessionId });
|
|
207
265
|
}
|
|
208
266
|
}
|
|
267
|
+
await guard?.(plan);
|
|
209
268
|
let removeHandles;
|
|
210
269
|
let archiveHandles;
|
|
211
270
|
let committed = false;
|
|
@@ -250,6 +309,8 @@ export class HostSessionRetirementCoordinator {
|
|
|
250
309
|
});
|
|
251
310
|
}
|
|
252
311
|
catch (error) {
|
|
312
|
+
if (error instanceof RetentionHold)
|
|
313
|
+
throw error;
|
|
253
314
|
return this.#removeFailure(error, input);
|
|
254
315
|
}
|
|
255
316
|
}
|
|
@@ -309,16 +370,21 @@ export class HostSessionRetirementCoordinator {
|
|
|
309
370
|
removedSubtaskCount: new Set(removedHeaders
|
|
310
371
|
.filter((header) => header.subagentParent?.graph !== undefined)
|
|
311
372
|
.map(sessionRevisionFamilyId)).size,
|
|
312
|
-
|
|
313
|
-
// through a worktree executor. A subagent Session carrying a binding
|
|
314
|
-
// cannot be a revision, so no two removed Sessions share one.
|
|
315
|
-
worktreeCount: this.#worktrees
|
|
316
|
-
? removedHeaders.filter((header) => header.subagentWorkspace !== undefined).length
|
|
317
|
-
: 0,
|
|
373
|
+
worktreeCount: this.#reclaimedWorktreeCount(removedHeaders),
|
|
318
374
|
...(bytes === undefined ? {} : { bytes }),
|
|
319
375
|
},
|
|
320
376
|
};
|
|
321
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* What cleanup retires: one binding per removed Session, and only through a
|
|
380
|
+
* worktree executor. A subagent Session carrying a binding cannot be a
|
|
381
|
+
* revision, so no two removed Sessions share one.
|
|
382
|
+
*/
|
|
383
|
+
#reclaimedWorktreeCount(removed) {
|
|
384
|
+
return this.#worktrees
|
|
385
|
+
? removed.filter((header) => header.subagentWorkspace !== undefined).length
|
|
386
|
+
: 0;
|
|
387
|
+
}
|
|
322
388
|
/**
|
|
323
389
|
* Sizes removed Sessions in storage-usage pages, yielding between them. A
|
|
324
390
|
* failed measurement is left out rather than failing the counts beside it.
|
|
@@ -20,6 +20,12 @@ const ACTIVE_DELAY_MS = 100;
|
|
|
20
20
|
const IDLE_DELAY_MS = 60_000;
|
|
21
21
|
const MAX_BATCH_ITEMS = 64;
|
|
22
22
|
const MAX_BATCH_BYTES = 16 * 1024 * 1024;
|
|
23
|
+
const MAX_VACUUM_PAGES = 64;
|
|
24
|
+
// Archive retention deletes user data, so it moves slower than reclamation:
|
|
25
|
+
// one bounded batch a second while work remains, otherwise a check every
|
|
26
|
+
// quarter hour.
|
|
27
|
+
const RETENTION_ACTIVE_DELAY_MS = 1000;
|
|
28
|
+
const RETENTION_IDLE_DELAY_MS = 15 * 60_000;
|
|
23
29
|
/** Physical cleanup is optional work, admitted only after the Host publishes Ready. */
|
|
24
30
|
export class HostStorageMaintenance {
|
|
25
31
|
#lanes;
|
|
@@ -33,6 +39,8 @@ export class HostStorageMaintenance {
|
|
|
33
39
|
{
|
|
34
40
|
name: 'artifact upgrade cleanup',
|
|
35
41
|
failures: 0,
|
|
42
|
+
activeDelay: ACTIVE_DELAY_MS,
|
|
43
|
+
idleDelay: IDLE_DELAY_MS,
|
|
36
44
|
run: async () => {
|
|
37
45
|
const result = await input.artifacts.reclaimUpgradeResidue({
|
|
38
46
|
after,
|
|
@@ -47,23 +55,45 @@ export class HostStorageMaintenance {
|
|
|
47
55
|
},
|
|
48
56
|
];
|
|
49
57
|
const context = input.contextOffload;
|
|
50
|
-
if (context)
|
|
58
|
+
if (context) {
|
|
51
59
|
this.#lanes.push({
|
|
52
60
|
name: 'context garbage collection',
|
|
53
61
|
failures: 0,
|
|
62
|
+
activeDelay: ACTIVE_DELAY_MS,
|
|
63
|
+
idleDelay: IDLE_DELAY_MS,
|
|
54
64
|
run: async () => (await context.collectGarbage({
|
|
55
65
|
olderThan: Date.now(),
|
|
56
66
|
maxBlobs: MAX_BATCH_ITEMS,
|
|
57
67
|
maxBytes: MAX_BATCH_BYTES,
|
|
58
68
|
})).hasMore,
|
|
59
69
|
});
|
|
70
|
+
this.#lanes.push({
|
|
71
|
+
name: 'context-offload page reclamation',
|
|
72
|
+
failures: 0,
|
|
73
|
+
activeDelay: ACTIVE_DELAY_MS,
|
|
74
|
+
idleDelay: IDLE_DELAY_MS,
|
|
75
|
+
run: async () => {
|
|
76
|
+
const result = await context.reclaimFreePages({ maxPages: MAX_VACUUM_PAGES });
|
|
77
|
+
return result.hasMore;
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
const retention = input.retention;
|
|
82
|
+
if (retention)
|
|
83
|
+
this.#lanes.push({
|
|
84
|
+
name: 'archive retention',
|
|
85
|
+
failures: 0,
|
|
86
|
+
activeDelay: RETENTION_ACTIVE_DELAY_MS,
|
|
87
|
+
idleDelay: RETENTION_IDLE_DELAY_MS,
|
|
88
|
+
run: () => retention.sweep(),
|
|
89
|
+
});
|
|
60
90
|
}
|
|
61
91
|
start() {
|
|
62
92
|
if (this.#started || this.#draining)
|
|
63
93
|
return;
|
|
64
94
|
this.#started = true;
|
|
65
95
|
for (const lane of this.#lanes)
|
|
66
|
-
this.#schedule(lane,
|
|
96
|
+
this.#schedule(lane, lane.activeDelay);
|
|
67
97
|
}
|
|
68
98
|
beginDrain() {
|
|
69
99
|
this.#draining = true;
|
|
@@ -89,11 +119,11 @@ export class HostStorageMaintenance {
|
|
|
89
119
|
try {
|
|
90
120
|
const more = await lane.run();
|
|
91
121
|
lane.failures = 0;
|
|
92
|
-
delay = more ?
|
|
122
|
+
delay = more ? lane.activeDelay : lane.idleDelay;
|
|
93
123
|
}
|
|
94
124
|
catch (error) {
|
|
95
125
|
lane.failures = Math.min(lane.failures + 1, 7);
|
|
96
|
-
delay = Math.min(
|
|
126
|
+
delay = Math.min(lane.idleDelay, 1000 * 2 ** (lane.failures - 1));
|
|
97
127
|
this.#report(lane.name, error);
|
|
98
128
|
}
|
|
99
129
|
this.#schedule(lane, delay);
|
|
@@ -0,0 +1,124 @@
|
|
|
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 { decodeArchiveRetentionDeletion, decodeArchiveRetentionHold, decodeArchiveRetentionSweep, isArchiveRetentionDays, } from '@maka/core/archive-retention';
|
|
20
|
+
import { runWithStorageRootLease } from './root-authority.js';
|
|
21
|
+
import { readBoundedJsonDocument, writeJsonDocument } from './runtime-policy/document-io.js';
|
|
22
|
+
import { RuntimePolicyStoreError } from './runtime-policy/errors.js';
|
|
23
|
+
const FILE = 'archive-retention.json';
|
|
24
|
+
const VERSION = 1;
|
|
25
|
+
const MAX_BYTES = 16 * 1024;
|
|
26
|
+
export function openArchiveRetentionStore(lease) {
|
|
27
|
+
return Object.freeze({
|
|
28
|
+
read: () => runWithStorageRootLease(lease, 'interactive', 'write', (root) => readArchiveRetentionDocument(root)),
|
|
29
|
+
write: (document) => runWithStorageRootLease(lease, 'interactive', 'write', (root) => writeJsonDocument(root, FILE, encodeArchiveRetentionDocument(document), MAX_BYTES)),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
export async function readArchiveRetentionDocument(root) {
|
|
33
|
+
let value;
|
|
34
|
+
try {
|
|
35
|
+
value = await readBoundedJsonDocument(root, FILE, MAX_BYTES);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (error instanceof RuntimePolicyStoreError && error.code === 'invalid_document') {
|
|
39
|
+
return { kind: 'invalid', reason: error.message };
|
|
40
|
+
}
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
if (value === undefined)
|
|
44
|
+
return { kind: 'absent' };
|
|
45
|
+
try {
|
|
46
|
+
return { kind: 'valid', document: decodeArchiveRetentionDocument(value) };
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
return { kind: 'invalid', reason: error instanceof Error ? error.message : String(error) };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function decodeArchiveRetentionDocument(value) {
|
|
53
|
+
const document = exactRecord(value, FILE, ['version', 'revision', 'enabled', 'days'], ['enabledAt', 'latest']);
|
|
54
|
+
if (document.version !== VERSION)
|
|
55
|
+
throw new Error(`${FILE} has an unsupported version`);
|
|
56
|
+
if (typeof document.enabled !== 'boolean')
|
|
57
|
+
throw new Error(`${FILE} has an invalid enabled`);
|
|
58
|
+
if (!isArchiveRetentionDays(document.days))
|
|
59
|
+
throw new Error(`${FILE} has invalid days`);
|
|
60
|
+
if (document.enabled !== (document.enabledAt !== undefined)) {
|
|
61
|
+
throw new Error(`${FILE} must carry enabledAt exactly while enabled`);
|
|
62
|
+
}
|
|
63
|
+
const latest = document.latest === undefined
|
|
64
|
+
? undefined
|
|
65
|
+
: exactRecord(document.latest, `${FILE}.latest`, [], ['observedAt', 'lastSweep', 'lastDeletion', 'hold']);
|
|
66
|
+
return {
|
|
67
|
+
version: VERSION,
|
|
68
|
+
revision: count(document.revision, 'revision'),
|
|
69
|
+
enabled: document.enabled,
|
|
70
|
+
days: document.days,
|
|
71
|
+
...(document.enabledAt === undefined
|
|
72
|
+
? {}
|
|
73
|
+
: { enabledAt: count(document.enabledAt, 'enabledAt') }),
|
|
74
|
+
...(latest === undefined
|
|
75
|
+
? {}
|
|
76
|
+
: {
|
|
77
|
+
latest: {
|
|
78
|
+
...(latest.observedAt === undefined
|
|
79
|
+
? {}
|
|
80
|
+
: { observedAt: count(latest.observedAt, 'latest observedAt') }),
|
|
81
|
+
...(latest.lastSweep === undefined
|
|
82
|
+
? {}
|
|
83
|
+
: { lastSweep: decodeArchiveRetentionSweep(latest.lastSweep, documentError) }),
|
|
84
|
+
...(latest.lastDeletion === undefined
|
|
85
|
+
? {}
|
|
86
|
+
: {
|
|
87
|
+
lastDeletion: decodeArchiveRetentionDeletion(latest.lastDeletion, documentError),
|
|
88
|
+
}),
|
|
89
|
+
...(latest.hold === undefined
|
|
90
|
+
? {}
|
|
91
|
+
: { hold: decodeArchiveRetentionHold(latest.hold, documentError) }),
|
|
92
|
+
},
|
|
93
|
+
}),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function encodeArchiveRetentionDocument(document) {
|
|
97
|
+
// Never publish what the reader would refuse.
|
|
98
|
+
return decodeArchiveRetentionDocument(JSON.parse(JSON.stringify(document)));
|
|
99
|
+
}
|
|
100
|
+
function exactRecord(value, label, required, optional) {
|
|
101
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
102
|
+
throw new Error(`${label} must be an object`);
|
|
103
|
+
}
|
|
104
|
+
const record = value;
|
|
105
|
+
for (const key of Object.keys(record)) {
|
|
106
|
+
if (!required.includes(key) && !optional.includes(key)) {
|
|
107
|
+
throw new Error(`${label} has an unknown key`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
for (const key of required) {
|
|
111
|
+
if (!Object.hasOwn(record, key))
|
|
112
|
+
throw new Error(`${label} is missing ${key}`);
|
|
113
|
+
}
|
|
114
|
+
return record;
|
|
115
|
+
}
|
|
116
|
+
function count(value, label) {
|
|
117
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
|
|
118
|
+
throw new Error(`${FILE} has an invalid ${label}`);
|
|
119
|
+
}
|
|
120
|
+
return value;
|
|
121
|
+
}
|
|
122
|
+
function documentError(message) {
|
|
123
|
+
return new Error(`${FILE}: ${message}`);
|
|
124
|
+
}
|
|
@@ -162,6 +162,10 @@ function createWriterFacade(lease, store, limitsKey) {
|
|
|
162
162
|
const accepted = Object.freeze({ ...input });
|
|
163
163
|
return run(() => store.collectGarbage(accepted));
|
|
164
164
|
},
|
|
165
|
+
reclaimFreePages: (input) => {
|
|
166
|
+
const accepted = Object.freeze({ ...input });
|
|
167
|
+
return run(() => store.reclaimFreePages(accepted));
|
|
168
|
+
},
|
|
165
169
|
usage: (sessionId) => run(() => store.usage(sessionId)),
|
|
166
170
|
close: () => {
|
|
167
171
|
if (closeTask)
|
|
@@ -324,6 +324,9 @@ async function createExecutionStoresForWrite(lease, provider) {
|
|
|
324
324
|
reconcileOrphanedAgentGraphRetirements: () => run(() => sessionStore.reconcileOrphanedAgentGraphRetirements()),
|
|
325
325
|
listPendingSessionRetirementCleanupIds: (sessionId) => run(() => sessionStore.listPendingSessionRetirementCleanupIds(sessionId)),
|
|
326
326
|
completeSessionRetirementCleanup: (sessionId) => run(() => sessionStore.completeSessionRetirementCleanup(sessionId)),
|
|
327
|
+
listArchiveRetentionCandidates: (query) => run(() => sessionStore.listArchiveRetentionCandidates(query)),
|
|
328
|
+
countArchiveRetentionCandidates: (enabledAt) => run(() => sessionStore.countArchiveRetentionCandidates(enabledAt)),
|
|
329
|
+
readLatestSessionMetadataTime: () => run(() => sessionStore.readLatestSessionMetadataTime()),
|
|
327
330
|
close,
|
|
328
331
|
},
|
|
329
332
|
agentRunStore: {
|
|
@@ -22,7 +22,7 @@ import { lookupModelMetadata } from '@maka/core/model-metadata';
|
|
|
22
22
|
import { LegacyModelFactsReader } from '../model-facts-store.js';
|
|
23
23
|
import { randomUUID } from 'node:crypto';
|
|
24
24
|
import { isDeepStrictEqual } from 'node:util';
|
|
25
|
-
import { CONNECTION_CATALOG_MAX_CONNECTIONS, decodeCanonicalConnectionCatalogEntry, decodeConnectionName, decodeConnectionSlug, decodeConnectionTarget, decodeConnectionTestSummary, decodeDefaultApiProtocol, decodeProviderType, decodeRuntimePolicyEntityId, normalizeConnectionCatalogEntryUpdateForProvider, normalizeConnectionModelDiscoveryResult, normalizeCreateCatalogConnectionInput, normalizeRemoveCatalogConnectionInput, normalizeSetDefaultConnectionTargetInput, normalizeUpdateCatalogConnectionInput, } from '@maka/core/runtime-policy';
|
|
25
|
+
import { CONNECTION_CATALOG_MAX_CONNECTIONS, CONNECTION_CATALOG_MAX_ENABLED_MODEL_IDS, decodeCanonicalConnectionCatalogEntry, decodeConnectionName, decodeConnectionSlug, decodeConnectionTarget, decodeConnectionTestSummary, decodeDefaultApiProtocol, decodeProviderType, decodeRuntimePolicyEntityId, normalizeConnectionCatalogEntryUpdateForProvider, normalizeConnectionModelDiscoveryResult, normalizeCreateCatalogConnectionInput, normalizeRemoveCatalogConnectionInput, normalizeSetDefaultConnectionTargetInput, normalizeUpdateCatalogConnectionInput, } from '@maka/core/runtime-policy';
|
|
26
26
|
import { PROVIDER_REGISTRY, reconcileConnectionAfterModelFetch } from '@maka/core/llm-connections';
|
|
27
27
|
import { modelIdAliasesForProvider, providerReportsCompleteModelCatalog, } from '@maka/core/model-metadata';
|
|
28
28
|
import { isRetiredProvider } from '@maka/core/provider-registry';
|
|
@@ -299,9 +299,36 @@ export class ConnectionCatalogDocumentOwner {
|
|
|
299
299
|
if (current.revision !== input.expectedCatalogRevision) {
|
|
300
300
|
return revisionConflict(input.expectedCatalogRevision, current.revision);
|
|
301
301
|
}
|
|
302
|
+
const connections = [...current.connections];
|
|
303
|
+
if (input.target && input.enableModel) {
|
|
304
|
+
const { connectionId, modelId } = input.target;
|
|
305
|
+
const index = connections.findIndex((item) => item.connectionId === connectionId);
|
|
306
|
+
const connection = connections[index];
|
|
307
|
+
if (!connection?.enabled || isRetiredProvider(connection.providerType)) {
|
|
308
|
+
return deepFreeze({ kind: 'invalid_default_target', target: input.target });
|
|
309
|
+
}
|
|
310
|
+
if (!connection.enabledModelIds.includes(modelId)) {
|
|
311
|
+
const model = resolveConnectionModelCatalog({
|
|
312
|
+
...connection,
|
|
313
|
+
models: [...connection.models],
|
|
314
|
+
enabledModelIds: [...connection.enabledModelIds],
|
|
315
|
+
defaultModel: '',
|
|
316
|
+
}).find((entry) => entry.id === modelId);
|
|
317
|
+
if (!model?.canUseAsChatDefault ||
|
|
318
|
+
connection.enabledModelIds.length >= CONNECTION_CATALOG_MAX_ENABLED_MODEL_IDS) {
|
|
319
|
+
return deepFreeze({ kind: 'invalid_default_target', target: input.target });
|
|
320
|
+
}
|
|
321
|
+
const { lastTest: _lastTest, ...withoutTest } = connection;
|
|
322
|
+
connections[index] = {
|
|
323
|
+
...withoutTest,
|
|
324
|
+
revision: nextRevision(connection.revision),
|
|
325
|
+
enabledModelIds: [...connection.enabledModelIds, modelId],
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
}
|
|
302
329
|
// The one call that states a target, so the one place an unusable one is
|
|
303
330
|
// the caller's error rather than a consequence to release.
|
|
304
|
-
if (input.target && !isValidTarget(input.target,
|
|
331
|
+
if (input.target && !isValidTarget(input.target, connections)) {
|
|
305
332
|
return deepFreeze({ kind: 'invalid_default_target', target: input.target });
|
|
306
333
|
}
|
|
307
334
|
// Refused rather than accepted-then-released: committing it would succeed
|
|
@@ -311,11 +338,11 @@ export class ConnectionCatalogDocumentOwner {
|
|
|
311
338
|
current.connections.some((item) => item.connectionId === input.target?.connectionId && isRetiredProvider(item.providerType))) {
|
|
312
339
|
return deepFreeze({ kind: 'invalid_default_target', target: input.target });
|
|
313
340
|
}
|
|
314
|
-
const next = this.nextDocument(current,
|
|
341
|
+
const next = this.nextDocument(current, connections, input.target);
|
|
315
342
|
await this.write(root, next);
|
|
316
343
|
return committed(next);
|
|
317
344
|
}
|
|
318
|
-
async writeModelFetchResult(root, current, expected, rawResult) {
|
|
345
|
+
async writeModelFetchResult(root, current, expected, rawResult, preserveSelection = false) {
|
|
319
346
|
const result = decodeConnectionInput(() => normalizeConnectionModelDiscoveryResult(rawResult));
|
|
320
347
|
if (result.models.length === 0) {
|
|
321
348
|
throw codecError('invalid_connection_input', 'Model discovery result must not be empty');
|
|
@@ -328,18 +355,23 @@ export class ConnectionCatalogDocumentOwner {
|
|
|
328
355
|
const currentDefaultTarget = current.defaultTarget?.connectionId === previous.connectionId
|
|
329
356
|
? current.defaultTarget
|
|
330
357
|
: undefined;
|
|
331
|
-
const reconciled =
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
358
|
+
const reconciled = preserveSelection
|
|
359
|
+
? {
|
|
360
|
+
defaultModel: currentDefaultTarget?.modelId ?? '',
|
|
361
|
+
enabledModelIds: [...previous.enabledModelIds],
|
|
362
|
+
}
|
|
363
|
+
: reconcileConnectionAfterModelFetch({
|
|
364
|
+
defaultModel: currentDefaultTarget?.modelId ?? previous.enabledModelIds[0],
|
|
365
|
+
enabledModelIds: previous.enabledModelIds,
|
|
366
|
+
// An entry always carries a `models` array, so "has an inventory" has
|
|
367
|
+
// to be read off its contents: empty means this connection has never
|
|
368
|
+
// had a list to pick from and discovery may seed one. A non-empty one
|
|
369
|
+
// means an empty selection is the user's answer.
|
|
370
|
+
hasModelInventory: previous.models.length > 0,
|
|
371
|
+
}, result.models, {
|
|
372
|
+
aliases: modelIdAliasesForProvider(previous.providerType),
|
|
373
|
+
authoritative: providerReportsCompleteModelCatalog(previous.providerType),
|
|
374
|
+
});
|
|
343
375
|
// Discovery MOVES a target: a provider's model rename carries the default
|
|
344
376
|
// across by alias. A default outside the selection the reconciler just
|
|
345
377
|
// decided is its own bug — fail closed where it is still attributable.
|
|
@@ -780,7 +780,7 @@ export class RuntimePolicyCoordinator {
|
|
|
780
780
|
});
|
|
781
781
|
});
|
|
782
782
|
}
|
|
783
|
-
async completeModelFetch(ticket, result) {
|
|
783
|
+
async completeModelFetch(ticket, result, preserveSelection = false) {
|
|
784
784
|
const claimed = this.claimTicket(ticket, 'model_fetch');
|
|
785
785
|
return this.completeClaimedTicket(claimed, () => this.inLane(async (root) => {
|
|
786
786
|
const catalog = await this.catalog.read(root);
|
|
@@ -788,7 +788,7 @@ export class RuntimePolicyCoordinator {
|
|
|
788
788
|
if (checked.changed.length > 0 || !checked.connection) {
|
|
789
789
|
return deepFreeze({ kind: 'superseded', changed: checked.changed });
|
|
790
790
|
}
|
|
791
|
-
const snapshot = await this.catalog.writeModelFetchResult(root, catalog, connectionBasis(checked.connection), result);
|
|
791
|
+
const snapshot = await this.catalog.writeModelFetchResult(root, catalog, connectionBasis(checked.connection), result, preserveSelection);
|
|
792
792
|
return deepFreeze({
|
|
793
793
|
kind: 'committed',
|
|
794
794
|
snapshot: await this.projectCatalogSnapshot(root),
|
|
@@ -26,7 +26,7 @@ export const POLICY_DOCUMENT_MAX_BYTES = 48 * 1024;
|
|
|
26
26
|
export const CATALOG_DOCUMENT_MAX_BYTES = 4 * 1024 * 1024;
|
|
27
27
|
export const VAULT_DOCUMENT_MAX_BYTES = 2 * 1024 * 1024;
|
|
28
28
|
const READ_CHUNK_BYTES = 64 * 1024;
|
|
29
|
-
const RUNTIME_POLICY_TEMP_PATTERN = /^(?:runtime-policy|connection-catalog|credential-vault|runtime-policy-onboarding|runtime-policy-oauth-login-receipts|model-facts)\.json\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/;
|
|
29
|
+
const RUNTIME_POLICY_TEMP_PATTERN = /^(?:runtime-policy|connection-catalog|credential-vault|runtime-policy-onboarding|runtime-policy-oauth-login-receipts|model-facts|archive-retention)\.json\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/;
|
|
30
30
|
export async function cleanupRuntimePolicyDocumentTemps(root) {
|
|
31
31
|
let failure;
|
|
32
32
|
try {
|
|
@@ -121,7 +121,7 @@ function createWriterFacade(coordinator) {
|
|
|
121
121
|
queryInteractiveOAuthLogin: (attemptId) => coordinator.queryInteractiveOAuthLogin(attemptId),
|
|
122
122
|
completeInteractiveOAuthLogin: (ticket, secret) => coordinator.completeInteractiveOAuthLogin(ticket, secret),
|
|
123
123
|
beginModelFetch: (connectionId) => coordinator.beginModelFetch(connectionId),
|
|
124
|
-
completeModelFetch: (ticket, result) => coordinator.completeModelFetch(ticket, result),
|
|
124
|
+
completeModelFetch: (ticket, result, preserveSelection) => coordinator.completeModelFetch(ticket, result, preserveSelection),
|
|
125
125
|
beginConnectionOnboarding: (input) => coordinator.beginConnectionOnboarding(input),
|
|
126
126
|
completeConnectionOnboarding: (ticket, input) => coordinator.completeConnectionOnboarding(ticket, input),
|
|
127
127
|
beginConnectionTest: (connectionId, modelId) => coordinator.beginConnectionTest(connectionId, modelId),
|
|
@@ -998,6 +998,15 @@ function mergeAttachedBundle(target) {
|
|
|
998
998
|
const quoted = quoteIdentifier(name);
|
|
999
999
|
target.exec(`INSERT INTO main.${quoted} SELECT * FROM bundle.${quoted}`);
|
|
1000
1000
|
}
|
|
1001
|
+
// An archived Session arrives with the archive time (or no time) of the
|
|
1002
|
+
// machine it left. Archive retention counts from that time, so an import
|
|
1003
|
+
// could be deleted at once; its clock starts at the import instead.
|
|
1004
|
+
target
|
|
1005
|
+
.prepare(`UPDATE main.session_metadata
|
|
1006
|
+
SET archived_at = ?
|
|
1007
|
+
WHERE is_archived = 1
|
|
1008
|
+
AND session_id IN (SELECT session_id FROM bundle.session_metadata)`)
|
|
1009
|
+
.run(Date.now());
|
|
1001
1010
|
const violation = target.prepare('PRAGMA foreign_key_check').get();
|
|
1002
1011
|
if (violation) {
|
|
1003
1012
|
throw new SessionBundleImportError('conflict', 'Imported Sessions would leave dangling references');
|
|
@@ -509,6 +509,23 @@ class SqliteSessionStore {
|
|
|
509
509
|
await this.ensureReady();
|
|
510
510
|
await this.metadata.completeSessionRetirementCleanup(sessionId);
|
|
511
511
|
}
|
|
512
|
+
async listArchiveRetentionCandidates(query) {
|
|
513
|
+
await this.ensureReady();
|
|
514
|
+
return (await this.metadata.listArchiveRetentionCandidates(query)).map((record) => 'undecodable' in record
|
|
515
|
+
? record
|
|
516
|
+
: {
|
|
517
|
+
...projectHeaderSnapshot(record),
|
|
518
|
+
...(record.archivedAt === undefined ? {} : { archivedAt: record.archivedAt }),
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
async countArchiveRetentionCandidates(enabledAt) {
|
|
522
|
+
await this.ensureReady();
|
|
523
|
+
return this.metadata.countArchiveRetentionCandidates(enabledAt);
|
|
524
|
+
}
|
|
525
|
+
async readLatestSessionMetadataTime() {
|
|
526
|
+
await this.ensureReady();
|
|
527
|
+
return this.metadata.readLatestSessionMetadataTime();
|
|
528
|
+
}
|
|
512
529
|
async setFlagged(sessionId, isFlagged) {
|
|
513
530
|
await this.updateHeader(sessionId, { isFlagged });
|
|
514
531
|
}
|
|
@@ -350,6 +350,40 @@ export class SqliteContextOffloadStore {
|
|
|
350
350
|
};
|
|
351
351
|
});
|
|
352
352
|
}
|
|
353
|
+
/**
|
|
354
|
+
* Returns up to `maxPages` free pages to the filesystem with one bounded
|
|
355
|
+
* `incremental_vacuum`. The schema guarantees `auto_vacuum = INCREMENTAL`.
|
|
356
|
+
*/
|
|
357
|
+
async reclaimFreePages(input) {
|
|
358
|
+
assertPositiveSafeInteger(input.maxPages, 'Context page reclamation limit');
|
|
359
|
+
this.#assertOpen();
|
|
360
|
+
// Probe under a read transaction so an idle tick never takes the write lock.
|
|
361
|
+
if (this.#readTransaction(() => this.#freelistPages()) === 0) {
|
|
362
|
+
return { reclaimedPages: 0, hasMore: false };
|
|
363
|
+
}
|
|
364
|
+
const result = this.#writeTransaction(() => {
|
|
365
|
+
const before = this.#freelistPages();
|
|
366
|
+
// incremental_vacuum(0) would free every page, so an emptied list stops here.
|
|
367
|
+
if (before === 0)
|
|
368
|
+
return { reclaimedPages: 0, hasMore: false };
|
|
369
|
+
this.#database.exec(`PRAGMA incremental_vacuum(${Math.min(input.maxPages, before)})`);
|
|
370
|
+
const after = this.#freelistPages();
|
|
371
|
+
// A batch that frees nothing reports no more work instead of spinning the lane.
|
|
372
|
+
return { reclaimedPages: before - after, hasMore: after > 0 && after < before };
|
|
373
|
+
});
|
|
374
|
+
// PASSIVE never waits on readers; it moves the shrink into the main file.
|
|
375
|
+
if (result.reclaimedPages > 0)
|
|
376
|
+
this.#database.exec('PRAGMA wal_checkpoint(PASSIVE)');
|
|
377
|
+
return result;
|
|
378
|
+
}
|
|
379
|
+
#freelistPages() {
|
|
380
|
+
const row = this.#database.prepare('PRAGMA freelist_count').get();
|
|
381
|
+
const pages = row?.freelist_count;
|
|
382
|
+
if (typeof pages !== 'number' || !Number.isSafeInteger(pages) || pages < 0) {
|
|
383
|
+
throw new Error('Invalid SQLite freelist_count');
|
|
384
|
+
}
|
|
385
|
+
return pages;
|
|
386
|
+
}
|
|
353
387
|
async usage(sessionId) {
|
|
354
388
|
if (sessionId !== undefined)
|
|
355
389
|
assertBoundedIdentity(sessionId, 'Session id');
|
|
@@ -17,14 +17,57 @@
|
|
|
17
17
|
* under the License.
|
|
18
18
|
*/
|
|
19
19
|
import { sqliteOrdinarySessionRolePredicate } from './sqlite-session-role-scope.js';
|
|
20
|
+
/**
|
|
21
|
+
* A Session row the catalog lists: ordinary, not a copy still being prepared,
|
|
22
|
+
* and not a transcript-less shell. `alias` names the `session_metadata` row;
|
|
23
|
+
* the caller joins `session_catalog_projection` for it.
|
|
24
|
+
*/
|
|
25
|
+
export function sqliteCatalogVisibleSessionPredicate(alias = 'metadata') {
|
|
26
|
+
const role = sqliteOrdinarySessionRolePredicate(alias);
|
|
27
|
+
return {
|
|
28
|
+
sql: `(
|
|
29
|
+
COALESCE(json_extract(${alias}.payload_json, '$.conversationCopy.state'), '') <> 'preparing'
|
|
30
|
+
AND ${role.sql}
|
|
31
|
+
AND COALESCE(json_extract(${alias}.payload_json, '$.transcriptLedgerVersion'), 1) <> 0
|
|
32
|
+
)`,
|
|
33
|
+
parameters: [...role.parameters],
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A row of Settings › Archived tasks, as the rail derives it from the catalog:
|
|
38
|
+
* an archived catalog-visible Session that is not a linked subtask of another
|
|
39
|
+
* catalog-visible Session. A subtask whose parent is gone is a row of its own.
|
|
40
|
+
* Revision families still collapse to one row; callers group by family.
|
|
41
|
+
* Requires `metadata` joined with its `session_catalog_projection`.
|
|
42
|
+
*/
|
|
43
|
+
export function sqliteArchivedTaskRowPredicate() {
|
|
44
|
+
const row = sqliteCatalogVisibleSessionPredicate('metadata');
|
|
45
|
+
const parent = sqliteCatalogVisibleSessionPredicate('parent');
|
|
46
|
+
return {
|
|
47
|
+
sql: `(
|
|
48
|
+
metadata.is_archived = 1
|
|
49
|
+
AND ${row.sql}
|
|
50
|
+
AND (
|
|
51
|
+
metadata.subagent_parent_session_id IS NULL
|
|
52
|
+
OR NOT EXISTS (
|
|
53
|
+
SELECT 1
|
|
54
|
+
FROM session_metadata parent
|
|
55
|
+
JOIN session_catalog_projection parent_projection
|
|
56
|
+
ON parent_projection.session_id = parent.session_id
|
|
57
|
+
WHERE parent.session_id = metadata.subagent_parent_session_id
|
|
58
|
+
AND ${parent.sql}
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
)`,
|
|
62
|
+
parameters: [...row.parameters, ...parent.parameters],
|
|
63
|
+
};
|
|
64
|
+
}
|
|
20
65
|
export function buildSqliteSessionCatalogPageQuery(filter, cursor) {
|
|
21
66
|
const where = [];
|
|
22
67
|
const parameters = [];
|
|
23
|
-
const
|
|
24
|
-
where.push(
|
|
25
|
-
|
|
26
|
-
parameters.push(...role.parameters);
|
|
27
|
-
where.push("COALESCE(json_extract(metadata.payload_json, '$.transcriptLedgerVersion'), 1) <> 0");
|
|
68
|
+
const visible = sqliteCatalogVisibleSessionPredicate();
|
|
69
|
+
where.push(visible.sql);
|
|
70
|
+
parameters.push(...visible.parameters);
|
|
28
71
|
if (filter.subagentParentSessionId !== undefined) {
|
|
29
72
|
where.push('projection.subagent_parent_session_id = ?');
|
|
30
73
|
parameters.push(filter.subagentParentSessionId);
|