gestalt-mobile 0.68.4 → 0.68.5
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 +15 -4
- package/dist/client/assets/index-Dl5gXKZh.js +183 -0
- package/dist/client/index.html +1 -1
- package/dist/server/server/composition.contracts.js +103 -9
- package/dist/server/server/composition.js +19 -7
- package/dist/server/server/features/plans/application/plan-attachment-supervision.js +3 -1
- package/dist/server/server/features/plans/application/start-org-plan-supervision.js +10 -0
- package/dist/server/server/features/plans/execute-plan/endpoint.js +1 -1
- package/dist/server/server/features/sessions/application/workspace-conflict.js +19 -0
- package/dist/server/server/features/sessions/forget-session/endpoint.js +7 -0
- package/dist/server/server/features/sessions/forget-session/use-case.js +8 -2
- package/dist/server/server/features/sessions/register-routes.js +1 -0
- package/dist/server/server/features/sessions/restore-session/endpoint.js +10 -1
- package/dist/server/server/features/sessions/start-turn/use-case.js +13 -1
- package/dist/server/server/platform/codex/session-runtime.js +18 -0
- package/dist/server/server/platform/http/problem-handler.js +9 -0
- package/dist/server/server/platform/kimi/kimi-session-runtime.js +5 -0
- package/dist/server/server/platform/persistence/migrate.js +17 -0
- package/dist/server/server/platform/persistence/sqlite-event-journal.js +6 -2
- package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +38 -6
- package/dist/server/server/platform/persistence/sqlite-session-repository.js +29 -7
- package/dist/server/server/platform/persistence/sqlite-workspace-lifecycle.js +59 -0
- package/dist/server/server/platform/plans/filesystem-plan-status-source.js +2 -2
- package/dist/server/server/platform/scratch/filesystem-session-scratch.js +3 -1
- package/dist/server/server/platform/scratch/filesystem-workspace-forget.js +123 -0
- package/dist/server/shared/contracts/org-plan-execution.js +1 -1
- package/dist/server/shared/contracts/plan-signal.js +2 -1
- package/package.json +1 -1
- package/dist/client/assets/index-CKyExrMf.js +0 -183
package/dist/client/index.html
CHANGED
|
@@ -16,7 +16,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
16
16
|
<link rel="icon" href="/icons/gestalt-mobile-192.png" />
|
|
17
17
|
<link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
|
|
18
18
|
<title>Gestalt Mobile</title>
|
|
19
|
-
<script type="module" crossorigin src="/assets/index-
|
|
19
|
+
<script type="module" crossorigin src="/assets/index-Dl5gXKZh.js"></script>
|
|
20
20
|
<link rel="stylesheet" crossorigin href="/assets/index-CCTlWqX8.css">
|
|
21
21
|
</head>
|
|
22
22
|
<body>
|
|
@@ -143,10 +143,10 @@ function liveAppServer(handles) {
|
|
|
143
143
|
};
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
|
-
async function createComposedSession(app) {
|
|
146
|
+
async function createComposedSession(app, workspaceName = 'workspace') {
|
|
147
147
|
const workspace = (await app.inject('/api/bootstrap'))
|
|
148
148
|
.json()
|
|
149
|
-
.workspaces[0]?.children.find((item) => item.name ===
|
|
149
|
+
.workspaces[0]?.children.find((item) => item.name === workspaceName);
|
|
150
150
|
expect(workspace).toBeDefined();
|
|
151
151
|
const created = await app.inject({
|
|
152
152
|
method: 'POST',
|
|
@@ -1865,6 +1865,21 @@ describe('production composition', () => {
|
|
|
1865
1865
|
expect(opened.statusCode).toBe(200);
|
|
1866
1866
|
expect(opened.json()).toMatchObject({ title: 'Autopilot fixture', allDone: false });
|
|
1867
1867
|
expect((await app.inject(`/api/sessions/${sessionId}/plan`)).statusCode).toBe(200);
|
|
1868
|
+
expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
|
|
1869
|
+
lastOrgPlan: { supervision: false },
|
|
1870
|
+
autopilot: { enabled: false },
|
|
1871
|
+
});
|
|
1872
|
+
// This coordinator fixture begins execution through the supervisor's explicit
|
|
1873
|
+
// helper publication, independently of the passive visualizer attachment.
|
|
1874
|
+
await writeFile(planStatusFilePath(planStatusDirectoryPath(workspacePath, sessionId), planPath), JSON.stringify({
|
|
1875
|
+
schemaVersion: 1,
|
|
1876
|
+
planPath,
|
|
1877
|
+
reason: 'supervision-start',
|
|
1878
|
+
updatedAt: new Date().toISOString(),
|
|
1879
|
+
}));
|
|
1880
|
+
await vi.waitFor(async () => expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
|
|
1881
|
+
lastOrgPlan: { supervision: true },
|
|
1882
|
+
}));
|
|
1868
1883
|
await app.listen({ host: '127.0.0.1', port: 0 });
|
|
1869
1884
|
const address = app.server.address();
|
|
1870
1885
|
if (!address || typeof address === 'string')
|
|
@@ -1963,6 +1978,8 @@ describe('production composition', () => {
|
|
|
1963
1978
|
ownTemporaryPaths(root, dataDir);
|
|
1964
1979
|
const workspacePath = join(root, 'workspace');
|
|
1965
1980
|
await mkdir(workspacePath);
|
|
1981
|
+
const otherWorkspace = join(root, 'workspace-other');
|
|
1982
|
+
await mkdir(otherWorkspace);
|
|
1966
1983
|
const handles = [];
|
|
1967
1984
|
const app = await composeAuthorizedApp({
|
|
1968
1985
|
root,
|
|
@@ -1982,7 +1999,10 @@ describe('production composition', () => {
|
|
|
1982
1999
|
});
|
|
1983
2000
|
onTestFinished(() => app.close());
|
|
1984
2001
|
// Managed TMPDIR fixtures share an ancestor publication fence during session creation.
|
|
1985
|
-
const sessions = [
|
|
2002
|
+
const sessions = [
|
|
2003
|
+
await createComposedSession(app),
|
|
2004
|
+
await createComposedSession(app, 'workspace-other'),
|
|
2005
|
+
];
|
|
1986
2006
|
await vi.waitFor(async () => expect(await Promise.all(sessions.map(async (sessionId) => (await app.inject(`/api/sessions/${sessionId}`)).json().state))).toEqual(['ready', 'ready']));
|
|
1987
2007
|
const planText = `#+TITLE: Autopilot fixture
|
|
1988
2008
|
* WIP [#A] Parent
|
|
@@ -2004,9 +2024,10 @@ describe('production composition', () => {
|
|
|
2004
2024
|
- Done when :: The plan remains incomplete.
|
|
2005
2025
|
`;
|
|
2006
2026
|
await Promise.all(sessions.map(async (sessionId, index) => {
|
|
2007
|
-
const
|
|
2027
|
+
const selectedWorkspace = index === 0 ? workspacePath : otherWorkspace;
|
|
2028
|
+
const planPath = join(selectedWorkspace, `autopilot-${index}.org`);
|
|
2008
2029
|
await writeFile(planPath, planText);
|
|
2009
|
-
await writeFile(planStatusFilePath(planStatusDirectoryPath(
|
|
2030
|
+
await writeFile(planStatusFilePath(planStatusDirectoryPath(selectedWorkspace, sessionId), planPath), JSON.stringify({
|
|
2010
2031
|
schemaVersion: 1,
|
|
2011
2032
|
planPath,
|
|
2012
2033
|
reason: 'supervision-start',
|
|
@@ -4303,8 +4324,10 @@ describe('production composition', () => {
|
|
|
4303
4324
|
},
|
|
4304
4325
|
});
|
|
4305
4326
|
onTestFinished(() => fixture.app.close());
|
|
4306
|
-
const
|
|
4307
|
-
await
|
|
4327
|
+
const peerWorkspace = join(fixture.root, 'workspace-peer');
|
|
4328
|
+
await mkdir(peerWorkspace);
|
|
4329
|
+
const peer = await createComposedSession(fixture.app, 'workspace-peer');
|
|
4330
|
+
await installAutopilotPlan(fixture.app, peer, peerWorkspace, 'peer-plan');
|
|
4308
4331
|
const starts = () => fixture.handles
|
|
4309
4332
|
.flatMap((handle) => handle.requests)
|
|
4310
4333
|
.filter((request) => request.method === 'turn/start');
|
|
@@ -5689,7 +5712,8 @@ describe('production composition', () => {
|
|
|
5689
5712
|
});
|
|
5690
5713
|
expect(transitions).toBeDefined();
|
|
5691
5714
|
const sessionA = await createComposedSession(app);
|
|
5692
|
-
|
|
5715
|
+
await mkdir(join(root, 'workspace-peer'));
|
|
5716
|
+
const sessionB = await createComposedSession(app, 'workspace-peer');
|
|
5693
5717
|
const handleA = await vi.waitFor(() => {
|
|
5694
5718
|
const handle = handles.find((candidate) => candidate.calls.includes('thread/start'));
|
|
5695
5719
|
expect(handle?.request).toBeDefined();
|
|
@@ -5918,7 +5942,8 @@ describe('production composition', () => {
|
|
|
5918
5942
|
launchAppServer: liveAppServer(handles),
|
|
5919
5943
|
});
|
|
5920
5944
|
const supportedSession = await createComposedSession(first);
|
|
5921
|
-
|
|
5945
|
+
await mkdir(join(root, 'workspace-legacy'));
|
|
5946
|
+
const legacySession = await createComposedSession(first, 'workspace-legacy');
|
|
5922
5947
|
await vi.waitFor(() => expect(handles.filter((handle) => handle.calls.includes('thread/start'))).toHaveLength(2));
|
|
5923
5948
|
const started = handles.filter((handle) => handle.calls.includes('thread/start'));
|
|
5924
5949
|
const supportedRequest = started[0].request(attentionCall(901));
|
|
@@ -6820,6 +6845,75 @@ describe('production composition', () => {
|
|
|
6820
6845
|
runtimeStart.mockRestore();
|
|
6821
6846
|
}
|
|
6822
6847
|
});
|
|
6848
|
+
it.each(['TODO', 'WIP'])('keeps a validated %s plan passive in the visualizer until Execute is confirmed', async (state) => {
|
|
6849
|
+
const f = await orgPlanActivationFixture();
|
|
6850
|
+
let app = await f.open();
|
|
6851
|
+
try {
|
|
6852
|
+
const authorId = await createComposedSession(app);
|
|
6853
|
+
const planPath = join(f.workspacePath, '.gestalt', 'activation.org');
|
|
6854
|
+
await writeFile(planPath, state === 'TODO' ? autopilotPlanText().replace('* WIP', '* TODO') : autopilotPlanText());
|
|
6855
|
+
for (let opened = 0; opened < 2; opened++) {
|
|
6856
|
+
const view = await app.inject({
|
|
6857
|
+
method: 'PUT',
|
|
6858
|
+
url: `/api/sessions/${authorId}/plan`,
|
|
6859
|
+
payload: { planName: '.gestalt/activation.org' },
|
|
6860
|
+
});
|
|
6861
|
+
expect(view.statusCode, view.body).toBe(200);
|
|
6862
|
+
expect((await app.inject(`/api/sessions/${authorId}`)).json()).toMatchObject({
|
|
6863
|
+
lastOrgPlan: { attached: true, supervision: false },
|
|
6864
|
+
autopilot: { enabled: false },
|
|
6865
|
+
});
|
|
6866
|
+
await f.prepare(app);
|
|
6867
|
+
expect(f.requests('turn/start')).toHaveLength(0);
|
|
6868
|
+
expect(f.database((db) => db.prepare('SELECT count(*) AS n FROM org_plan_launches').get())).toEqual({ n: 0 });
|
|
6869
|
+
}
|
|
6870
|
+
// A deliberate Execute must report the occupied workspace and release
|
|
6871
|
+
// its unpublished claim, rather than poisoning all subsequent retries.
|
|
6872
|
+
const busyInput = await f.prepare(app);
|
|
6873
|
+
const busy = await app.inject({
|
|
6874
|
+
method: 'POST',
|
|
6875
|
+
url: '/api/plans/execute',
|
|
6876
|
+
payload: busyInput,
|
|
6877
|
+
});
|
|
6878
|
+
expect(busy.statusCode, busy.body).toBe(409);
|
|
6879
|
+
expect(busy.json()).toMatchObject({
|
|
6880
|
+
kind: 'blocked',
|
|
6881
|
+
code: 'WORKSPACE_BUSY',
|
|
6882
|
+
existingSessionId: authorId,
|
|
6883
|
+
});
|
|
6884
|
+
expect(f.requests('turn/start')).toHaveLength(0);
|
|
6885
|
+
expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
|
|
6886
|
+
await app.close();
|
|
6887
|
+
await rm(planStatusDirectoryPath(f.workspacePath, authorId), {
|
|
6888
|
+
recursive: true,
|
|
6889
|
+
force: true,
|
|
6890
|
+
});
|
|
6891
|
+
app = await f.open();
|
|
6892
|
+
await app.listen({ host: '127.0.0.1', port: 0 });
|
|
6893
|
+
expect((await app.inject(`/api/sessions/${authorId}`)).json()).toMatchObject({
|
|
6894
|
+
lastOrgPlan: { attached: true, supervision: false },
|
|
6895
|
+
autopilot: { enabled: false },
|
|
6896
|
+
});
|
|
6897
|
+
expect(f.requests('turn/start')).toHaveLength(0);
|
|
6898
|
+
const input = await f.prepare(app);
|
|
6899
|
+
const execute = await app.inject({
|
|
6900
|
+
method: 'POST',
|
|
6901
|
+
url: '/api/plans/execute',
|
|
6902
|
+
payload: input,
|
|
6903
|
+
});
|
|
6904
|
+
expect(execute.json()).toMatchObject({
|
|
6905
|
+
kind: 'started',
|
|
6906
|
+
bootstrap: { kind: 'accepted' },
|
|
6907
|
+
});
|
|
6908
|
+
expect(f.requests('turn/start')).toHaveLength(1);
|
|
6909
|
+
const supervisorId = execute.json().session.id;
|
|
6910
|
+
expect(supervisorId).not.toBe(authorId);
|
|
6911
|
+
expect((await app.inject(`/api/sessions/${authorId}`)).json().autopilot.enabled).toBe(false);
|
|
6912
|
+
}
|
|
6913
|
+
finally {
|
|
6914
|
+
await app.close();
|
|
6915
|
+
}
|
|
6916
|
+
});
|
|
6823
6917
|
it.each(['authoring-start', 'resync'])('executes a draft retained through %s in one new supervisor, including after restart', async (reason) => {
|
|
6824
6918
|
const f = await orgPlanActivationFixture();
|
|
6825
6919
|
let app = await f.open();
|
|
@@ -57,6 +57,8 @@ import { SqliteAuthorizationStore } from './platform/auth/sqlite-authorization-s
|
|
|
57
57
|
import { SimpleWebAuthnAdapter } from './platform/auth/simple-webauthn-adapter.js';
|
|
58
58
|
import { authorizationSessionId, authorizedDeviceId } from './features/auth/domain/identifiers.js';
|
|
59
59
|
import { SqliteSessionRepository } from './platform/persistence/sqlite-session-repository.js';
|
|
60
|
+
import { SqliteWorkspaceLifecycle } from './platform/persistence/sqlite-workspace-lifecycle.js';
|
|
61
|
+
import { FilesystemWorkspaceForget } from './platform/scratch/filesystem-workspace-forget.js';
|
|
60
62
|
import { SqliteEventJournal } from './platform/persistence/sqlite-event-journal.js';
|
|
61
63
|
import { SqlitePendingInteractionStore } from './platform/persistence/sqlite-pending-interaction-store.js';
|
|
62
64
|
import { SqliteIdempotencyStore } from './platform/persistence/sqlite-idempotency-store.js';
|
|
@@ -155,7 +157,7 @@ export async function composeRelayApp(options) {
|
|
|
155
157
|
database.close();
|
|
156
158
|
throw error;
|
|
157
159
|
}
|
|
158
|
-
const sessions = new SqliteSessionRepository(database);
|
|
160
|
+
const sessions = new SqliteSessionRepository(database, new SqliteWorkspaceLifecycle(database));
|
|
159
161
|
const forgetOperations = new SqliteForgetOperationStore(database);
|
|
160
162
|
// Only sessions found while opening the relay database belong to a previous
|
|
161
163
|
// process. A listen hook can run after a new session has already started in
|
|
@@ -526,7 +528,13 @@ export async function composeRelayApp(options) {
|
|
|
526
528
|
const debugHome = options.homeDirectory ?? homedir();
|
|
527
529
|
const debugWorkspace = new SelfDebugWorkspace(join(debugHome, '.gestalt', 'self-debug'), join(process.env.CODEX_HOME ?? join(debugHome, '.codex'), 'agents', 'org-plan-executor.toml'), databasePath);
|
|
528
530
|
const homeDirectory = options.homeDirectory ?? homedir();
|
|
529
|
-
const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id))
|
|
531
|
+
const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id), ({ id }) => {
|
|
532
|
+
forgetOperations.assertAvailable(id);
|
|
533
|
+
const current = sessions.find(id);
|
|
534
|
+
if (!current)
|
|
535
|
+
throw new Error('SESSION_NOT_FOUND');
|
|
536
|
+
sessions.save(RelaySession.rehydrate(current).beginRecovery(new Date().toISOString()).snapshot, true);
|
|
537
|
+
});
|
|
530
538
|
// Constructing the manager is cheap (no spawn until `ensure`); building it
|
|
531
539
|
// before the model catalog lets the catalog reuse the gestalt-owned servers.
|
|
532
540
|
const kimiManager = options.kimiServerManager ??
|
|
@@ -1559,6 +1567,7 @@ export async function composeRelayApp(options) {
|
|
|
1559
1567
|
/** Routes a session to the runtime owning its provider's llm service. */
|
|
1560
1568
|
const ownerRuntime = (session) => session.provider === 'kimi' ? kimiRuntime : runtime;
|
|
1561
1569
|
const scratchCleanup = new FilesystemScratchCleanup();
|
|
1570
|
+
const workspaceForget = new FilesystemWorkspaceForget(database);
|
|
1562
1571
|
const cleanTmp = new CleanSessionScratch({
|
|
1563
1572
|
sessions: () => sessions.list(),
|
|
1564
1573
|
knownWorkspacePaths: async () => [root, ...sessions.knownWorkspacePaths()],
|
|
@@ -1580,7 +1589,7 @@ export async function composeRelayApp(options) {
|
|
|
1580
1589
|
await ownerRuntime(session)?.releaseForForget(session);
|
|
1581
1590
|
await playwright.waitForRelease(session.id);
|
|
1582
1591
|
},
|
|
1583
|
-
clean: (session, operationId) =>
|
|
1592
|
+
clean: (session, operationId) => workspaceForget.clean(session, operationId, () => {
|
|
1584
1593
|
const operation = forgetOperations.find(session.id);
|
|
1585
1594
|
return operation?.operationId === operationId && operation.phase === 'cleaning';
|
|
1586
1595
|
}, () => sessions.list()),
|
|
@@ -1782,12 +1791,13 @@ export async function composeRelayApp(options) {
|
|
|
1782
1791
|
}
|
|
1783
1792
|
: undefined,
|
|
1784
1793
|
releaseWriter: runtime || kimiRuntime
|
|
1785
|
-
? (id) => {
|
|
1794
|
+
? async (id) => {
|
|
1786
1795
|
providerRecovery.cancel(id);
|
|
1787
1796
|
dismissPendingInteractions(id, new Date().toISOString());
|
|
1788
1797
|
const session = sessions.find(id);
|
|
1789
1798
|
const owner = session ? ownerRuntime(session) : null;
|
|
1790
|
-
|
|
1799
|
+
if (owner && session)
|
|
1800
|
+
await owner.releaseForForget(session);
|
|
1791
1801
|
}
|
|
1792
1802
|
: undefined,
|
|
1793
1803
|
onStarted: (session) => {
|
|
@@ -2293,7 +2303,9 @@ export async function composeRelayApp(options) {
|
|
|
2293
2303
|
activity.dispose(id);
|
|
2294
2304
|
const session = sessions.find(id);
|
|
2295
2305
|
const owner = session ? ownerRuntime(session) : null;
|
|
2296
|
-
|
|
2306
|
+
if (session && owner)
|
|
2307
|
+
await owner.releaseForForget(session);
|
|
2308
|
+
await playwright.waitForRelease(id);
|
|
2297
2309
|
}
|
|
2298
2310
|
: undefined,
|
|
2299
2311
|
replyInteraction: runtime || kimiRuntime
|
|
@@ -2356,7 +2368,7 @@ export async function composeRelayApp(options) {
|
|
|
2356
2368
|
const result = await workspacePlanCatalog.read(session.workspacePath, planName);
|
|
2357
2369
|
if (result.kind === 'available') {
|
|
2358
2370
|
const planPath = resolve(session.workspacePath, ...planName.split('/'));
|
|
2359
|
-
await planStatusSource.attach(session, planPath, (update) => acceptPlanUpdate(id, update));
|
|
2371
|
+
await planStatusSource.attach(session, planPath, (update) => acceptPlanUpdate(id, update), 'display-open');
|
|
2360
2372
|
}
|
|
2361
2373
|
return result;
|
|
2362
2374
|
},
|
|
@@ -17,7 +17,9 @@ export function planAttachmentSupervision(previous, update, retainedSupervision)
|
|
|
17
17
|
update.reason === 'checkpoint' ||
|
|
18
18
|
!!update.reason?.match(/^(?:l2:|review:|measure:)/))
|
|
19
19
|
return true;
|
|
20
|
-
if (update.reason === '
|
|
20
|
+
if (update.reason === 'display-open' ||
|
|
21
|
+
update.reason === 'authoring-start' ||
|
|
22
|
+
(sameAttachment && previous.supervision === false))
|
|
21
23
|
return false;
|
|
22
24
|
return (progressed(update.plan.steps) ||
|
|
23
25
|
// Unknown legacy publications cannot prove that a previous supervisor was only authoring.
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
|
+
import { WorkspaceSessionConflict } from '../../sessions/application/workspace-conflict.js';
|
|
7
8
|
import { orgPlanLaunchRequestSchema, } from '../../../../shared/contracts/org-plan-execution.js';
|
|
8
9
|
import { fingerprintTurnInput, } from '../../sessions/start-turn/use-case.js';
|
|
9
10
|
/** One public application boundary, including durable ownership and retry rules. */
|
|
@@ -149,6 +150,15 @@ async function continueLaunch(record, deps) {
|
|
|
149
150
|
}
|
|
150
151
|
catch (error) {
|
|
151
152
|
session = deps.sessions.find(record.sessionId);
|
|
153
|
+
if (!session && error instanceof WorkspaceSessionConflict) {
|
|
154
|
+
deps.launches.revokePublication(record, deps.sessions);
|
|
155
|
+
return {
|
|
156
|
+
kind: 'blocked',
|
|
157
|
+
code: 'WORKSPACE_BUSY',
|
|
158
|
+
reason: error.message,
|
|
159
|
+
existingSessionId: error.sessionId,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
152
162
|
if (session)
|
|
153
163
|
deps.launches.save({ ...record, phase: 'session' }, 'creating');
|
|
154
164
|
else if (error instanceof OrgPlanSessionNotPublished) {
|
|
@@ -19,7 +19,7 @@ export function registerExecuteOrgPlan(app, deps) {
|
|
|
19
19
|
? 409
|
|
20
20
|
: 400
|
|
21
21
|
: result.kind === 'blocked' &&
|
|
22
|
-
['CONTEXT_CHANGED', 'ACTIVE_SUPERVISION'].includes(result.code)
|
|
22
|
+
['CONTEXT_CHANGED', 'ACTIVE_SUPERVISION', 'WORKSPACE_BUSY'].includes(result.code)
|
|
23
23
|
? 409
|
|
24
24
|
: 200;
|
|
25
25
|
return reply.code(status).send(result);
|
|
@@ -0,0 +1,19 @@
|
|
|
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
|
+
export class WorkspaceSessionConflict extends Error {
|
|
7
|
+
code;
|
|
8
|
+
sessionId;
|
|
9
|
+
statusCode = 409;
|
|
10
|
+
constructor(code, sessionId) {
|
|
11
|
+
super(code === 'SESSION_WORKSPACE_BUSY'
|
|
12
|
+
? 'A session is already running in this workspace. Open that session or stop it first.'
|
|
13
|
+
: code === 'SESSION_NESTED_WORKSPACE'
|
|
14
|
+
? 'Forget the session whose workspace is inside this temporary directory first.'
|
|
15
|
+
: 'This workspace is being forgotten. Retry when cleanup finishes.');
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.sessionId = sessionId;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -10,6 +10,13 @@ export function registerForgetSession(app, deps) {
|
|
|
10
10
|
const operation = await deps.forget(id);
|
|
11
11
|
if (!operation)
|
|
12
12
|
return reply.code(404).send({ code: 'SESSION_NOT_FOUND' });
|
|
13
|
+
if (operation.phase === 'failed' && operation.blockingSessionId)
|
|
14
|
+
return reply.code(409).send({
|
|
15
|
+
code: 'SESSION_NESTED_WORKSPACE',
|
|
16
|
+
sessionId: operation.blockingSessionId,
|
|
17
|
+
detail: 'Forget the contained workspace session first, then retry.',
|
|
18
|
+
operation,
|
|
19
|
+
});
|
|
13
20
|
if (operation.phase !== 'completed')
|
|
14
21
|
return reply.code(503).send({ code: 'SESSION_FORGET_FAILED', operation });
|
|
15
22
|
return reply.code(204).send();
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
|
+
import { WorkspaceSessionConflict } from '../application/workspace-conflict.js';
|
|
6
7
|
export class ForgetSession {
|
|
7
8
|
deps;
|
|
8
9
|
pending = new Map();
|
|
@@ -37,6 +38,7 @@ export class ForgetSession {
|
|
|
37
38
|
sessionId: id,
|
|
38
39
|
phase,
|
|
39
40
|
updatedAt: this.deps.now(),
|
|
41
|
+
...(operation.scratchRetained ? { scratchRetained: true } : {}),
|
|
40
42
|
});
|
|
41
43
|
this.deps.changed(operation);
|
|
42
44
|
return operation;
|
|
@@ -53,7 +55,8 @@ export class ForgetSession {
|
|
|
53
55
|
failureCode = 'SESSION_CLEANUP_FAILED';
|
|
54
56
|
if (advance('cleaning').phase === 'completed')
|
|
55
57
|
return operation;
|
|
56
|
-
await this.deps.clean(session, operation.operationId);
|
|
58
|
+
const cleanup = await this.deps.clean(session, operation.operationId);
|
|
59
|
+
operation = { ...operation, scratchRetained: cleanup === 'retained' ? true : undefined };
|
|
57
60
|
failureCode = 'SESSION_FORGET_FAILED';
|
|
58
61
|
if (advance('finalizing').phase === 'completed')
|
|
59
62
|
return operation;
|
|
@@ -61,12 +64,15 @@ export class ForgetSession {
|
|
|
61
64
|
this.deps.changed(operation);
|
|
62
65
|
return operation;
|
|
63
66
|
}
|
|
64
|
-
catch {
|
|
67
|
+
catch (error) {
|
|
65
68
|
operation = this.deps.operations.update({
|
|
66
69
|
...operation,
|
|
67
70
|
phase: 'failed',
|
|
68
71
|
failureCode,
|
|
69
72
|
updatedAt: this.deps.now(),
|
|
73
|
+
...(error instanceof WorkspaceSessionConflict
|
|
74
|
+
? { blockingSessionId: error.sessionId }
|
|
75
|
+
: {}),
|
|
70
76
|
});
|
|
71
77
|
this.deps.changed(operation);
|
|
72
78
|
return operation;
|
|
@@ -134,6 +134,7 @@ export function registerSessionRoutes(app, deps) {
|
|
|
134
134
|
registerRestoreSession(app, {
|
|
135
135
|
find: sessions.find,
|
|
136
136
|
restore: sessions.restore,
|
|
137
|
+
close: sessions.close,
|
|
137
138
|
save: sessions.save,
|
|
138
139
|
ownsWriter: sessions.ownsWriter,
|
|
139
140
|
idempotency: sessions.idempotency,
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Designed by Denis Roio <jaromil@dyne.org>
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
|
+
import { WorkspaceSessionConflict } from '../application/workspace-conflict.js';
|
|
6
7
|
import { idempotencyKey } from '../../../platform/http/idempotency.js';
|
|
7
8
|
import { RelaySession, relayOwnsWriter } from '../model/relay-session.js';
|
|
8
9
|
import { canRestore } from './use-case.js';
|
|
@@ -32,12 +33,20 @@ export function registerRestoreSession(app, deps) {
|
|
|
32
33
|
try {
|
|
33
34
|
restored = await deps.restore(session);
|
|
34
35
|
}
|
|
35
|
-
catch {
|
|
36
|
+
catch (error) {
|
|
37
|
+
try {
|
|
38
|
+
await deps.close?.(id);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return reply.code(502).send({ code: 'RESTORE_FAILED' });
|
|
42
|
+
}
|
|
36
43
|
// The pre-I/O recovery marker must never strand a saved session: keep
|
|
37
44
|
// its original thread and inactive state available for a later Open.
|
|
38
45
|
deps.save(staleWriter
|
|
39
46
|
? RelaySession.rehydrate(session).stop(new Date().toISOString()).snapshot
|
|
40
47
|
: session);
|
|
48
|
+
if (error instanceof WorkspaceSessionConflict)
|
|
49
|
+
throw error;
|
|
41
50
|
return reply.code(502).send({ code: 'RESTORE_FAILED' });
|
|
42
51
|
}
|
|
43
52
|
const response = 'session' in restored
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
|
+
import { WorkspaceSessionConflict } from '../application/workspace-conflict.js';
|
|
7
8
|
import { RelaySession } from '../model/relay-session.js';
|
|
8
9
|
import { WriterAcquisitionError, writerAcquisitionProblem, } from '../application/writer-acquisition.js';
|
|
9
10
|
/** Ordinary turn acceptance, shared by HTTP and application callers with one serialization boundary. */
|
|
@@ -203,7 +204,8 @@ async function cleanupAcquiredWriter(deps, acquired, original) {
|
|
|
203
204
|
await deps.releaseWriter?.(acquired.id);
|
|
204
205
|
}
|
|
205
206
|
catch {
|
|
206
|
-
//
|
|
207
|
+
// Keep the workspace reservation when shutdown could not be confirmed.
|
|
208
|
+
return;
|
|
207
209
|
}
|
|
208
210
|
try {
|
|
209
211
|
deps.save(original);
|
|
@@ -222,6 +224,16 @@ async function ensureWriter(deps, session) {
|
|
|
222
224
|
return await deps.ensureWriter(session);
|
|
223
225
|
}
|
|
224
226
|
catch (error) {
|
|
227
|
+
if (error instanceof WorkspaceSessionConflict)
|
|
228
|
+
return {
|
|
229
|
+
statusCode: 409,
|
|
230
|
+
body: JSON.stringify({
|
|
231
|
+
code: error.code,
|
|
232
|
+
detail: error.message,
|
|
233
|
+
sessionId: error.sessionId,
|
|
234
|
+
retryable: true,
|
|
235
|
+
}),
|
|
236
|
+
};
|
|
225
237
|
if (error instanceof WriterAcquisitionError &&
|
|
226
238
|
error.kind === 'writerBusy' &&
|
|
227
239
|
session.state !== 'stopped')
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
6
|
import { ORG_PLAN_CAPABILITIES } from '../plans/org-plan-capabilities.js';
|
|
7
|
+
import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
|
|
7
8
|
import { readExecutorConfiguration } from './executor-configuration.js';
|
|
8
9
|
import { decodeCodexPolicyCatalog } from './codex-model-catalog.js';
|
|
9
10
|
import { RelaySession, } from '../../features/sessions/model/relay-session.js';
|
|
@@ -170,6 +171,7 @@ export class CodexSessionRuntime {
|
|
|
170
171
|
childTopologyReads = new Map();
|
|
171
172
|
writerAcquisitions = new Map();
|
|
172
173
|
liveResources = new Map();
|
|
174
|
+
confirmedWorkspaceReleases = new Set();
|
|
173
175
|
resourceCreations = new Map();
|
|
174
176
|
resourceReleases = new Map();
|
|
175
177
|
/** Current runtime observations only; durable workspace selection is never rewritten. */
|
|
@@ -238,7 +240,9 @@ export class CodexSessionRuntime {
|
|
|
238
240
|
}
|
|
239
241
|
/** Forget requires actual release, including resources still starting or already closing. */
|
|
240
242
|
async releaseForForget(session) {
|
|
243
|
+
let observedResource = false;
|
|
241
244
|
for (const resource of this.liveResources.get(session.id) ?? []) {
|
|
245
|
+
observedResource = true;
|
|
242
246
|
resource.beginExplicitShutdown();
|
|
243
247
|
if (resource.active) {
|
|
244
248
|
if (session.activeTurnId)
|
|
@@ -282,11 +286,14 @@ export class CodexSessionRuntime {
|
|
|
282
286
|
...[this.writerAcquisitions.get(session.id)].filter((item) => item !== undefined),
|
|
283
287
|
]);
|
|
284
288
|
for (const resource of this.liveResources.get(session.id) ?? []) {
|
|
289
|
+
observedResource = true;
|
|
285
290
|
resource.beginExplicitShutdown();
|
|
286
291
|
resource.dispose();
|
|
287
292
|
await this.confirmResourceRelease(resource, true);
|
|
288
293
|
}
|
|
289
294
|
this.retrieval?.release?.(session.id);
|
|
295
|
+
if (observedResource && !this.liveResources.get(session.id)?.size)
|
|
296
|
+
this.confirmedWorkspaceReleases.add(session.id);
|
|
290
297
|
}
|
|
291
298
|
confirmResourceRelease(resource, strict = false) {
|
|
292
299
|
const prior = this.resourceReleases.get(resource);
|
|
@@ -563,6 +570,8 @@ export class CodexSessionRuntime {
|
|
|
563
570
|
return { session: restored.session, replacementCreated: restored.replacementCreated };
|
|
564
571
|
}
|
|
565
572
|
catch (error) {
|
|
573
|
+
if (error instanceof WorkspaceSessionConflict)
|
|
574
|
+
throw error;
|
|
566
575
|
throw classifyWriterAcquisitionFailure(error);
|
|
567
576
|
}
|
|
568
577
|
}
|
|
@@ -587,6 +596,13 @@ export class CodexSessionRuntime {
|
|
|
587
596
|
}
|
|
588
597
|
/** Stops the previous root's actor tree without transferring its native collaboration namespace. */
|
|
589
598
|
async quiesceForTakeover(session, recordedProcesses = [], executor) {
|
|
599
|
+
// A user-confirmed Close already quiesced this root. Reopening it solely
|
|
600
|
+
// for takeover would conflict with the incoming workspace's running slot.
|
|
601
|
+
if (session.desiredState === 'stopped' &&
|
|
602
|
+
this.confirmedWorkspaceReleases.has(session.id) &&
|
|
603
|
+
!this.liveResources.get(session.id)?.size &&
|
|
604
|
+
!recordedProcesses.some((claim) => ['running', 'detached-active'].includes(claim.state)))
|
|
605
|
+
return true;
|
|
590
606
|
let expired = false;
|
|
591
607
|
let timer;
|
|
592
608
|
try {
|
|
@@ -1448,6 +1464,8 @@ export class CodexSessionRuntime {
|
|
|
1448
1464
|
return task;
|
|
1449
1465
|
}
|
|
1450
1466
|
async createResourceInner(session) {
|
|
1467
|
+
this.scratch?.reserveRuntime?.(session);
|
|
1468
|
+
this.confirmedWorkspaceReleases.delete(session.id);
|
|
1451
1469
|
const deadline = xerjDeadline();
|
|
1452
1470
|
const lease = this.planStatusSource
|
|
1453
1471
|
? await this.planStatusSource.open({ id: session.id, workspacePath: session.workspacePath }, (update) => this.onPlanStatus?.(session.id, update))
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
5
|
*/
|
|
6
6
|
import { problem as createProblem } from './problem.js';
|
|
7
|
+
import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
|
|
7
8
|
export function registerProblemHandler(app, serveSpa = false) {
|
|
8
9
|
app.setNotFoundHandler((request, reply) => {
|
|
9
10
|
if (serveSpa && request.method === 'GET' && !request.url.startsWith('/api/')) {
|
|
@@ -20,6 +21,14 @@ export function registerProblemHandler(app, serveSpa = false) {
|
|
|
20
21
|
return reply.code(404).type('application/problem+json').send(problem);
|
|
21
22
|
});
|
|
22
23
|
app.setErrorHandler((error, _request, reply) => {
|
|
24
|
+
if (error instanceof WorkspaceSessionConflict)
|
|
25
|
+
return reply
|
|
26
|
+
.code(409)
|
|
27
|
+
.type('application/problem+json')
|
|
28
|
+
.send({
|
|
29
|
+
...createProblem(error.code, 409, error.message, true),
|
|
30
|
+
sessionId: error.sessionId,
|
|
31
|
+
});
|
|
23
32
|
if (typeof error === 'object' &&
|
|
24
33
|
error !== null &&
|
|
25
34
|
'code' in error &&
|
|
@@ -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 { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
|
|
7
8
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
8
9
|
import { RelaySession, } from '../../features/sessions/model/relay-session.js';
|
|
9
10
|
import { normalizeSkillProfileName, } from '../../features/skills/model/skill-profile.js';
|
|
@@ -45,6 +46,7 @@ export class KimiSessionRuntime {
|
|
|
45
46
|
};
|
|
46
47
|
}
|
|
47
48
|
async start(session, now) {
|
|
49
|
+
this.input.scratch?.reserveRuntime?.(session);
|
|
48
50
|
const handle = await this.ensureServer(session);
|
|
49
51
|
const created = (await handle.client.post('/api/v1/sessions', {
|
|
50
52
|
metadata: { cwd: session.workspacePath },
|
|
@@ -260,6 +262,8 @@ export class KimiSessionRuntime {
|
|
|
260
262
|
return { session: restored.session, replacementCreated: restored.replacementCreated };
|
|
261
263
|
}
|
|
262
264
|
catch (error) {
|
|
265
|
+
if (error instanceof WorkspaceSessionConflict)
|
|
266
|
+
throw error;
|
|
263
267
|
throw classifyWriterAcquisitionFailure(error);
|
|
264
268
|
}
|
|
265
269
|
}
|
|
@@ -327,6 +331,7 @@ export class KimiSessionRuntime {
|
|
|
327
331
|
}
|
|
328
332
|
/** Attaches to the durable kimi session recorded on the relay snapshot. */
|
|
329
333
|
async attachExisting(session) {
|
|
334
|
+
this.input.scratch?.reserveRuntime?.(session);
|
|
330
335
|
if (!session.threadId)
|
|
331
336
|
throw new Error('KIMI_THREAD_ID_MISSING');
|
|
332
337
|
const handle = await this.ensureServer(session);
|
|
@@ -53,6 +53,23 @@ export function migrate(database) {
|
|
|
53
53
|
CREATE TRIGGER IF NOT EXISTS forget_fence_update BEFORE UPDATE ON relay_sessions
|
|
54
54
|
WHEN EXISTS (SELECT 1 FROM session_forget_operations WHERE session_id = NEW.id)
|
|
55
55
|
BEGIN SELECT RAISE(IGNORE); END;`);
|
|
56
|
+
const forgetColumns = database
|
|
57
|
+
.prepare('PRAGMA table_info(session_forget_operations)')
|
|
58
|
+
.all();
|
|
59
|
+
if (!forgetColumns.some((column) => column.name === 'scratch_retained'))
|
|
60
|
+
database.exec('ALTER TABLE session_forget_operations ADD COLUMN scratch_retained INTEGER NOT NULL DEFAULT 0');
|
|
61
|
+
database.exec(`CREATE TABLE IF NOT EXISTS workspace_forget_locks (
|
|
62
|
+
workspace_path TEXT PRIMARY KEY,
|
|
63
|
+
session_id TEXT NOT NULL,
|
|
64
|
+
operation_id TEXT NOT NULL UNIQUE
|
|
65
|
+
);`);
|
|
66
|
+
if (!forgetColumns.some((column) => column.name === 'blocking_session_id'))
|
|
67
|
+
database.exec('ALTER TABLE session_forget_operations ADD COLUMN blocking_session_id TEXT');
|
|
68
|
+
const workspaceLockColumns = database
|
|
69
|
+
.prepare('PRAGMA table_info(workspace_forget_locks)')
|
|
70
|
+
.all();
|
|
71
|
+
if (!workspaceLockColumns.some((column) => column.name === 'retired_path'))
|
|
72
|
+
database.exec('ALTER TABLE workspace_forget_locks ADD COLUMN retired_path TEXT');
|
|
56
73
|
database.exec(`CREATE TABLE IF NOT EXISTS scratch_known_workspaces (
|
|
57
74
|
workspace_path TEXT PRIMARY KEY
|
|
58
75
|
); INSERT OR IGNORE INTO scratch_known_workspaces (workspace_path)
|
|
@@ -64,8 +64,12 @@ export class SqliteEventJournal {
|
|
|
64
64
|
this.db.exec('BEGIN IMMEDIATE');
|
|
65
65
|
try {
|
|
66
66
|
const row = this.db
|
|
67
|
-
|
|
68
|
-
.
|
|
67
|
+
// Forget fences roster writes, including the sequence counter. Allocate
|
|
68
|
+
// above the durable journal tail as well, including already-stuck rows.
|
|
69
|
+
.prepare(`SELECT MAX(next_sequence, COALESCE(
|
|
70
|
+
(SELECT MAX(sequence) + 1 FROM session_events WHERE session_id = ?), 1
|
|
71
|
+
)) AS sequence FROM relay_sessions WHERE id = ?`)
|
|
72
|
+
.get(sessionId, sessionId);
|
|
69
73
|
if (!row)
|
|
70
74
|
throw new Error('SESSION_NOT_FOUND');
|
|
71
75
|
const inserted = this.db
|