gestalt-mobile 0.65.8 → 0.66.0
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/README.md +22 -0
- package/dist/client/assets/index-BDsGojoG.js +128 -0
- package/dist/client/assets/{index-VDRT2Esv.css → index-DxsD-jG4.css} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/server/cli.js +2 -1
- package/dist/server/server/composition.contracts.js +179 -84
- package/dist/server/server/composition.js +65 -5
- package/dist/server/server/features/sessions/application/session-scratch.js +6 -0
- package/dist/server/server/features/sessions/clean-tmp/endpoint.js +68 -0
- package/dist/server/server/features/sessions/clean-tmp/use-case.js +82 -0
- package/dist/server/server/features/sessions/forget-session/endpoint.js +10 -2
- package/dist/server/server/features/sessions/forget-session/use-case.js +75 -0
- package/dist/server/server/features/sessions/get-session/endpoint.js +2 -1
- package/dist/server/server/features/sessions/list-sessions/endpoint.js +3 -0
- package/dist/server/server/features/sessions/promote-recent-thread/use-case.js +4 -1
- package/dist/server/server/features/sessions/register-routes.js +29 -2
- package/dist/server/server/features/sessions/start-session/endpoint.js +7 -0
- package/dist/server/server/features/sessions/start-session/use-case.js +4 -1
- package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +19 -1
- package/dist/server/server/platform/codex/codex-playwright.js +41 -3
- package/dist/server/server/platform/codex/codex-process-launcher.js +24 -2
- package/dist/server/server/platform/codex/codex-serena.js +2 -1
- package/dist/server/server/platform/codex/managed-playwright.js +48 -36
- package/dist/server/server/platform/codex/session-runtime.js +134 -4
- package/dist/server/server/platform/git/command.js +7 -1
- package/dist/server/server/platform/host-tests/runner.js +47 -6
- package/dist/server/server/platform/kimi/kimi-session-runtime.js +41 -0
- package/dist/server/server/platform/kimi/kimi-web-server-manager.js +13 -17
- package/dist/server/server/platform/maintenance/managed-upgrade.js +2 -1
- package/dist/server/server/platform/persistence/migrate.js +24 -0
- package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +67 -0
- package/dist/server/server/platform/persistence/sqlite-session-repository.js +4 -0
- package/dist/server/server/platform/plans/org-plan-discovery.js +2 -0
- package/dist/server/server/platform/plans/plan-measurement-command.js +5 -1
- package/dist/server/server/platform/retrieval/codex-xerj.js +8 -1
- package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
- package/dist/server/server/platform/retrieval/repository-readiness.js +2 -1
- package/dist/server/server/platform/retrieval/xerj-indexer.js +21 -11
- package/dist/server/server/platform/scratch/child-environment.js +21 -0
- package/dist/server/server/platform/scratch/containment-fence.js +262 -0
- package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +245 -0
- package/dist/server/server/platform/scratch/filesystem-session-scratch.js +360 -0
- package/dist/server/server/platform/scratch/legacy-scratch-layouts.js +22 -0
- package/dist/server/server/platform/scratch/managed-scratch-owner.js +148 -0
- package/dist/server/server/platform/scratch/owned-process-group.js +53 -0
- package/dist/server/server/platform/scratch/owner-fence.js +27 -0
- package/dist/server/server/platform/scratch/scratch-filesystem.js +53 -0
- package/dist/server/server/platform/self-debug/workspace.js +3 -0
- package/dist/server/shared/contracts/session-forget.js +6 -0
- package/dist/server/shared/contracts/tmp-cleanup.js +6 -0
- package/package.json +1 -1
- package/dist/client/assets/index-CKJWzSwH.js +0 -128
|
@@ -49,6 +49,7 @@ class SessionResource {
|
|
|
49
49
|
planMeasurementToken;
|
|
50
50
|
unregister;
|
|
51
51
|
onDisposed;
|
|
52
|
+
scratchLease;
|
|
52
53
|
disposed = false;
|
|
53
54
|
explicitShutdown = false;
|
|
54
55
|
pendingRequests = new Map();
|
|
@@ -123,6 +124,7 @@ export class CodexSessionRuntime {
|
|
|
123
124
|
resolveModelConfig;
|
|
124
125
|
retrieval;
|
|
125
126
|
requireExecutorAdmission;
|
|
127
|
+
scratch;
|
|
126
128
|
/** Trusted read-only port for the current controller-bound child on its owning process. */
|
|
127
129
|
async readExecutorConfiguration(input) {
|
|
128
130
|
const resource = this.sessions.get(input.sessionId);
|
|
@@ -145,7 +147,7 @@ export class CodexSessionRuntime {
|
|
|
145
147
|
// correlated-map constructor shape. Live ownership is `sessions` only.
|
|
146
148
|
_legacyProcesses = undefined, onNotification, onServerRequest, onProcessExit, resolveSkills, planStatusSource, onPlanStatus, planMeasurementBaseUrl,
|
|
147
149
|
// Compatibility slot: blocking app-server requests wait for explicit input.
|
|
148
|
-
_legacyRequestTimeoutMs = undefined, maxPendingRequests = 64, readerCwd, resolveModelConfig, retrieval, requireExecutorAdmission) {
|
|
150
|
+
_legacyRequestTimeoutMs = undefined, maxPendingRequests = 64, readerCwd, resolveModelConfig, retrieval, requireExecutorAdmission, scratch) {
|
|
149
151
|
this.launch = launch;
|
|
150
152
|
this.onNotification = onNotification;
|
|
151
153
|
this.onServerRequest = onServerRequest;
|
|
@@ -159,6 +161,7 @@ export class CodexSessionRuntime {
|
|
|
159
161
|
this.resolveModelConfig = resolveModelConfig;
|
|
160
162
|
this.retrieval = retrieval;
|
|
161
163
|
this.requireExecutorAdmission = requireExecutorAdmission;
|
|
164
|
+
this.scratch = scratch;
|
|
162
165
|
void _legacyProcesses;
|
|
163
166
|
void _legacyRequestTimeoutMs;
|
|
164
167
|
}
|
|
@@ -166,6 +169,9 @@ export class CodexSessionRuntime {
|
|
|
166
169
|
historyReads = new Map();
|
|
167
170
|
childTopologyReads = new Map();
|
|
168
171
|
writerAcquisitions = new Map();
|
|
172
|
+
liveResources = new Map();
|
|
173
|
+
resourceCreations = new Map();
|
|
174
|
+
resourceReleases = new Map();
|
|
169
175
|
/** Current runtime observations only; durable workspace selection is never rewritten. */
|
|
170
176
|
async readRetrievalReadiness(sessionId) {
|
|
171
177
|
const resource = this.sessions.get(sessionId);
|
|
@@ -198,6 +204,7 @@ export class CodexSessionRuntime {
|
|
|
198
204
|
if (resource.retrieval)
|
|
199
205
|
this.retrieval?.bound?.(resource.retrieval, startedThreadId);
|
|
200
206
|
await this.verifyRetrieval(resource, session, true);
|
|
207
|
+
await this.scratch?.associateProviderThread(session, 'codex', resource.threadId);
|
|
201
208
|
this.sessions.set(session.id, resource);
|
|
202
209
|
await this.writePendingThreadName(session.id);
|
|
203
210
|
return this.withEffectiveRetrieval(RelaySession.rehydrate(session)
|
|
@@ -213,6 +220,87 @@ export class CodexSessionRuntime {
|
|
|
213
220
|
const resource = this.sessions.get(sessionId);
|
|
214
221
|
resource?.beginExplicitShutdown();
|
|
215
222
|
resource?.dispose();
|
|
223
|
+
if (resource)
|
|
224
|
+
void this.confirmResourceRelease(resource).catch(() => undefined);
|
|
225
|
+
}
|
|
226
|
+
/** Forget requires actual release, including resources still starting or already closing. */
|
|
227
|
+
async releaseForForget(session) {
|
|
228
|
+
for (const resource of this.liveResources.get(session.id) ?? []) {
|
|
229
|
+
resource.beginExplicitShutdown();
|
|
230
|
+
if (resource.active) {
|
|
231
|
+
if (session.activeTurnId)
|
|
232
|
+
await this.interruptTurn(session, session.activeTurnId);
|
|
233
|
+
if (resource.childThreads.size > 64)
|
|
234
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
235
|
+
for (const threadId of resource.childThreads)
|
|
236
|
+
await this.interruptExecutor(session, threadId);
|
|
237
|
+
for (const claim of [...resource.ownedChildProcesses.values()]) {
|
|
238
|
+
if (!['running', 'detached-active'].includes(claim.state))
|
|
239
|
+
continue;
|
|
240
|
+
const present = async () => {
|
|
241
|
+
const result = asRecord(await resource.process.rpc.request('thread/backgroundTerminals/list', {
|
|
242
|
+
threadId: claim.ownerThreadId,
|
|
243
|
+
limit: 64,
|
|
244
|
+
}));
|
|
245
|
+
if (!Array.isArray(result?.data) ||
|
|
246
|
+
result.data.length > 64 ||
|
|
247
|
+
result.nextCursor ||
|
|
248
|
+
result.data.some((item) => !boundedString(asRecord(item)?.processId, 256) ||
|
|
249
|
+
!boundedString(asRecord(item)?.itemId, 256)))
|
|
250
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
251
|
+
return result.data.some((item) => asRecord(item)?.processId === claim.processId &&
|
|
252
|
+
asRecord(item)?.itemId === claim.itemId);
|
|
253
|
+
};
|
|
254
|
+
if (await present()) {
|
|
255
|
+
const stopped = asRecord(await resource.process.rpc.request('thread/backgroundTerminals/terminate', {
|
|
256
|
+
threadId: claim.ownerThreadId,
|
|
257
|
+
processId: claim.processId,
|
|
258
|
+
}));
|
|
259
|
+
if (stopped?.terminated !== true || (await present()))
|
|
260
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
261
|
+
}
|
|
262
|
+
resource.ownedChildProcesses.delete(childProcessKey(claim.ownerThreadId, claim.processId));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
resource.dispose();
|
|
266
|
+
}
|
|
267
|
+
await Promise.allSettled([
|
|
268
|
+
...(this.resourceCreations.get(session.id) ?? []),
|
|
269
|
+
...[this.writerAcquisitions.get(session.id)].filter((item) => item !== undefined),
|
|
270
|
+
]);
|
|
271
|
+
for (const resource of this.liveResources.get(session.id) ?? []) {
|
|
272
|
+
resource.beginExplicitShutdown();
|
|
273
|
+
resource.dispose();
|
|
274
|
+
await this.confirmResourceRelease(resource, true);
|
|
275
|
+
}
|
|
276
|
+
this.retrieval?.release?.(session.id);
|
|
277
|
+
}
|
|
278
|
+
confirmResourceRelease(resource, strict = false) {
|
|
279
|
+
const prior = this.resourceReleases.get(resource);
|
|
280
|
+
if (prior)
|
|
281
|
+
return prior;
|
|
282
|
+
const task = (async () => {
|
|
283
|
+
if (!resource.process.closeAndWait) {
|
|
284
|
+
if (strict || resource.scratchLease)
|
|
285
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
await resource.process.closeAndWait();
|
|
289
|
+
if ([...resource.ownedChildProcesses.values()].some((claim) => ['running', 'detached-active'].includes(claim.state)))
|
|
290
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
291
|
+
await resource.scratchLease?.release();
|
|
292
|
+
const live = this.liveResources.get(resource.sessionId);
|
|
293
|
+
live?.delete(resource);
|
|
294
|
+
if (!live?.size)
|
|
295
|
+
this.liveResources.delete(resource.sessionId);
|
|
296
|
+
})();
|
|
297
|
+
this.resourceReleases.set(resource, task);
|
|
298
|
+
void task
|
|
299
|
+
.finally(() => {
|
|
300
|
+
this.resourceReleases.delete(resource);
|
|
301
|
+
})
|
|
302
|
+
.catch(() => undefined);
|
|
303
|
+
return task;
|
|
216
304
|
}
|
|
217
305
|
async release(sessionId) {
|
|
218
306
|
const resource = this.sessions.get(sessionId);
|
|
@@ -242,11 +330,20 @@ export class CodexSessionRuntime {
|
|
|
242
330
|
const resources = [...this.sessions.values()];
|
|
243
331
|
for (const resource of resources)
|
|
244
332
|
resource.beginExplicitShutdown();
|
|
245
|
-
for (const resource of resources)
|
|
333
|
+
for (const resource of resources) {
|
|
246
334
|
resource.dispose();
|
|
335
|
+
void this.confirmResourceRelease(resource).catch(() => undefined);
|
|
336
|
+
}
|
|
247
337
|
for (const resource of resources)
|
|
248
338
|
this.retrieval?.release?.(resource.sessionId);
|
|
249
339
|
}
|
|
340
|
+
async drainReleases() {
|
|
341
|
+
await Promise.allSettled([...this.liveResources.values()].flatMap((resources) => [...resources].map((resource) => {
|
|
342
|
+
resource.beginExplicitShutdown();
|
|
343
|
+
resource.dispose();
|
|
344
|
+
return this.confirmResourceRelease(resource);
|
|
345
|
+
})));
|
|
346
|
+
}
|
|
250
347
|
/** Keeps a detached session's supervised-plan status observable without launching Codex. */
|
|
251
348
|
async watchPlanStatus(session) {
|
|
252
349
|
if (!this.planStatusSource)
|
|
@@ -292,6 +389,7 @@ export class CodexSessionRuntime {
|
|
|
292
389
|
return pending && !pending.settling ? 'available' : 'cleared';
|
|
293
390
|
}
|
|
294
391
|
async startTurn(session, text, clientUserMessageId, now, mayStart) {
|
|
392
|
+
this.scratch?.assertAvailable?.(session.id);
|
|
295
393
|
const resumeRequested = this.retrieval?.needsResume?.(session);
|
|
296
394
|
if (resumeRequested === true || (resumeRequested && (await resumeRequested))) {
|
|
297
395
|
// The same root resumes only at an idle boundary. Never recycle a writer
|
|
@@ -430,6 +528,7 @@ export class CodexSessionRuntime {
|
|
|
430
528
|
return this.sessions.get(sessionId)?.active === true;
|
|
431
529
|
}
|
|
432
530
|
async ensureWriter(session, now) {
|
|
531
|
+
this.scratch?.assertAvailable?.(session.id);
|
|
433
532
|
if (this.ownsWriter(session.id))
|
|
434
533
|
return { session, replacementCreated: false };
|
|
435
534
|
const inflight = this.writerAcquisitions.get(session.id);
|
|
@@ -637,6 +736,7 @@ export class CodexSessionRuntime {
|
|
|
637
736
|
return true;
|
|
638
737
|
}
|
|
639
738
|
async queueTurnInput(session, turnId, text, clientUserMessageId) {
|
|
739
|
+
this.scratch?.assertAvailable?.(session.id);
|
|
640
740
|
const resource = this.sessions.get(session.id);
|
|
641
741
|
if (!resource || !session.threadId)
|
|
642
742
|
throw new Error('CODEX_SESSION_NOT_RUNNING');
|
|
@@ -1208,6 +1308,7 @@ export class CodexSessionRuntime {
|
|
|
1208
1308
|
if (resource.retrieval)
|
|
1209
1309
|
this.retrieval?.bound?.(resource.retrieval, resource.threadId);
|
|
1210
1310
|
await this.verifyRetrieval(resource, session, result.replacementCreated);
|
|
1311
|
+
await this.scratch?.associateProviderThread(session, 'codex', resource.threadId);
|
|
1211
1312
|
if (result.replacementCreated && resource.threadId !== result.session.threadId)
|
|
1212
1313
|
result = rebindMissingRollout(session, missingRollout, resource.threadId, now);
|
|
1213
1314
|
this.sessions.get(session.id)?.dispose();
|
|
@@ -1310,21 +1411,42 @@ export class CodexSessionRuntime {
|
|
|
1310
1411
|
? { permissions: 'workspace-git' }
|
|
1311
1412
|
: { sandbox: selection };
|
|
1312
1413
|
}
|
|
1313
|
-
|
|
1414
|
+
createResource(session) {
|
|
1415
|
+
this.scratch?.assertAvailable?.(session.id);
|
|
1416
|
+
const task = this.createResourceInner(session);
|
|
1417
|
+
const pending = this.resourceCreations.get(session.id) ?? new Set();
|
|
1418
|
+
pending.add(task);
|
|
1419
|
+
this.resourceCreations.set(session.id, pending);
|
|
1420
|
+
void task
|
|
1421
|
+
.finally(() => {
|
|
1422
|
+
pending.delete(task);
|
|
1423
|
+
if (!pending.size)
|
|
1424
|
+
this.resourceCreations.delete(session.id);
|
|
1425
|
+
})
|
|
1426
|
+
.catch(() => undefined);
|
|
1427
|
+
return task;
|
|
1428
|
+
}
|
|
1429
|
+
async createResourceInner(session) {
|
|
1314
1430
|
const deadline = xerjDeadline();
|
|
1315
1431
|
const lease = this.planStatusSource
|
|
1316
1432
|
? await this.planStatusSource.open({ id: session.id, workspacePath: session.workspacePath }, (update) => this.onPlanStatus?.(session.id, update))
|
|
1317
1433
|
: undefined;
|
|
1434
|
+
let borrowed;
|
|
1435
|
+
let launched = false;
|
|
1318
1436
|
try {
|
|
1319
1437
|
const token = randomUUID();
|
|
1320
1438
|
const skillsConfig = await this.resolveSkills?.(session);
|
|
1321
1439
|
const modelConfig = (await this.resolveModelConfig?.(session)) ?? {};
|
|
1440
|
+
const scratch = await this.scratch?.allocate(session);
|
|
1441
|
+
const scratchLease = (borrowed = await this.scratch?.borrow?.(session));
|
|
1442
|
+
this.scratch?.assertAvailable?.(session.id);
|
|
1322
1443
|
const process = this.launch({
|
|
1323
1444
|
profile: session.profile,
|
|
1324
1445
|
cwd: session.workspacePath,
|
|
1325
|
-
...(lease || this.planMeasurementBaseUrl
|
|
1446
|
+
...(lease || this.planMeasurementBaseUrl || scratch
|
|
1326
1447
|
? {
|
|
1327
1448
|
environment: {
|
|
1449
|
+
...scratch?.environment,
|
|
1328
1450
|
...(lease
|
|
1329
1451
|
? {
|
|
1330
1452
|
GESTALT_MOBILE_ORG_PLAN_STATUS_DIRECTORY: lease.statusDirectory,
|
|
@@ -1345,12 +1467,18 @@ export class CodexSessionRuntime {
|
|
|
1345
1467
|
if (this.sessions.get(session.id) === resource)
|
|
1346
1468
|
this.sessions.delete(session.id);
|
|
1347
1469
|
});
|
|
1470
|
+
launched = true;
|
|
1471
|
+
resource.scratchLease = scratchLease;
|
|
1472
|
+
const live = this.liveResources.get(session.id) ?? new Set();
|
|
1473
|
+
live.add(resource);
|
|
1474
|
+
this.liveResources.set(session.id, live);
|
|
1348
1475
|
resource.readinessDeadline = deadline;
|
|
1349
1476
|
// Own process exit before resume/initialization can make this resource appear healthy.
|
|
1350
1477
|
// A short-lived child could otherwise leave a durable ready session without a writer.
|
|
1351
1478
|
const exitUnsubscribe = process.onExit?.(() => {
|
|
1352
1479
|
if (resource.dispose() && resource.exitedUnexpectedly)
|
|
1353
1480
|
this.onProcessExit?.(session.id);
|
|
1481
|
+
void this.confirmResourceRelease(resource).catch(() => undefined);
|
|
1354
1482
|
}) ?? (() => { });
|
|
1355
1483
|
resource.attach([exitUnsubscribe]);
|
|
1356
1484
|
if (!resource.active) {
|
|
@@ -1468,6 +1596,8 @@ export class CodexSessionRuntime {
|
|
|
1468
1596
|
return resource;
|
|
1469
1597
|
}
|
|
1470
1598
|
catch (error) {
|
|
1599
|
+
if (borrowed && !launched)
|
|
1600
|
+
await borrowed.release();
|
|
1471
1601
|
lease?.close();
|
|
1472
1602
|
throw error;
|
|
1473
1603
|
}
|
|
@@ -5,9 +5,15 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { execFile } from 'node:child_process';
|
|
7
7
|
import { promisify } from 'node:util';
|
|
8
|
+
import { withoutSessionScratch } from '../scratch/child-environment.js';
|
|
8
9
|
const execute = promisify(execFile);
|
|
9
10
|
export const GIT_READ_TIMEOUT_MS = 15_000;
|
|
10
11
|
export const GIT_FETCH_TIMEOUT_MS = 120_000;
|
|
11
12
|
export async function git(cwd, args, timeoutMs = GIT_READ_TIMEOUT_MS) {
|
|
12
|
-
return (await execute('git', args, {
|
|
13
|
+
return (await execute('git', args, {
|
|
14
|
+
cwd,
|
|
15
|
+
env: withoutSessionScratch(),
|
|
16
|
+
shell: false,
|
|
17
|
+
timeout: timeoutMs,
|
|
18
|
+
})).stdout;
|
|
13
19
|
}
|
|
@@ -9,6 +9,8 @@ import { closeSync, openSync, writeSync } from 'node:fs';
|
|
|
9
9
|
import { lstat, mkdir, readFile, readdir, realpath, rename, writeFile } from 'node:fs/promises';
|
|
10
10
|
import { join } from 'node:path';
|
|
11
11
|
import { candidate } from './candidate.js';
|
|
12
|
+
import { stopOwnedProcessGroup } from '../scratch/owned-process-group.js';
|
|
13
|
+
import { withoutSessionScratch } from '../scratch/child-environment.js';
|
|
12
14
|
import { loadWorkspaceHostTestConfig, within } from './config.js';
|
|
13
15
|
// The host owns a lifetime pipe; even a host crash closes it. Tests cannot inherit
|
|
14
16
|
// that pipe or the IPC channel. The guardian reaps its own group, never a stored PID.
|
|
@@ -29,6 +31,7 @@ export class LocalHostTestRunner {
|
|
|
29
31
|
evidenceRoot;
|
|
30
32
|
completed;
|
|
31
33
|
workspaceSuites;
|
|
34
|
+
scratch;
|
|
32
35
|
results = new Map();
|
|
33
36
|
active = new Map();
|
|
34
37
|
reservations = new Set();
|
|
@@ -36,10 +39,11 @@ export class LocalHostTestRunner {
|
|
|
36
39
|
resultReads = new Map();
|
|
37
40
|
sessionGenerations = new Map();
|
|
38
41
|
closing = false;
|
|
39
|
-
constructor(evidenceRoot, completed = () => { }, workspaceSuites = loadWorkspaceHostTestConfig) {
|
|
42
|
+
constructor(evidenceRoot, completed = () => { }, workspaceSuites = loadWorkspaceHostTestConfig, scratch) {
|
|
40
43
|
this.evidenceRoot = evidenceRoot;
|
|
41
44
|
this.completed = completed;
|
|
42
45
|
this.workspaceSuites = workspaceSuites;
|
|
46
|
+
this.scratch = scratch;
|
|
43
47
|
}
|
|
44
48
|
async initialize() {
|
|
45
49
|
if (process.platform !== 'linux' && process.platform !== 'darwin')
|
|
@@ -207,7 +211,22 @@ export class LocalHostTestRunner {
|
|
|
207
211
|
return structuredClone(result);
|
|
208
212
|
}
|
|
209
213
|
try {
|
|
210
|
-
this.
|
|
214
|
+
const scratch = await this.scratch?.allocate({
|
|
215
|
+
id: owner.sessionId,
|
|
216
|
+
workspacePath: owner.workspace,
|
|
217
|
+
});
|
|
218
|
+
const claim = await this.scratch?.borrow?.({
|
|
219
|
+
id: owner.sessionId,
|
|
220
|
+
workspacePath: owner.workspace,
|
|
221
|
+
});
|
|
222
|
+
try {
|
|
223
|
+
this.scratch?.assertAvailable?.(owner.sessionId);
|
|
224
|
+
this.launch(suite, result, scratch?.environment, claim);
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
await claim?.release();
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
211
230
|
}
|
|
212
231
|
catch {
|
|
213
232
|
result.state = 'interrupted';
|
|
@@ -220,17 +239,30 @@ export class LocalHostTestRunner {
|
|
|
220
239
|
this.reservations.delete(suite.repository);
|
|
221
240
|
}
|
|
222
241
|
}
|
|
223
|
-
launch(suite, result) {
|
|
242
|
+
launch(suite, result, scratchEnvironment, scratchLease) {
|
|
224
243
|
const fd = openSync(result.logPath, 'wx', 0o600);
|
|
225
244
|
const hash = createHash('sha256');
|
|
226
245
|
// No provider keys, relay tokens, hooks, NODE_OPTIONS or shell startup variables.
|
|
227
246
|
const env = {};
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
247
|
+
const independent = withoutSessionScratch();
|
|
248
|
+
for (const key of [
|
|
249
|
+
'PATH',
|
|
250
|
+
'HOME',
|
|
251
|
+
'USER',
|
|
252
|
+
'LOGNAME',
|
|
253
|
+
'LANG',
|
|
254
|
+
'LC_ALL',
|
|
255
|
+
'TZ',
|
|
256
|
+
'TMPDIR',
|
|
257
|
+
'TMP',
|
|
258
|
+
'TEMP',
|
|
259
|
+
]) {
|
|
260
|
+
if (independent[key] !== undefined)
|
|
261
|
+
env[key] = independent[key];
|
|
231
262
|
}
|
|
232
263
|
env.CI = '1';
|
|
233
264
|
env.NO_COLOR = '1';
|
|
265
|
+
Object.assign(env, scratchEnvironment);
|
|
234
266
|
let child;
|
|
235
267
|
try {
|
|
236
268
|
child = spawn(process.execPath, ['-e', guardian, suite.command, JSON.stringify(suite.args), suite.repository], {
|
|
@@ -292,6 +324,15 @@ export class LocalHostTestRunner {
|
|
|
292
324
|
clearTimeout(timeout);
|
|
293
325
|
closeSync(fd);
|
|
294
326
|
void (async () => {
|
|
327
|
+
if (scratchLease) {
|
|
328
|
+
try {
|
|
329
|
+
if (await stopOwnedProcessGroup(child, 0, 1000))
|
|
330
|
+
await scratchLease.release();
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
/* Unknown release remains a durable protected lease. */
|
|
334
|
+
}
|
|
335
|
+
}
|
|
295
336
|
const terminal = structuredClone(result);
|
|
296
337
|
terminal.outputSha256 = hash.digest('hex');
|
|
297
338
|
try {
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
6
|
import { createHash, randomUUID } from 'node:crypto';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
8
|
import { RelaySession, } from '../../features/sessions/model/relay-session.js';
|
|
8
9
|
import { normalizeSkillProfileName, } from '../../features/skills/model/skill-profile.js';
|
|
9
10
|
import { WriterAcquisitionError, } from '../../features/sessions/application/writer-acquisition.js';
|
|
@@ -67,6 +68,43 @@ export class KimiSessionRuntime {
|
|
|
67
68
|
resource.explicitShutdown = true;
|
|
68
69
|
await this.detach(sessionId);
|
|
69
70
|
}
|
|
71
|
+
async releaseForForget(session) {
|
|
72
|
+
await this.writerAcquisitions.get(session.id)?.catch(() => undefined);
|
|
73
|
+
const resource = this.sessions.get(session.id);
|
|
74
|
+
if (!resource)
|
|
75
|
+
return;
|
|
76
|
+
resource.explicitShutdown = true;
|
|
77
|
+
// Kimi scratch belongs to the shared service. Do not stop or relocate that
|
|
78
|
+
// service when retiring one relay claim; abort only this session's prompt.
|
|
79
|
+
const handle = this.input.servers.get(resource.profileKey);
|
|
80
|
+
if (!handle)
|
|
81
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
82
|
+
const read = async () => (await handle.client.get(`/api/v1/sessions/${resource.threadId}`));
|
|
83
|
+
let status = await read();
|
|
84
|
+
const prompts = new Set(resource.pendingPrompts);
|
|
85
|
+
if (resource.activePromptId)
|
|
86
|
+
prompts.add(resource.activePromptId);
|
|
87
|
+
if (status.main_turn_active === true) {
|
|
88
|
+
if (typeof status.current_prompt_id !== 'string' ||
|
|
89
|
+
status.current_prompt_id.length > 256 ||
|
|
90
|
+
!status.current_prompt_id)
|
|
91
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
92
|
+
prompts.add(status.current_prompt_id);
|
|
93
|
+
}
|
|
94
|
+
if (prompts.size > 64)
|
|
95
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
96
|
+
for (const prompt of prompts)
|
|
97
|
+
await handle.client.post(`/api/v1/sessions/${resource.threadId}/prompts/${encodeURIComponent(prompt)}:abort`);
|
|
98
|
+
for (let attempt = 0; prompts.size && status.main_turn_active === true && attempt < 50; attempt++) {
|
|
99
|
+
await delay(20);
|
|
100
|
+
status = await read();
|
|
101
|
+
}
|
|
102
|
+
if (status.main_turn_active !== false)
|
|
103
|
+
throw new Error('SESSION_RELEASE_UNCONFIRMED');
|
|
104
|
+
const connection = this.connections.get(resource.profileKey);
|
|
105
|
+
await connection?.client.unsubscribe([resource.threadId]);
|
|
106
|
+
await this.detach(session.id);
|
|
107
|
+
}
|
|
70
108
|
async recycle(session, now) {
|
|
71
109
|
this.stop(session.id);
|
|
72
110
|
return this.restore(session, now);
|
|
@@ -242,6 +280,7 @@ export class KimiSessionRuntime {
|
|
|
242
280
|
return `sel-${createHash('sha256').update(canonical).digest('hex').slice(0, 12)}`;
|
|
243
281
|
}
|
|
244
282
|
async ensureServer(session) {
|
|
283
|
+
await this.input.scratch?.allocate(session);
|
|
245
284
|
// A recent thread imported from a running Kimi server carries that server's
|
|
246
285
|
// profile key in `profile`, but no reconstructable effective skill selection.
|
|
247
286
|
// Reuse its exact owner; never collapse it onto the default server or restart
|
|
@@ -264,6 +303,7 @@ export class KimiSessionRuntime {
|
|
|
264
303
|
});
|
|
265
304
|
}
|
|
266
305
|
async attachResource(session, threadId, handle) {
|
|
306
|
+
await this.input.scratch?.associateProviderThread(session, 'kimi', threadId);
|
|
267
307
|
await this.detach(session.id);
|
|
268
308
|
const resource = {
|
|
269
309
|
sessionId: session.id,
|
|
@@ -485,6 +525,7 @@ export class KimiSessionRuntime {
|
|
|
485
525
|
}
|
|
486
526
|
}
|
|
487
527
|
requireResource(session) {
|
|
528
|
+
this.input.scratch?.assertAvailable?.(session.id);
|
|
488
529
|
const resource = this.sessions.get(session.id);
|
|
489
530
|
if (!resource || !session.threadId)
|
|
490
531
|
throw new Error(KIMI_SESSION_NOT_RUNNING);
|
|
@@ -9,6 +9,8 @@ import { KimiWebClient } from './kimi-web-client.js';
|
|
|
9
9
|
import { boundMessage } from './kimi-errors.js';
|
|
10
10
|
import { prepareKimiShareDir } from './kimi-share-dir.js';
|
|
11
11
|
import { materializeKimiSkillsDir } from './kimi-skills-materializer.js';
|
|
12
|
+
import { withoutSessionScratch } from '../scratch/child-environment.js';
|
|
13
|
+
import { stopOwnedProcessGroup } from '../scratch/owned-process-group.js';
|
|
12
14
|
const READINESS_TIMEOUT_MS = 15_000;
|
|
13
15
|
const READINESS_POLL_MS = 100;
|
|
14
16
|
const LOG_TAIL_BYTES = 4 * 1024;
|
|
@@ -78,10 +80,8 @@ export class KimiWebServerManager {
|
|
|
78
80
|
if (!server)
|
|
79
81
|
return;
|
|
80
82
|
this.servers.delete(profileKey);
|
|
81
|
-
if (
|
|
82
|
-
server.
|
|
83
|
-
await waitForExit(server.child, 3_000);
|
|
84
|
-
}
|
|
83
|
+
if (await stopOwnedProcessGroup(server.child, 3000))
|
|
84
|
+
await server.scratch?.release();
|
|
85
85
|
for (const listener of server.exitListeners)
|
|
86
86
|
listener();
|
|
87
87
|
}
|
|
@@ -97,11 +97,13 @@ export class KimiWebServerManager {
|
|
|
97
97
|
materializeKimiSkillsDir(skillsDir, selection);
|
|
98
98
|
const port = await pickFreePort(this.input.startPort ?? BASE_PORT);
|
|
99
99
|
const baseUrl = `http://127.0.0.1:${port}`;
|
|
100
|
+
const scratch = await this.input.serviceScratch?.(profileKey);
|
|
100
101
|
const child = (this.input.spawnImpl ?? spawn)(this.input.command ?? 'kimi', ['web', '--no-open', '--port', String(port)], {
|
|
101
102
|
cwd: shareDir,
|
|
102
|
-
env: kimiChildEnvironment({ KIMI_SHARE_DIR: shareDir }),
|
|
103
|
+
env: kimiChildEnvironment({ KIMI_SHARE_DIR: shareDir, ...scratch?.environment }),
|
|
103
104
|
shell: false,
|
|
104
105
|
stdio: 'pipe',
|
|
106
|
+
detached: true,
|
|
105
107
|
});
|
|
106
108
|
const server = {
|
|
107
109
|
profileKey,
|
|
@@ -118,8 +120,13 @@ export class KimiWebServerManager {
|
|
|
118
120
|
exitListeners: new Set(),
|
|
119
121
|
exited: false,
|
|
120
122
|
logTail: '',
|
|
123
|
+
scratch,
|
|
121
124
|
};
|
|
122
125
|
this.servers.set(profileKey, server);
|
|
126
|
+
child.once('exit', () => {
|
|
127
|
+
server.exited = true;
|
|
128
|
+
// Unexpected exit cannot prove its descendants stopped. Keep the lease protected.
|
|
129
|
+
});
|
|
123
130
|
try {
|
|
124
131
|
server.handle.token = await waitForServerReady(server);
|
|
125
132
|
server.handle.client = new KimiWebClient(baseUrl, server.handle.token, this.input.fetchImpl);
|
|
@@ -142,7 +149,7 @@ export class KimiWebServerManager {
|
|
|
142
149
|
}
|
|
143
150
|
/** Prevents relay state from leaking into kimi web children, and pins KIMI_SHARE_DIR. */
|
|
144
151
|
export function kimiChildEnvironment(overrides) {
|
|
145
|
-
const inherited =
|
|
152
|
+
const inherited = withoutSessionScratch();
|
|
146
153
|
delete inherited.GESTALT_MOBILE_ORG_PLAN_CAPABILITIES;
|
|
147
154
|
delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_FILE;
|
|
148
155
|
delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_DIRECTORY;
|
|
@@ -200,17 +207,6 @@ async function waitForServerReady(server) {
|
|
|
200
207
|
clearTimeout(timeout);
|
|
201
208
|
}
|
|
202
209
|
}
|
|
203
|
-
function waitForExit(child, timeoutMs) {
|
|
204
|
-
if (child.exitCode !== null || child.signalCode !== null)
|
|
205
|
-
return Promise.resolve();
|
|
206
|
-
return new Promise((resolve) => {
|
|
207
|
-
const timer = setTimeout(resolve, timeoutMs);
|
|
208
|
-
child.once('exit', () => {
|
|
209
|
-
clearTimeout(timer);
|
|
210
|
-
resolve();
|
|
211
|
-
});
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
210
|
function delay(ms) {
|
|
215
211
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
216
212
|
}
|
|
@@ -8,6 +8,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
8
8
|
import { access } from 'node:fs/promises';
|
|
9
9
|
import { dirname, join } from 'node:path';
|
|
10
10
|
import { promisify } from 'node:util';
|
|
11
|
+
import { withoutSessionScratch } from '../scratch/child-environment.js';
|
|
11
12
|
const runFile = promisify(execFile);
|
|
12
13
|
export class ManagedUpgrade {
|
|
13
14
|
cwd;
|
|
@@ -50,7 +51,7 @@ export class ManagedUpgrade {
|
|
|
50
51
|
this.current = { instanceId: this.current.instanceId, phase: 'updating' };
|
|
51
52
|
this.starting = this.run(this.environment.GESTALT_MANAGER_BIN || 'gestalt', ['update-restart'], {
|
|
52
53
|
cwd: this.cwd,
|
|
53
|
-
env: this.environment,
|
|
54
|
+
env: withoutSessionScratch(this.environment),
|
|
54
55
|
timeout: 15_000,
|
|
55
56
|
maxBuffer: 64 * 1024,
|
|
56
57
|
})
|
|
@@ -28,6 +28,30 @@ function migrateWorkspaceGitDefaults(database) {
|
|
|
28
28
|
}
|
|
29
29
|
export function migrate(database) {
|
|
30
30
|
database.exec(schema);
|
|
31
|
+
database.exec(`CREATE TABLE IF NOT EXISTS session_forget_operations (
|
|
32
|
+
session_id TEXT PRIMARY KEY CHECK(length(session_id) BETWEEN 1 AND 256),
|
|
33
|
+
operation_id TEXT NOT NULL UNIQUE CHECK(length(operation_id) = 36),
|
|
34
|
+
phase TEXT NOT NULL CHECK(phase IN ('stopping','cleaning','finalizing','failed','completed')),
|
|
35
|
+
updated_at TEXT NOT NULL CHECK(length(updated_at) <= 32),
|
|
36
|
+
failure_code TEXT CHECK(failure_code IS NULL OR failure_code IN ('SESSION_RELEASE_UNCONFIRMED','SESSION_CLEANUP_FAILED','SESSION_FORGET_FAILED'))
|
|
37
|
+
);
|
|
38
|
+
CREATE TRIGGER IF NOT EXISTS forget_fence_insert BEFORE INSERT ON relay_sessions
|
|
39
|
+
WHEN EXISTS (SELECT 1 FROM session_forget_operations WHERE session_id = NEW.id)
|
|
40
|
+
BEGIN SELECT RAISE(IGNORE); END;
|
|
41
|
+
CREATE TRIGGER IF NOT EXISTS forget_fence_update BEFORE UPDATE ON relay_sessions
|
|
42
|
+
WHEN EXISTS (SELECT 1 FROM session_forget_operations WHERE session_id = NEW.id)
|
|
43
|
+
BEGIN SELECT RAISE(IGNORE); END;`);
|
|
44
|
+
database.exec(`CREATE TABLE IF NOT EXISTS scratch_known_workspaces (
|
|
45
|
+
workspace_path TEXT PRIMARY KEY
|
|
46
|
+
); INSERT OR IGNORE INTO scratch_known_workspaces (workspace_path)
|
|
47
|
+
SELECT DISTINCT workspace_path FROM relay_sessions;
|
|
48
|
+
CREATE TRIGGER IF NOT EXISTS scratch_workspace_on_insert AFTER INSERT ON relay_sessions
|
|
49
|
+
BEGIN INSERT INTO scratch_known_workspaces VALUES (NEW.workspace_path)
|
|
50
|
+
ON CONFLICT(workspace_path) DO NOTHING; END;
|
|
51
|
+
CREATE TRIGGER IF NOT EXISTS scratch_workspace_on_update AFTER UPDATE OF workspace_path ON relay_sessions
|
|
52
|
+
WHEN NEW.workspace_path IS NOT OLD.workspace_path
|
|
53
|
+
BEGIN INSERT INTO scratch_known_workspaces VALUES (NEW.workspace_path)
|
|
54
|
+
ON CONFLICT(workspace_path) DO NOTHING; END;`);
|
|
31
55
|
database.exec('CREATE TABLE IF NOT EXISTS org_plan_retired_supervisors (plan_identity TEXT NOT NULL, session_id TEXT NOT NULL, stopped INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(plan_identity, session_id))');
|
|
32
56
|
database.exec('CREATE TABLE IF NOT EXISTS org_plan_takeovers (plan_identity TEXT PRIMARY KEY, session_id TEXT NOT NULL, epoch INTEGER NOT NULL, phase TEXT NOT NULL)');
|
|
33
57
|
database.exec('CREATE TABLE IF NOT EXISTS tool_efficiency (session_id TEXT PRIMARY KEY REFERENCES relay_sessions(id) ON DELETE CASCADE, state_json TEXT NOT NULL)');
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2026 Dyne.org foundation
|
|
3
|
+
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
export class SqliteForgetOperationStore {
|
|
8
|
+
db;
|
|
9
|
+
constructor(db) {
|
|
10
|
+
this.db = db;
|
|
11
|
+
}
|
|
12
|
+
find(id) {
|
|
13
|
+
const row = this.db
|
|
14
|
+
.prepare('SELECT * FROM session_forget_operations WHERE session_id = ?')
|
|
15
|
+
.get(id);
|
|
16
|
+
return row
|
|
17
|
+
? {
|
|
18
|
+
operationId: row.operation_id,
|
|
19
|
+
sessionId: row.session_id,
|
|
20
|
+
phase: row.phase,
|
|
21
|
+
updatedAt: row.updated_at,
|
|
22
|
+
...(row.failure_code ? { failureCode: row.failure_code } : {}),
|
|
23
|
+
}
|
|
24
|
+
: null;
|
|
25
|
+
}
|
|
26
|
+
assertAvailable(id) {
|
|
27
|
+
if (this.find(id))
|
|
28
|
+
throw new Error('SESSION_FORGET_IN_PROGRESS');
|
|
29
|
+
}
|
|
30
|
+
pendingIds() {
|
|
31
|
+
return this.db
|
|
32
|
+
.prepare("SELECT session_id FROM session_forget_operations WHERE phase != 'completed'")
|
|
33
|
+
.all().map((row) => row.session_id);
|
|
34
|
+
}
|
|
35
|
+
begin(id) {
|
|
36
|
+
this.db
|
|
37
|
+
.prepare(`INSERT INTO session_forget_operations (session_id, operation_id, phase, updated_at)
|
|
38
|
+
SELECT id, ?, 'stopping', ? FROM relay_sessions WHERE id = ?
|
|
39
|
+
ON CONFLICT(session_id) DO NOTHING`)
|
|
40
|
+
.run(randomUUID(), new Date().toISOString(), id);
|
|
41
|
+
return this.find(id);
|
|
42
|
+
}
|
|
43
|
+
update(operation) {
|
|
44
|
+
this.db
|
|
45
|
+
.prepare(`UPDATE session_forget_operations SET phase = ?, updated_at = ?, failure_code = ?
|
|
46
|
+
WHERE session_id = ? AND operation_id = ? AND phase != 'completed'`)
|
|
47
|
+
.run(operation.phase, operation.updatedAt, operation.failureCode ?? null, operation.sessionId, operation.operationId);
|
|
48
|
+
return this.find(operation.sessionId);
|
|
49
|
+
}
|
|
50
|
+
finalize(operation) {
|
|
51
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
52
|
+
try {
|
|
53
|
+
const current = this.find(operation.sessionId);
|
|
54
|
+
if (current?.operationId !== operation.operationId ||
|
|
55
|
+
!['finalizing', 'completed'].includes(current.phase))
|
|
56
|
+
throw new Error('SESSION_FORGET_OPERATION_CHANGED');
|
|
57
|
+
this.db.prepare('DELETE FROM relay_sessions WHERE id = ?').run(operation.sessionId);
|
|
58
|
+
this.update({ ...operation, phase: 'completed' });
|
|
59
|
+
this.db.exec('COMMIT');
|
|
60
|
+
return this.find(operation.sessionId);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
this.db.exec('ROLLBACK');
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -23,6 +23,10 @@ export class SqliteSessionRepository {
|
|
|
23
23
|
list() {
|
|
24
24
|
return this.db.prepare('SELECT * FROM relay_sessions ORDER BY updated_at DESC').all().map(map);
|
|
25
25
|
}
|
|
26
|
+
/** Workspace locators outlive Forget; they never grant deletion authority. */
|
|
27
|
+
knownWorkspacePaths() {
|
|
28
|
+
return this.db.prepare('SELECT workspace_path FROM scratch_known_workspaces').all().map((row) => row.workspace_path);
|
|
29
|
+
}
|
|
26
30
|
remove(id) {
|
|
27
31
|
this.db.prepare('DELETE FROM relay_sessions WHERE id = ?').run(id);
|
|
28
32
|
}
|