gestalt-mobile 0.68.4 → 0.68.6

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.
Files changed (35) hide show
  1. package/README.md +15 -4
  2. package/dist/client/assets/index-Dl5gXKZh.js +183 -0
  3. package/dist/client/index.html +1 -1
  4. package/dist/server/server/composition.contracts.js +232 -12
  5. package/dist/server/server/composition.js +111 -29
  6. package/dist/server/server/features/plans/application/plan-attachment-supervision.js +3 -1
  7. package/dist/server/server/features/plans/application/prepare-org-plan-supervision.js +18 -10
  8. package/dist/server/server/features/plans/application/start-org-plan-supervision.js +23 -4
  9. package/dist/server/server/features/plans/execute-plan/endpoint.js +1 -1
  10. package/dist/server/server/features/sessions/application/workspace-conflict.js +19 -0
  11. package/dist/server/server/features/sessions/application/writer-acquisition.js +7 -0
  12. package/dist/server/server/features/sessions/forget-session/endpoint.js +7 -0
  13. package/dist/server/server/features/sessions/forget-session/use-case.js +8 -2
  14. package/dist/server/server/features/sessions/register-routes.js +1 -0
  15. package/dist/server/server/features/sessions/restore-session/endpoint.js +10 -1
  16. package/dist/server/server/features/sessions/start-session/endpoint.js +8 -0
  17. package/dist/server/server/features/sessions/start-turn/use-case.js +13 -1
  18. package/dist/server/server/platform/codex/error-code.js +2 -2
  19. package/dist/server/server/platform/codex/protocol-compatibility.js +7 -24
  20. package/dist/server/server/platform/codex/session-runtime.js +18 -0
  21. package/dist/server/server/platform/http/problem-handler.js +9 -0
  22. package/dist/server/server/platform/kimi/kimi-session-runtime.js +5 -0
  23. package/dist/server/server/platform/persistence/migrate.js +17 -0
  24. package/dist/server/server/platform/persistence/sqlite-event-journal.js +6 -2
  25. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +38 -6
  26. package/dist/server/server/platform/persistence/sqlite-org-plan-launch-store.js +43 -16
  27. package/dist/server/server/platform/persistence/sqlite-session-repository.js +29 -7
  28. package/dist/server/server/platform/persistence/sqlite-workspace-lifecycle.js +59 -0
  29. package/dist/server/server/platform/plans/filesystem-plan-status-source.js +2 -2
  30. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +3 -1
  31. package/dist/server/server/platform/scratch/filesystem-workspace-forget.js +123 -0
  32. package/dist/server/shared/contracts/org-plan-execution.js +1 -1
  33. package/dist/server/shared/contracts/plan-signal.js +2 -1
  34. package/package.json +1 -1
  35. package/dist/client/assets/index-CKyExrMf.js +0 -183
@@ -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';
@@ -128,7 +130,6 @@ import { currentExecutableL1Index } from './features/plans/domain/supervised-pla
128
130
  import { AttentionResolution } from './features/org-plan-attention/application/resolve.js';
129
131
  import { AttentionAcknowledgement } from './features/org-plan-attention/application/acknowledgement.js';
130
132
  import { pwaIconUrl } from './features/pwa/register-routes.js';
131
- const generatedProtocolVersion = 'codex-cli 0.144.3';
132
133
  const checkpointDiagnostic = debuglog('gestalt-mobile:checkpoint');
133
134
  const attentionDiagnostic = debuglog('gestalt-mobile:attention');
134
135
  export async function composeRelayApp(options) {
@@ -155,7 +156,7 @@ export async function composeRelayApp(options) {
155
156
  database.close();
156
157
  throw error;
157
158
  }
158
- const sessions = new SqliteSessionRepository(database);
159
+ const sessions = new SqliteSessionRepository(database, new SqliteWorkspaceLifecycle(database));
159
160
  const forgetOperations = new SqliteForgetOperationStore(database);
160
161
  // Only sessions found while opening the relay database belong to a previous
161
162
  // process. A listen hook can run after a new session has already started in
@@ -167,6 +168,36 @@ export async function composeRelayApp(options) {
167
168
  const interactions = new SqlitePendingInteractionStore(database);
168
169
  const idempotency = new SqliteIdempotencyStore(database);
169
170
  const orgPlanLaunches = new SqliteOrgPlanLaunchStore(database);
171
+ // Admission spans asynchronous provider calls so Execute cannot reserve a workspace mid-start.
172
+ const workspaceAdmissions = new Map();
173
+ const assertWorkspaceOwner = (session) => {
174
+ let owner = orgPlanLaunches.workspaceOwner(session.workspacePath);
175
+ while (owner &&
176
+ forgetOperations.find(owner.sessionId)?.phase === 'completed' &&
177
+ !sessions.find(owner.sessionId) &&
178
+ !runtime?.ownsWriter(owner.sessionId)) {
179
+ orgPlanLaunches.releaseOwner(owner);
180
+ owner = orgPlanLaunches.workspaceOwner(session.workspacePath);
181
+ }
182
+ if (owner && owner.sessionId !== session.id)
183
+ throw new WriterAcquisitionError('workspaceLocked');
184
+ };
185
+ const withWorkspaceAdmission = async (sessionId, operation) => {
186
+ const session = sessions.find(sessionId);
187
+ if (session)
188
+ assertWorkspaceOwner(session);
189
+ workspaceAdmissions.set(sessionId, (workspaceAdmissions.get(sessionId) ?? 0) + 1);
190
+ try {
191
+ return await operation();
192
+ }
193
+ finally {
194
+ const count = (workspaceAdmissions.get(sessionId) ?? 1) - 1;
195
+ if (count)
196
+ workspaceAdmissions.set(sessionId, count);
197
+ else
198
+ workspaceAdmissions.delete(sessionId);
199
+ }
200
+ };
170
201
  const reconcileOrgPlanReceipt = (sessionId) => {
171
202
  const record = orgPlanLaunches.forSession(sessionId);
172
203
  if (record?.phase !== 'submitting' || !record.bootstrapFingerprint)
@@ -372,7 +403,7 @@ export async function composeRelayApp(options) {
372
403
  }),
373
404
  nextControlId: (sessionId, generation) => `autopilot-${generation}-${createHash('sha256').update(`${sessionId}:${randomUUID()}`).digest('hex').slice(0, 16)}`,
374
405
  turnStarter: {
375
- start: async (sessionId, controlId, generation, launchIdentity) => {
406
+ start: async (sessionId, controlId, generation, launchIdentity) => withWorkspaceAdmission(sessionId, async () => {
376
407
  if (supervisorOwnership(sessionId) !== 'owned')
377
408
  throw new Error('AUTOPILOT_START_UNAVAILABLE');
378
409
  const current = () => {
@@ -386,7 +417,10 @@ export async function composeRelayApp(options) {
386
417
  if (!current())
387
418
  throw new Error('AUTOPILOT_START_UNAVAILABLE');
388
419
  const session = sessions.find(sessionId);
389
- if (!session || !runtime || session.activeTurnId || blockingInteractions(sessionId).length)
420
+ if (!session ||
421
+ !runtime ||
422
+ session.activeTurnId ||
423
+ blockingInteractions(sessionId).length)
390
424
  throw new Error('AUTOPILOT_START_UNAVAILABLE');
391
425
  requireOrgExecutionAdmission(sessionId);
392
426
  if (!current() ||
@@ -440,10 +474,10 @@ export async function composeRelayApp(options) {
440
474
  ...(started.threadId ? { threadId: started.threadId } : {}),
441
475
  ...(started.activeTurnId ? { turnId: started.activeTurnId } : {}),
442
476
  });
443
- },
477
+ }),
444
478
  },
445
479
  executorController: {
446
- resume: async (sessionId, threadId, generation, trigger) => {
480
+ resume: async (sessionId, threadId, generation, trigger) => withWorkspaceAdmission(sessionId, async () => {
447
481
  if (supervisorOwnership(sessionId) !== 'owned')
448
482
  throw new Error('AUTOPILOT_EXECUTOR_UNAVAILABLE');
449
483
  const session = sessions.find(sessionId);
@@ -480,7 +514,7 @@ export async function composeRelayApp(options) {
480
514
  threadId,
481
515
  turnId,
482
516
  });
483
- },
517
+ }),
484
518
  refresh: (sessionId) => activity.refresh(sessionId),
485
519
  interrupt: async (sessionId, threadId) => {
486
520
  const session = sessions.find(sessionId);
@@ -526,7 +560,13 @@ export async function composeRelayApp(options) {
526
560
  const debugHome = options.homeDirectory ?? homedir();
527
561
  const debugWorkspace = new SelfDebugWorkspace(join(debugHome, '.gestalt', 'self-debug'), join(process.env.CODEX_HOME ?? join(debugHome, '.codex'), 'agents', 'org-plan-executor.toml'), databasePath);
528
562
  const homeDirectory = options.homeDirectory ?? homedir();
529
- const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id));
563
+ const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id), ({ id }) => {
564
+ forgetOperations.assertAvailable(id);
565
+ const current = sessions.find(id);
566
+ if (!current)
567
+ throw new Error('SESSION_NOT_FOUND');
568
+ sessions.save(RelaySession.rehydrate(current).beginRecovery(new Date().toISOString()).snapshot, true);
569
+ });
530
570
  // Constructing the manager is cheap (no spawn until `ensure`); building it
531
571
  // before the model catalog lets the catalog reuse the gestalt-owned servers.
532
572
  const kimiManager = options.kimiServerManager ??
@@ -643,7 +683,7 @@ export async function composeRelayApp(options) {
643
683
  ? { ...session, executionPolicy, updatedAt: new Date().toISOString() }
644
684
  : session;
645
685
  };
646
- const protocol = protocolCompatibility(options.installedCodexVersion, generatedProtocolVersion);
686
+ const protocol = protocolCompatibility(options.installedCodexVersion);
647
687
  const providerAvailability = {
648
688
  codex: {
649
689
  available: options.installedCodexVersion !== null && protocol.compatible,
@@ -859,7 +899,7 @@ export async function composeRelayApp(options) {
859
899
  const timer = setTimeout(callback, delay);
860
900
  return () => clearTimeout(timer);
861
901
  }),
862
- start: async (session, current) => {
902
+ start: async (session, current) => withWorkspaceAdmission(session.id, async () => {
863
903
  if (!runtime || !current())
864
904
  throw new Error('PROVIDER_RETRY_CANCELLED');
865
905
  const started = await runtime.startTurn(session, providerContinuationPrompt, `provider-retry-${randomUUID()}`, new Date().toISOString(), current);
@@ -871,7 +911,7 @@ export async function composeRelayApp(options) {
871
911
  threadId: started.threadId,
872
912
  turnId: started.activeTurnId,
873
913
  });
874
- },
914
+ }),
875
915
  publish: (id, type, payload) => {
876
916
  events.publish(journal.append(id, type, payload, new Date().toISOString()));
877
917
  },
@@ -1538,6 +1578,7 @@ export async function composeRelayApp(options) {
1538
1578
  return current;
1539
1579
  };
1540
1580
  const publishSession = (session, beforeCommit, commit) => withScratchContainment(session.workspacePath, () => {
1581
+ assertWorkspaceOwner(session);
1541
1582
  beforeCommit?.();
1542
1583
  if (commit)
1543
1584
  commit();
@@ -1559,6 +1600,7 @@ export async function composeRelayApp(options) {
1559
1600
  /** Routes a session to the runtime owning its provider's llm service. */
1560
1601
  const ownerRuntime = (session) => session.provider === 'kimi' ? kimiRuntime : runtime;
1561
1602
  const scratchCleanup = new FilesystemScratchCleanup();
1603
+ const workspaceForget = new FilesystemWorkspaceForget(database);
1562
1604
  const cleanTmp = new CleanSessionScratch({
1563
1605
  sessions: () => sessions.list(),
1564
1606
  knownWorkspacePaths: async () => [root, ...sessions.knownWorkspacePaths()],
@@ -1580,7 +1622,7 @@ export async function composeRelayApp(options) {
1580
1622
  await ownerRuntime(session)?.releaseForForget(session);
1581
1623
  await playwright.waitForRelease(session.id);
1582
1624
  },
1583
- clean: (session, operationId) => scratchCleanup.cleanSession(session, () => {
1625
+ clean: (session, operationId) => workspaceForget.clean(session, operationId, () => {
1584
1626
  const operation = forgetOperations.find(session.id);
1585
1627
  return operation?.operationId === operationId && operation.phase === 'cleaning';
1586
1628
  }, () => sessions.list()),
@@ -1675,7 +1717,7 @@ export async function composeRelayApp(options) {
1675
1717
  const session = sessions.find(sessionId);
1676
1718
  if (!runtime || !session)
1677
1719
  return null;
1678
- return async (text, operationKey) => {
1720
+ return async (text, operationKey) => withWorkspaceAdmission(sessionId, async () => {
1679
1721
  const writer = await runtime.ensureWriter(session, new Date().toISOString());
1680
1722
  if (writer.session.activeTurnId)
1681
1723
  await runtime.queueTurnInput(writer.session, writer.session.activeTurnId, text, operationKey);
@@ -1690,7 +1732,7 @@ export async function composeRelayApp(options) {
1690
1732
  turnId: started.activeTurnId,
1691
1733
  });
1692
1734
  }
1693
- };
1735
+ });
1694
1736
  },
1695
1737
  },
1696
1738
  policy: {
@@ -1727,12 +1769,13 @@ export async function composeRelayApp(options) {
1727
1769
  defaultSkillProfile: options.explicitSkillProfile,
1728
1770
  activate: runtime || kimiRuntime
1729
1771
  ? async (session) => {
1772
+ assertWorkspaceOwner(session);
1730
1773
  const now = new Date().toISOString();
1731
1774
  dismissPendingInteractions(session.id, now);
1732
1775
  const owner = ownerRuntime(session);
1733
1776
  if (!owner)
1734
1777
  throw new Error('LLM_RUNTIME_UNAVAILABLE');
1735
- return owner.start(session, now);
1778
+ return withWorkspaceAdmission(session.id, () => owner.start(session, now));
1736
1779
  }
1737
1780
  : undefined,
1738
1781
  };
@@ -1749,7 +1792,7 @@ export async function composeRelayApp(options) {
1749
1792
  session.activeTurnId)
1750
1793
  orgPlanLaunches.save({ ...record, phase: 'submitting', manualRecoveryTurnId: session.activeTurnId }, record.phase);
1751
1794
  },
1752
- start: async (session, text, clientUserMessageId) => {
1795
+ start: async (session, text, clientUserMessageId) => withWorkspaceAdmission(session.id, async () => {
1753
1796
  providerRecovery.cancel(session.id);
1754
1797
  autopilot.manualSend(session.id);
1755
1798
  const owner = ownerRuntime(session);
@@ -1763,9 +1806,9 @@ export async function composeRelayApp(options) {
1763
1806
  !forgetOperations.find(session.id));
1764
1807
  });
1765
1808
  return owner.startTurn(session, text, clientUserMessageId, new Date().toISOString());
1766
- },
1809
+ }),
1767
1810
  ensureWriter: runtime || kimiRuntime
1768
- ? async (session) => {
1811
+ ? async (session) => withWorkspaceAdmission(session.id, async () => {
1769
1812
  if (supervisorOwnership(session.id) === 'replaced')
1770
1813
  throw new WriterAcquisitionError('supervisorReplaced');
1771
1814
  dismissPendingInteractions(session.id, new Date().toISOString());
@@ -1779,15 +1822,16 @@ export async function composeRelayApp(options) {
1779
1822
  persisted: true,
1780
1823
  };
1781
1824
  return owner.ensureWriter(await recoverExecutionPolicy(session), new Date().toISOString());
1782
- }
1825
+ })
1783
1826
  : undefined,
1784
1827
  releaseWriter: runtime || kimiRuntime
1785
- ? (id) => {
1828
+ ? async (id) => {
1786
1829
  providerRecovery.cancel(id);
1787
1830
  dismissPendingInteractions(id, new Date().toISOString());
1788
1831
  const session = sessions.find(id);
1789
1832
  const owner = session ? ownerRuntime(session) : null;
1790
- return owner ? owner.release(id) : Promise.resolve();
1833
+ if (owner && session)
1834
+ await owner.releaseForForget(session);
1791
1835
  }
1792
1836
  : undefined,
1793
1837
  onStarted: (session) => {
@@ -1845,11 +1889,37 @@ export async function composeRelayApp(options) {
1845
1889
  const reclaimableLaunchOwner = (record) => forgetOperations.find(record.sessionId)?.phase === 'completed' &&
1846
1890
  !sessions.find(record.sessionId) &&
1847
1891
  !runtime?.ownsWriter(record.sessionId);
1892
+ const workspaceBusy = (workspacePath) => {
1893
+ const session = sessions.list().find((session) => {
1894
+ if (!within(workspacePath, session.workspacePath) &&
1895
+ !within(session.workspacePath, workspacePath))
1896
+ return false;
1897
+ const snapshot = activity.snapshot(session.id, new Date().toISOString());
1898
+ return Boolean(session.activeTurnId ||
1899
+ pendingRootTurn(session.id) ||
1900
+ workspaceAdmissions.has(session.id) ||
1901
+ orgPlanStarting.has(session.id) ||
1902
+ snapshot.subagents.some((agent) => ['working', 'awaitingAgent'].includes(agent.state) ||
1903
+ agent.ownedProcesses?.some((process) => ['running', 'detached-active'].includes(process.state))));
1904
+ });
1905
+ return session
1906
+ ? {
1907
+ sessionId: session.id,
1908
+ reason: 'Another session is working in this workspace. Stop its work before starting a supervisor.',
1909
+ }
1910
+ : null;
1911
+ };
1848
1912
  const prepareOrgPlan = (reference, expectedRevision, skillProfile, ownUnpublishedLaunchId) => prepareOrgPlanSupervision(reference, {
1849
1913
  resolveReference: (ref) => orgPlanContext.resolveReference(ref),
1850
1914
  workspace: (path, revision) => orgPlanContext.workspace(path, revision),
1851
1915
  read: (workspacePath, planName) => workspacePlanCatalog.readExecution(workspacePath, planName),
1852
- runtimeAvailable: async () => providerAvailability.codex.available,
1916
+ runtimeAvailable: async () => protocol.compatible
1917
+ ? { available: true }
1918
+ : {
1919
+ available: false,
1920
+ code: protocol.code,
1921
+ reason: 'Codex CLI was not found when Mobile started. Install Codex and restart Mobile.',
1922
+ },
1853
1923
  policy: assessModelPolicyAdmission,
1854
1924
  settings: (workspacePath, selectedProfile) => prepareOrgPlanSettings(workspacePath, {
1855
1925
  defaults: sessionDefaults,
@@ -1859,8 +1929,8 @@ export async function composeRelayApp(options) {
1859
1929
  skillCatalog,
1860
1930
  defaultSkillProfile: options.explicitSkillProfile,
1861
1931
  }, selectedProfile),
1862
- owner: async (canonicalPath) => {
1863
- const pending = orgPlanLaunches.owner(canonicalPath);
1932
+ owner: async (canonicalPath, workspacePath) => {
1933
+ const pending = orgPlanLaunches.owner(canonicalPath) ?? orgPlanLaunches.workspaceOwner(workspacePath);
1864
1934
  const ownUnpublished = pending &&
1865
1935
  ownUnpublishedLaunchId &&
1866
1936
  pending.launchId === ownUnpublishedLaunchId &&
@@ -1868,7 +1938,13 @@ export async function composeRelayApp(options) {
1868
1938
  !runtime?.ownsWriter(pending.sessionId) &&
1869
1939
  ['reserved', 'creating'].includes(pending.phase);
1870
1940
  if (pending && !reclaimableLaunchOwner(pending) && !ownUnpublished)
1871
- return sessions.find(pending.sessionId) ? { sessionId: pending.sessionId } : {};
1941
+ return {
1942
+ ...(sessions.find(pending.sessionId) ? { sessionId: pending.sessionId } : {}),
1943
+ reason: 'This plan or an overlapping workspace is reserved by another supervisor. Open its session to continue, or forget it to release the reservation.',
1944
+ };
1945
+ const busy = workspaceBusy(workspacePath);
1946
+ if (busy && busy.sessionId !== pending?.sessionId)
1947
+ return busy;
1872
1948
  const identity = createHash('sha256').update(canonicalPath).digest('hex');
1873
1949
  const owner = sessions.list().find((session) => {
1874
1950
  if (!session.lastOrgPlan?.attached || session.lastOrgPlan.path !== canonicalPath)
@@ -1885,10 +1961,14 @@ export async function composeRelayApp(options) {
1885
1961
  prepare: prepareOrgPlan,
1886
1962
  createId: randomUUID,
1887
1963
  launches: orgPlanLaunches,
1888
- reclaimForgottenOwner: (path) => {
1964
+ workspaceBusy,
1965
+ reclaimForgottenOwner: (path, workspacePath) => {
1889
1966
  const record = orgPlanLaunches.owner(path);
1890
1967
  if (record && reclaimableLaunchOwner(record))
1891
1968
  orgPlanLaunches.releaseOwner(record);
1969
+ const workspaceOwner = orgPlanLaunches.workspaceOwner(workspacePath);
1970
+ if (workspaceOwner && reclaimableLaunchOwner(workspaceOwner))
1971
+ orgPlanLaunches.releaseOwner(workspaceOwner);
1892
1972
  },
1893
1973
  authorizeReplay: async (record) => {
1894
1974
  try {
@@ -2035,7 +2115,7 @@ export async function composeRelayApp(options) {
2035
2115
  version: '0.1.0',
2036
2116
  codex: {
2037
2117
  installedVersion: options.installedCodexVersion,
2038
- protocolVersion: generatedProtocolVersion,
2118
+ protocolVersion: null,
2039
2119
  compatible: protocol.compatible,
2040
2120
  },
2041
2121
  providers: providerAvailability,
@@ -2293,7 +2373,9 @@ export async function composeRelayApp(options) {
2293
2373
  activity.dispose(id);
2294
2374
  const session = sessions.find(id);
2295
2375
  const owner = session ? ownerRuntime(session) : null;
2296
- return owner ? owner.release(id) : Promise.resolve();
2376
+ if (session && owner)
2377
+ await owner.releaseForForget(session);
2378
+ await playwright.waitForRelease(id);
2297
2379
  }
2298
2380
  : undefined,
2299
2381
  replyInteraction: runtime || kimiRuntime
@@ -2356,7 +2438,7 @@ export async function composeRelayApp(options) {
2356
2438
  const result = await workspacePlanCatalog.read(session.workspacePath, planName);
2357
2439
  if (result.kind === 'available') {
2358
2440
  const planPath = resolve(session.workspacePath, ...planName.split('/'));
2359
- await planStatusSource.attach(session, planPath, (update) => acceptPlanUpdate(id, update));
2441
+ await planStatusSource.attach(session, planPath, (update) => acceptPlanUpdate(id, update), 'display-open');
2360
2442
  }
2361
2443
  return result;
2362
2444
  },
@@ -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 === 'authoring-start' || (sameAttachment && previous.supervision === false))
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.
@@ -54,17 +54,25 @@ export async function prepareOrgPlanSupervision(reference, deps, expectedRevisio
54
54
  const policy = deps.policy(file.plan);
55
55
  if (!policy.allowed)
56
56
  return blocked('MODEL_POLICY_UNAVAILABLE', policy.action);
57
+ let owner;
57
58
  try {
58
- const owner = await deps.owner(file.canonicalPath);
59
- if (owner)
60
- return {
61
- kind: 'blocked',
62
- code: 'ACTIVE_SUPERVISION',
63
- reason: 'This plan already has a supervisor. Open its session to continue or recover it.',
64
- ...(owner.sessionId ? { existingSessionId: owner.sessionId } : {}),
65
- };
66
- if (!(await deps.runtimeAvailable()))
67
- return blocked('CODEX_UNAVAILABLE', 'Codex supervision is currently unavailable.');
59
+ owner = await deps.owner(file.canonicalPath, context.workspace.path);
60
+ }
61
+ catch {
62
+ return blocked('WORKSPACE_UNAVAILABLE', 'Plan and workspace ownership could not be verified. Refresh and retry.');
63
+ }
64
+ if (owner)
65
+ return {
66
+ kind: 'blocked',
67
+ code: 'ACTIVE_SUPERVISION',
68
+ reason: owner.reason ??
69
+ 'This plan already has a supervisor. Open its session to continue or recover it.',
70
+ ...(owner.sessionId ? { existingSessionId: owner.sessionId } : {}),
71
+ };
72
+ try {
73
+ const runtime = await deps.runtimeAvailable();
74
+ if (!runtime.available)
75
+ return blocked(runtime.code, runtime.reason);
68
76
  }
69
77
  catch {
70
78
  return blocked('CODEX_UNAVAILABLE', 'Supervision availability could not be verified. Retry after refreshing.');
@@ -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. */
@@ -58,7 +59,15 @@ export async function startOrgPlanSupervision(request, deps) {
58
59
  code: 'GESTALT_CAPABILITIES_UNAVAILABLE',
59
60
  reason: 'The Org-plan skill changed before launch. Refresh and confirm again.',
60
61
  };
61
- deps.reclaimForgottenOwner?.(context.sourcePath);
62
+ deps.reclaimForgottenOwner?.(context.sourcePath, context.workspace.path);
63
+ const busy = deps.workspaceBusy?.(context.workspace.path);
64
+ if (busy)
65
+ return {
66
+ kind: 'blocked',
67
+ code: 'ACTIVE_SUPERVISION',
68
+ reason: busy.reason,
69
+ existingSessionId: busy.sessionId,
70
+ };
62
71
  const reservation = deps.launches.reserve({
63
72
  launchId: input.launchId,
64
73
  requestFingerprint: fingerprint,
@@ -75,7 +84,7 @@ export async function startOrgPlanSupervision(request, deps) {
75
84
  return {
76
85
  kind: 'blocked',
77
86
  code: 'ACTIVE_SUPERVISION',
78
- reason: 'This plan already has a supervisor launch. Open its session to continue or recover it.',
87
+ reason: 'This plan or an overlapping workspace already has a supervisor launch. Open its session to continue or recover it.',
79
88
  ...(deps.sessions.find(record.sessionId) ? { existingSessionId: record.sessionId } : {}),
80
89
  };
81
90
  if (record.requestFingerprint !== fingerprint)
@@ -130,11 +139,12 @@ async function continueLaunch(record, deps) {
130
139
  }
131
140
  if ((record.phase === 'reserved' || record.phase === 'creating') && !session) {
132
141
  if (record.notPersisted && !deps.launches.acquireOwner(record)) {
133
- const owner = deps.launches.owner(record.canonicalPath);
142
+ const owner = deps.launches.owner(record.canonicalPath) ??
143
+ deps.launches.workspaceOwner(record.context.workspace.path);
134
144
  return {
135
145
  kind: 'blocked',
136
146
  code: 'ACTIVE_SUPERVISION',
137
- reason: 'Another launch now owns this plan.',
147
+ reason: 'Another supervisor launch now owns this plan or an overlapping workspace.',
138
148
  ...(owner && deps.sessions.find(owner.sessionId)
139
149
  ? { existingSessionId: owner.sessionId }
140
150
  : {}),
@@ -149,6 +159,15 @@ async function continueLaunch(record, deps) {
149
159
  }
150
160
  catch (error) {
151
161
  session = deps.sessions.find(record.sessionId);
162
+ if (!session && error instanceof WorkspaceSessionConflict) {
163
+ deps.launches.revokePublication(record, deps.sessions);
164
+ return {
165
+ kind: 'blocked',
166
+ code: 'WORKSPACE_BUSY',
167
+ reason: error.message,
168
+ existingSessionId: error.sessionId,
169
+ };
170
+ }
152
171
  if (session)
153
172
  deps.launches.save({ ...record, phase: 'session' }, 'creating');
154
173
  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
+ }
@@ -13,6 +13,13 @@ export class WriterAcquisitionError extends Error {
13
13
  }
14
14
  export function writerAcquisitionProblem(kind) {
15
15
  switch (kind) {
16
+ case 'workspaceLocked':
17
+ return {
18
+ status: 409,
19
+ code: 'SESSION_WORKSPACE_LOCKED',
20
+ retryable: false,
21
+ detail: 'An Org-plan supervisor owns this workspace. Continue in its session, or forget that session to release the reservation.',
22
+ };
16
23
  case 'supervisorReplaced':
17
24
  return {
18
25
  status: 409,
@@ -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
@@ -8,6 +8,7 @@ import { parseStartSessionRequest } from './request.js';
8
8
  import { startSession } from './use-case.js';
9
9
  import { SkillProfileError } from '../../skills/model/errors.js';
10
10
  import { problem } from '../../../platform/http/problem.js';
11
+ import { WriterAcquisitionError, writerAcquisitionProblem, } from '../application/writer-acquisition.js';
11
12
  export function registerStartSession(app, deps) {
12
13
  app.post('/api/sessions', { bodyLimit: 4 * 1024 }, async (request, reply) => {
13
14
  const key = idempotencyKey(request.headers);
@@ -30,6 +31,13 @@ export function registerStartSession(app, deps) {
30
31
  }
31
32
  catch (error) {
32
33
  deps.reportFailure?.('start-session', error);
34
+ if (error instanceof WriterAcquisitionError) {
35
+ const failure = writerAcquisitionProblem(error.kind);
36
+ return reply
37
+ .code(failure.status)
38
+ .type('application/problem+json')
39
+ .send(problem(failure.code, failure.status, failure.detail, failure.retryable));
40
+ }
33
41
  if (error instanceof Error && error.message === 'CODEX_EXECUTOR_MODEL_UNAVAILABLE')
34
42
  return reply
35
43
  .code(400)