gestalt-mobile 0.67.2 → 0.68.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.
Files changed (35) hide show
  1. package/dist/client/assets/index-BZ3ivopC.js +183 -0
  2. package/dist/client/assets/index-DRbCnCbk.css +1 -0
  3. package/dist/client/index.html +2 -2
  4. package/dist/server/server/composition.contracts.js +976 -0
  5. package/dist/server/server/composition.js +330 -57
  6. package/dist/server/server/features/autopilot/application/service.js +18 -1
  7. package/dist/server/server/features/plans/application/org-plan-launch-store.js +6 -0
  8. package/dist/server/server/features/plans/application/prepare-org-plan-settings.js +66 -0
  9. package/dist/server/server/features/plans/application/prepare-org-plan-supervision.js +86 -0
  10. package/dist/server/server/features/plans/application/start-org-plan-supervision.js +323 -0
  11. package/dist/server/server/features/plans/execute-plan/endpoint.js +27 -0
  12. package/dist/server/server/features/plans/get-workspace-plan/endpoint.js +2 -1
  13. package/dist/server/server/features/plans/open-plan/endpoint.js +2 -1
  14. package/dist/server/server/features/plans/prepare-supervision/endpoint.js +52 -0
  15. package/dist/server/server/features/plans/register-routes.js +6 -0
  16. package/dist/server/server/features/sessions/application/resolve-session-skills.js +35 -0
  17. package/dist/server/server/features/sessions/application/start-settings.js +2 -1
  18. package/dist/server/server/features/sessions/register-routes.js +1 -0
  19. package/dist/server/server/features/sessions/start-session/endpoint.js +5 -0
  20. package/dist/server/server/features/sessions/start-session/use-case.js +7 -32
  21. package/dist/server/server/features/sessions/start-turn/endpoint.js +9 -167
  22. package/dist/server/server/features/sessions/start-turn/use-case.js +243 -0
  23. package/dist/server/server/features/skills/application/read-global-profiles.js +34 -0
  24. package/dist/server/server/features/skills/list-profiles/endpoint.js +9 -33
  25. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +11 -0
  26. package/dist/server/server/platform/codex/session-runtime.js +20 -6
  27. package/dist/server/server/platform/persistence/migrate.js +12 -0
  28. package/dist/server/server/platform/persistence/sqlite-org-plan-launch-store.js +215 -0
  29. package/dist/server/server/platform/plans/filesystem-org-plan-context.js +99 -0
  30. package/dist/server/server/platform/plans/filesystem-workspace-plan-catalog.js +36 -3
  31. package/dist/server/shared/contracts/org-plan-execution.js +46 -0
  32. package/dist/server/shared/contracts/session-defaults.js +33 -3
  33. package/package.json +1 -1
  34. package/dist/client/assets/index-DcXYn8rY.js +0 -128
  35. package/dist/client/assets/index-DxsD-jG4.css +0 -1
@@ -27,6 +27,7 @@ import { gestaltTestRunnerDynamicTool } from '../shared/contracts/host-tests.js'
27
27
  import { SelfDebugWorkspace } from './platform/self-debug/workspace.js';
28
28
  import { createSelfDebugSession, debugExecutionSettings, } from './features/self-debug/create-session.js';
29
29
  import { startSession } from './features/sessions/start-session/use-case.js';
30
+ import { createStartTurn, readAcceptedTurn, } from './features/sessions/start-turn/use-case.js';
30
31
  import { FilesystemWorkspaceCatalog } from './platform/catalog/filesystem-workspace-catalog.js';
31
32
  import { FilesystemWorkspaceFiles } from './platform/filesystem/filesystem-workspace-files.js';
32
33
  import { protocolCompatibility } from './platform/codex/protocol-compatibility.js';
@@ -98,8 +99,14 @@ import { ManagedPlaywright } from './platform/codex/managed-playwright.js';
98
99
  import { isManagedPlaywrightCall } from '../shared/contracts/managed-playwright.js';
99
100
  import { compileSkillOverride } from './features/skills/model/skill-profile.js';
100
101
  import { SupervisedPlanRegistry } from './features/plans/application/supervised-plan-registry.js';
102
+ import { prepareOrgPlanSupervision } from './features/plans/application/prepare-org-plan-supervision.js';
103
+ import { startOrgPlanSupervision, OrgPlanSessionNotPublished, } from './features/plans/application/start-org-plan-supervision.js';
104
+ import { SqliteOrgPlanLaunchStore } from './platform/persistence/sqlite-org-plan-launch-store.js';
105
+ import { resolveSessionSkillSelection } from './features/sessions/application/resolve-session-skills.js';
106
+ import { prepareOrgPlanSettings } from './features/plans/application/prepare-org-plan-settings.js';
101
107
  import { FilesystemPlanStatusSource } from './platform/plans/filesystem-plan-status-source.js';
102
108
  import { FilesystemWorkspacePlanCatalog } from './platform/plans/filesystem-workspace-plan-catalog.js';
109
+ import { FilesystemOrgPlanContext } from './platform/plans/filesystem-org-plan-context.js';
103
110
  import { FilesystemPlanArchiver } from './platform/plans/filesystem-plan-archiver.js';
104
111
  import { checkpointPlanMeasurement } from './platform/plans/plan-measurement-command.js';
105
112
  import { PlanMeasurementRefresh } from './platform/plans/plan-measurement-refresh.js';
@@ -115,7 +122,7 @@ import { isOrgPlanHealthCall, parseOrgPlanHealthArguments, } from '../shared/con
115
122
  import { compactSupervisionSnapshot, SupervisionSnapshots, } from './features/autopilot/application/supervision-snapshot.js';
116
123
  import { ExecutorModelEvidenceReader } from './features/plans/application/executor-model-evidence.js';
117
124
  import { ExecutorLaunchValidationReader } from './features/plans/application/executor-launch-validation.js';
118
- import { requireModelPolicyAdmission } from './features/plans/domain/model-policy-admission.js';
125
+ import { assessModelPolicyAdmission, requireModelPolicyAdmission, } from './features/plans/domain/model-policy-admission.js';
119
126
  import { currentExecutableL1Index } from './features/plans/domain/supervised-plan.js';
120
127
  import { AttentionResolution } from './features/org-plan-attention/application/resolve.js';
121
128
  import { AttentionAcknowledgement } from './features/org-plan-attention/application/acknowledgement.js';
@@ -158,6 +165,23 @@ export async function composeRelayApp(options) {
158
165
  const toolEfficiency = new ToolEfficiencyProjection(new SqliteToolEfficiencyStore(database));
159
166
  const interactions = new SqlitePendingInteractionStore(database);
160
167
  const idempotency = new SqliteIdempotencyStore(database);
168
+ const orgPlanLaunches = new SqliteOrgPlanLaunchStore(database);
169
+ const reconcileOrgPlanReceipt = (sessionId) => {
170
+ const record = orgPlanLaunches.forSession(sessionId);
171
+ if (record?.phase !== 'submitting' || !record.bootstrapFingerprint)
172
+ return;
173
+ const receipt = readAcceptedTurn(idempotency, sessionId, `org-plan-bootstrap:${record.launchId}`, record.bootstrapFingerprint);
174
+ if (receipt?.activeTurnId)
175
+ orgPlanLaunches.save({
176
+ ...record,
177
+ phase: 'accepted',
178
+ bootstrap: {
179
+ kind: 'accepted',
180
+ requestId: `org-plan-bootstrap:${record.launchId}`,
181
+ turnId: receipt.activeTurnId,
182
+ },
183
+ }, 'submitting');
184
+ };
161
185
  const autopilotStore = new SqliteAutopilotStore(database);
162
186
  const takeoverStore = new SqliteSupervisionTakeoverStore(database, autopilotStore);
163
187
  const supervisedPlans = new SupervisedPlanRegistry();
@@ -296,6 +320,10 @@ export async function composeRelayApp(options) {
296
320
  return true;
297
321
  },
298
322
  });
323
+ let ordinaryTurnPending = () => false;
324
+ const pendingRootTurn = (sessionId) => ordinaryTurnPending(sessionId) ||
325
+ (orgPlanLaunches.forSession(sessionId)?.phase === 'submitting' &&
326
+ !orgPlanLaunches.forSession(sessionId)?.manualRecoveryTurnId);
299
327
  const autopilot = new AutopilotCoordinator({
300
328
  supervisorOwnership,
301
329
  pendingProcessResult: (sessionId) => hostTests?.hasUnreadResult(sessionId) ?? false,
@@ -314,6 +342,7 @@ export async function composeRelayApp(options) {
314
342
  ? options.autopilotActivity(sessionId)
315
343
  : activity.snapshot(sessionId, new Date().toISOString()),
316
344
  pendingInteraction: (sessionId) => blockingInteractions(sessionId).length > 0,
345
+ pendingTurn: pendingRootTurn,
317
346
  attention: (sessionId) => {
318
347
  const interaction = interactions
319
348
  .list(sessionId)
@@ -344,6 +373,7 @@ export async function composeRelayApp(options) {
344
373
  const current = () => {
345
374
  const state = autopilotStore.find(sessionId);
346
375
  return Boolean(state &&
376
+ !pendingRootTurn(sessionId) &&
347
377
  state.requestedEnabled &&
348
378
  state.generation === generation &&
349
379
  state.lastControlId === controlId);
@@ -568,6 +598,7 @@ export async function composeRelayApp(options) {
568
598
  };
569
599
  }, skillProvenance);
570
600
  const workspacePlanCatalog = new FilesystemWorkspacePlanCatalog();
601
+ const orgPlanContext = new FilesystemOrgPlanContext(workspaces, (id) => sessions.find(id));
571
602
  const planArchiver = new FilesystemPlanArchiver();
572
603
  const resolveSkills = async (session) => {
573
604
  const catalog = session.provider === 'kimi'
@@ -1465,11 +1496,8 @@ export async function composeRelayApp(options) {
1465
1496
  return runtime.readPlanMeasurement(session);
1466
1497
  }, (planPath, stepId, snapshot) => checkpointPlanMeasurement(planMeasurementHelperPath, planPath, stepId, snapshot));
1467
1498
  }
1468
- const saveSession = (session) => {
1469
- if (forgetOperations.find(session.id))
1470
- return;
1471
- const prior = sessions.find(session.id);
1472
- sessions.save(session);
1499
+ const notifySessionSaved = (session, prior) => {
1500
+ reconcileOrgPlanReceipt(session.id);
1473
1501
  events.publish(journal.append(session.id, 'session.updated', session, session.updatedAt));
1474
1502
  const becameRuntimeReady = prior &&
1475
1503
  prior.state !== 'ready' &&
@@ -1482,7 +1510,28 @@ export async function composeRelayApp(options) {
1482
1510
  if (becameRuntimeReady)
1483
1511
  autopilot.restore(session.id);
1484
1512
  };
1485
- const publishSession = (session) => withScratchContainment(session.workspacePath, () => saveSession(session));
1513
+ const saveSession = (session) => {
1514
+ if (forgetOperations.find(session.id))
1515
+ return;
1516
+ const prior = sessions.find(session.id);
1517
+ sessions.save(session);
1518
+ notifySessionSaved(session, prior);
1519
+ };
1520
+ const notifyCommittedSession = (id, prior) => {
1521
+ if (forgetOperations.find(id))
1522
+ return null;
1523
+ const current = sessions.find(id);
1524
+ if (current)
1525
+ notifySessionSaved(current, prior);
1526
+ return current;
1527
+ };
1528
+ const publishSession = (session, beforeCommit, commit) => withScratchContainment(session.workspacePath, () => {
1529
+ beforeCommit?.();
1530
+ if (commit)
1531
+ commit();
1532
+ else
1533
+ saveSession(session);
1534
+ });
1486
1535
  if (kimiRuntime) {
1487
1536
  // A gestalt-owned kimi web process exited or its websocket dropped: stop
1488
1537
  // the durable session like the codex supervisor does, without a resume
@@ -1651,6 +1700,271 @@ export async function composeRelayApp(options) {
1651
1700
  throw error;
1652
1701
  }
1653
1702
  }
1703
+ const orgPlanStarting = new Map();
1704
+ const ordinarySessionLifecycle = {
1705
+ createId: randomUUID,
1706
+ now: () => new Date().toISOString(),
1707
+ save: saveSession,
1708
+ publish: publishSession,
1709
+ workspaces,
1710
+ profiles: options.profiles,
1711
+ models,
1712
+ sessionModels,
1713
+ skillProfiles,
1714
+ skillCatalog,
1715
+ defaultSkillProfile: options.explicitSkillProfile,
1716
+ activate: runtime || kimiRuntime
1717
+ ? async (session) => {
1718
+ const now = new Date().toISOString();
1719
+ dismissPendingInteractions(session.id, now);
1720
+ const owner = ownerRuntime(session);
1721
+ if (!owner)
1722
+ throw new Error('LLM_RUNTIME_UNAVAILABLE');
1723
+ return owner.start(session, now);
1724
+ }
1725
+ : undefined,
1726
+ };
1727
+ const ordinaryTurnDependencies = {
1728
+ find: (id) => withPendingInteractions(sessions.find(id)),
1729
+ save: saveSession,
1730
+ idempotency,
1731
+ onSettled: (id) => autopilot.activityChanged(id),
1732
+ onAccepted: (session, key) => {
1733
+ const record = orgPlanLaunches.forSession(session.id);
1734
+ if (record &&
1735
+ ['session', 'submitting'].includes(record.phase) &&
1736
+ key !== `org-plan-bootstrap:${record.launchId}` &&
1737
+ session.activeTurnId)
1738
+ orgPlanLaunches.save({ ...record, phase: 'submitting', manualRecoveryTurnId: session.activeTurnId }, record.phase);
1739
+ },
1740
+ start: async (session, text, clientUserMessageId) => {
1741
+ providerRecovery.cancel(session.id);
1742
+ autopilot.manualSend(session.id);
1743
+ const owner = ownerRuntime(session);
1744
+ if (!owner)
1745
+ throw new Error('LLM_RUNTIME_UNAVAILABLE');
1746
+ if (session.provider === 'codex' && runtime)
1747
+ return runtime.startTurn(session, text, clientUserMessageId, new Date().toISOString(), () => {
1748
+ const current = sessions.find(session.id);
1749
+ return Boolean(current?.desiredState === 'active' &&
1750
+ current.threadId === session.threadId &&
1751
+ !forgetOperations.find(session.id));
1752
+ });
1753
+ return owner.startTurn(session, text, clientUserMessageId, new Date().toISOString());
1754
+ },
1755
+ ensureWriter: runtime || kimiRuntime
1756
+ ? async (session) => {
1757
+ if (supervisorOwnership(session.id) === 'replaced')
1758
+ throw new WriterAcquisitionError('supervisorReplaced');
1759
+ dismissPendingInteractions(session.id, new Date().toISOString());
1760
+ const owner = ownerRuntime(session);
1761
+ if (!owner)
1762
+ throw new Error('LLM_RUNTIME_UNAVAILABLE');
1763
+ if (!session.threadId && orgPlanLaunches.forSession(session.id))
1764
+ return {
1765
+ session: await activateInitialPlanSession(session),
1766
+ replacementCreated: false,
1767
+ persisted: true,
1768
+ };
1769
+ return owner.ensureWriter(await recoverExecutionPolicy(session), new Date().toISOString());
1770
+ }
1771
+ : undefined,
1772
+ releaseWriter: runtime || kimiRuntime
1773
+ ? (id) => {
1774
+ providerRecovery.cancel(id);
1775
+ dismissPendingInteractions(id, new Date().toISOString());
1776
+ const session = sessions.find(id);
1777
+ const owner = session ? ownerRuntime(session) : null;
1778
+ return owner ? owner.release(id) : Promise.resolve();
1779
+ }
1780
+ : undefined,
1781
+ onStarted: (session) => {
1782
+ activity.observe({
1783
+ sessionId: session.id,
1784
+ occurredAt: session.updatedAt,
1785
+ kind: 'turnStarted',
1786
+ ...(session.threadId ? { threadId: session.threadId } : {}),
1787
+ ...(session.activeTurnId ? { turnId: session.activeTurnId } : {}),
1788
+ });
1789
+ planMeasurementRefresh?.refreshNow(session.id);
1790
+ },
1791
+ };
1792
+ const initialActivationSessions = {
1793
+ find: (id) => (forgetOperations.find(id) ? null : sessions.find(id)),
1794
+ save: (session) => sessions.save(session),
1795
+ };
1796
+ const activateInitialPlanSession = async (session) => {
1797
+ if (!runtime || session.provider !== 'codex')
1798
+ throw new Error('LLM_RUNTIME_UNAVAILABLE');
1799
+ const attempt = orgPlanLaunches.claimInitialActivation(session.id, initialActivationSessions);
1800
+ if (!attempt)
1801
+ throw new Error('ORG_PLAN_INITIAL_ACTIVATION_UNSETTLED');
1802
+ const assertCurrent = () => {
1803
+ if (!orgPlanLaunches.initialActivationCurrent(attempt, initialActivationSessions))
1804
+ throw new Error('ORG_PLAN_INITIAL_ACTIVATION_FENCED');
1805
+ };
1806
+ try {
1807
+ dismissPendingInteractions(session.id, new Date().toISOString());
1808
+ const active = await runtime.start(session, new Date().toISOString(), {
1809
+ assertCurrent,
1810
+ beforeThreadStart: () => {
1811
+ if (!orgPlanLaunches.requestInitialThread(attempt, initialActivationSessions))
1812
+ throw new Error('ORG_PLAN_INITIAL_ACTIVATION_FENCED');
1813
+ },
1814
+ });
1815
+ if (!orgPlanLaunches.completeInitialActivation(attempt, active, initialActivationSessions)) {
1816
+ await runtime.release(session.id);
1817
+ throw new Error('ORG_PLAN_INITIAL_ACTIVATION_FENCED');
1818
+ }
1819
+ const current = notifyCommittedSession(session.id, session);
1820
+ if (!current || current.desiredState !== 'active') {
1821
+ await runtime.release(session.id);
1822
+ throw new Error('ORG_PLAN_INITIAL_ACTIVATION_FENCED');
1823
+ }
1824
+ return current;
1825
+ }
1826
+ catch (error) {
1827
+ orgPlanLaunches.failInitialActivation(attempt);
1828
+ throw error;
1829
+ }
1830
+ };
1831
+ const submitSessionTurn = createStartTurn(ordinaryTurnDependencies);
1832
+ ordinaryTurnPending = (id) => submitSessionTurn.pending?.(id) ?? false;
1833
+ const reclaimableLaunchOwner = (record) => forgetOperations.find(record.sessionId)?.phase === 'completed' &&
1834
+ !sessions.find(record.sessionId) &&
1835
+ !runtime?.ownsWriter(record.sessionId);
1836
+ const prepareOrgPlan = (reference, expectedRevision, skillProfile, ownUnpublishedLaunchId) => prepareOrgPlanSupervision(reference, {
1837
+ resolveReference: (ref) => orgPlanContext.resolveReference(ref),
1838
+ workspace: (path, revision) => orgPlanContext.workspace(path, revision),
1839
+ read: (workspacePath, planName) => workspacePlanCatalog.readExecution(workspacePath, planName),
1840
+ runtimeAvailable: async () => providerAvailability.codex.available,
1841
+ policy: assessModelPolicyAdmission,
1842
+ settings: (workspacePath, selectedProfile) => prepareOrgPlanSettings(workspacePath, {
1843
+ defaults: sessionDefaults,
1844
+ models: sessionModels,
1845
+ profiles: options.profiles,
1846
+ skillProfiles,
1847
+ skillCatalog,
1848
+ defaultSkillProfile: options.explicitSkillProfile,
1849
+ }, selectedProfile),
1850
+ owner: async (canonicalPath) => {
1851
+ const pending = orgPlanLaunches.owner(canonicalPath);
1852
+ const ownUnpublished = pending &&
1853
+ ownUnpublishedLaunchId &&
1854
+ pending.launchId === ownUnpublishedLaunchId &&
1855
+ !sessions.find(pending.sessionId) &&
1856
+ !runtime?.ownsWriter(pending.sessionId) &&
1857
+ ['reserved', 'creating'].includes(pending.phase);
1858
+ if (pending && !reclaimableLaunchOwner(pending) && !ownUnpublished)
1859
+ return sessions.find(pending.sessionId) ? { sessionId: pending.sessionId } : {};
1860
+ const owner = sessions
1861
+ .list()
1862
+ .find((session) => session.lastOrgPlan?.attached && session.lastOrgPlan.path === canonicalPath);
1863
+ return owner ? { sessionId: owner.id } : null;
1864
+ },
1865
+ }, expectedRevision, skillProfile);
1866
+ // Both transports and future internal consumers retain the same scoped admission boundary.
1867
+ const startPlanSupervision = (request) => startOrgPlanSupervision(request, {
1868
+ prepare: prepareOrgPlan,
1869
+ createId: randomUUID,
1870
+ launches: orgPlanLaunches,
1871
+ reclaimForgottenOwner: (path) => {
1872
+ const record = orgPlanLaunches.owner(path);
1873
+ if (record && reclaimableLaunchOwner(record))
1874
+ orgPlanLaunches.releaseOwner(record);
1875
+ },
1876
+ authorizeReplay: async (record) => {
1877
+ try {
1878
+ const workspace = await workspaces.resolve(record.context.workspace.id);
1879
+ return workspace.realPath === record.context.workspace.path;
1880
+ }
1881
+ catch {
1882
+ return false;
1883
+ }
1884
+ },
1885
+ captureSkills: (context) => resolveSessionSkillSelection({
1886
+ workspacePath: context.workspace.path,
1887
+ provider: 'codex',
1888
+ profile: 'default',
1889
+ ...(context.settings.skillProfile
1890
+ ? { skillProfile: context.settings.skillProfile }
1891
+ : {}),
1892
+ }, { skillProfiles, skillCatalog, defaultSkillProfile: options.explicitSkillProfile }),
1893
+ sessions: {
1894
+ create: async (id, context, selection, publication) => {
1895
+ orgPlanStarting.set(id, (orgPlanStarting.get(id) ?? 0) + 1);
1896
+ let publicationEntered = false;
1897
+ let ownsPublication = false;
1898
+ let publishedSession = null;
1899
+ try {
1900
+ return await startSession({ ...context.settings, workspaceId: context.workspace.id }, {
1901
+ ...ordinarySessionLifecycle,
1902
+ createId: () => id,
1903
+ inheritedSkillSelection: selection,
1904
+ // Both lifecycle stages already commit through the guarded launch store.
1905
+ save: () => { },
1906
+ publish: (session) => publishSession(session, () => {
1907
+ publicationEntered = true;
1908
+ }, () => {
1909
+ const receipt = orgPlanLaunches.publishSession(publication, session, sessions);
1910
+ ownsPublication = receipt.created;
1911
+ publishedSession = receipt.session;
1912
+ if (receipt.created)
1913
+ notifyCommittedSession(id, null);
1914
+ }),
1915
+ activate: async (session) => {
1916
+ if (!ownsPublication)
1917
+ return sessions.find(id) ?? publishedSession ?? session;
1918
+ const active = await activateInitialPlanSession(session);
1919
+ const current = sessions.find(id);
1920
+ if (!current || current.desiredState === 'stopped') {
1921
+ await ownerRuntime(active)?.release(id);
1922
+ if (!current)
1923
+ throw new Error('SESSION_UNAVAILABLE');
1924
+ return current;
1925
+ }
1926
+ return active;
1927
+ },
1928
+ });
1929
+ }
1930
+ catch (error) {
1931
+ if (!publicationEntered)
1932
+ throw new OrgPlanSessionNotPublished();
1933
+ throw error;
1934
+ }
1935
+ finally {
1936
+ const count = (orgPlanStarting.get(id) ?? 1) - 1;
1937
+ if (count)
1938
+ orgPlanStarting.set(id, count);
1939
+ else
1940
+ orgPlanStarting.delete(id);
1941
+ }
1942
+ },
1943
+ recover: async (session) => {
1944
+ if (orgPlanStarting.has(session.id))
1945
+ return null;
1946
+ if (!session.threadId)
1947
+ return activateInitialPlanSession(session);
1948
+ const acquisition = await ordinaryTurnDependencies.ensureWriter?.(session);
1949
+ if (!acquisition)
1950
+ return null;
1951
+ const current = sessions.find(session.id);
1952
+ if (!current || current.desiredState !== 'active') {
1953
+ await ownerRuntime(acquisition.session)?.release(session.id);
1954
+ return current;
1955
+ }
1956
+ saveSession(acquisition.session);
1957
+ return acquisition.session;
1958
+ },
1959
+ find: (id) => sessions.find(id),
1960
+ unavailable: (id) => Boolean(forgetOperations.find(id)),
1961
+ },
1962
+ submitTurn: submitSessionTurn,
1963
+ acceptedTurn: (record) => record.bootstrapFingerprint
1964
+ ? readAcceptedTurn(idempotency, record.sessionId, `org-plan-bootstrap:${record.launchId}`, record.bootstrapFingerprint)
1965
+ : null,
1966
+ onSettled: ordinaryTurnDependencies.onSettled,
1967
+ });
1654
1968
  let app;
1655
1969
  try {
1656
1970
  if (options.testRunnerEnabled !== false) {
@@ -1843,6 +2157,7 @@ export async function composeRelayApp(options) {
1843
2157
  }
1844
2158
  : undefined,
1845
2159
  sessionRoutes: {
2160
+ ...ordinarySessionLifecycle,
1846
2161
  forget: (id) => forgetSessions.execute(id),
1847
2162
  forgetOperation: (id) => forgetOperations.find(id),
1848
2163
  createId: randomUUID,
@@ -1857,56 +2172,12 @@ export async function composeRelayApp(options) {
1857
2172
  skillProfiles,
1858
2173
  skillCatalog,
1859
2174
  defaultSkillProfile: options.explicitSkillProfile,
1860
- activate: runtime || kimiRuntime
1861
- ? async (session) => {
1862
- const now = new Date().toISOString();
1863
- dismissPendingInteractions(session.id, now);
1864
- const owner = ownerRuntime(session);
1865
- if (!owner)
1866
- throw new Error('LLM_RUNTIME_UNAVAILABLE');
1867
- return owner.start(session, now);
1868
- }
1869
- : undefined,
1870
- startTurn: runtime || kimiRuntime
1871
- ? async (session, text, clientUserMessageId) => {
1872
- providerRecovery.cancel(session.id);
1873
- autopilot.manualSend(session.id);
1874
- const owner = ownerRuntime(session);
1875
- if (!owner)
1876
- throw new Error('LLM_RUNTIME_UNAVAILABLE');
1877
- return owner.startTurn(session, text, clientUserMessageId, new Date().toISOString());
1878
- }
1879
- : undefined,
1880
- ensureWriter: runtime || kimiRuntime
1881
- ? async (session) => {
1882
- if (supervisorOwnership(session.id) === 'replaced')
1883
- throw new WriterAcquisitionError('supervisorReplaced');
1884
- dismissPendingInteractions(session.id, new Date().toISOString());
1885
- const owner = ownerRuntime(session);
1886
- if (!owner)
1887
- throw new Error('LLM_RUNTIME_UNAVAILABLE');
1888
- return owner.ensureWriter(await recoverExecutionPolicy(session), new Date().toISOString());
1889
- }
1890
- : undefined,
1891
- releaseWriter: runtime || kimiRuntime
1892
- ? (id) => {
1893
- providerRecovery.cancel(id);
1894
- dismissPendingInteractions(id, new Date().toISOString());
1895
- const session = sessions.find(id);
1896
- const owner = session ? ownerRuntime(session) : null;
1897
- return owner ? owner.release(id) : Promise.resolve();
1898
- }
1899
- : undefined,
1900
- onTurnStarted: (session) => {
1901
- activity.observe({
1902
- sessionId: session.id,
1903
- occurredAt: session.updatedAt,
1904
- kind: 'turnStarted',
1905
- ...(session.threadId ? { threadId: session.threadId } : {}),
1906
- ...(session.activeTurnId ? { turnId: session.activeTurnId } : {}),
1907
- });
1908
- planMeasurementRefresh?.refreshNow(session.id);
1909
- },
2175
+ activate: ordinarySessionLifecycle.activate,
2176
+ startTurn: runtime || kimiRuntime ? ordinaryTurnDependencies.start : undefined,
2177
+ ensureWriter: ordinaryTurnDependencies.ensureWriter,
2178
+ releaseWriter: ordinaryTurnDependencies.releaseWriter,
2179
+ onTurnStarted: ordinaryTurnDependencies.onStarted,
2180
+ submitTurn: submitSessionTurn,
1910
2181
  agentActivity: (id) => activity.snapshot(id, new Date().toISOString()),
1911
2182
  toolEfficiency: (id) => toolEfficiency.snapshot(id),
1912
2183
  retrievalReadiness: (id) => runtime?.readRetrievalReadiness(id) ?? Promise.resolve(null),
@@ -2092,6 +2363,8 @@ export async function composeRelayApp(options) {
2092
2363
  },
2093
2364
  },
2094
2365
  workspacePlanRoutes: { workspaces, plans: workspacePlanCatalog, archiver: planArchiver },
2366
+ prepareOrgPlanRoutes: { prepare: prepareOrgPlan },
2367
+ executeOrgPlanRoutes: { startOrgPlanSupervision: startPlanSupervision },
2095
2368
  workspaceFileRoutes: {
2096
2369
  workspaces,
2097
2370
  files: workspaceFiles,
@@ -756,6 +756,8 @@ export class AutopilotCoordinator {
756
756
  this.parkedSubscriptions.delete(sessionId);
757
757
  }
758
758
  evaluate(sessionId) {
759
+ if (this.deps.pendingTurn?.(sessionId))
760
+ return this.snapshot(sessionId);
759
761
  const binding = this.reconcileExecutorBinding(sessionId);
760
762
  const prior = this.deps.store.find(sessionId);
761
763
  if (!prior)
@@ -1442,6 +1444,11 @@ export class AutopilotCoordinator {
1442
1444
  * while a new identity can receive its own explicit supervision request.
1443
1445
  */
1444
1446
  supervisionStarted(sessionId) {
1447
+ const sessionIntent = this.deps.session(sessionId);
1448
+ if (sessionIntent?.desiredState === 'stopped' ||
1449
+ sessionIntent?.state === 'stopped' ||
1450
+ sessionIntent?.state === 'released')
1451
+ return this.snapshot(sessionId);
1445
1452
  if (this.deps.supervisorOwnership?.(sessionId) &&
1446
1453
  this.deps.supervisorOwnership(sessionId) !== 'owned')
1447
1454
  return { code: 'AUTOPILOT_SESSION_UNAVAILABLE' };
@@ -1495,6 +1502,8 @@ export class AutopilotCoordinator {
1495
1502
  }
1496
1503
  /** Reacts only to fresh actor status; plan mutations are not scheduling signals. */
1497
1504
  activityChanged(sessionId) {
1505
+ if (this.deps.pendingTurn?.(sessionId))
1506
+ return;
1498
1507
  this.reconcileExecutorBinding(sessionId);
1499
1508
  let prior = this.deps.store.find(sessionId);
1500
1509
  if (!prior?.requestedEnabled)
@@ -1763,6 +1772,8 @@ export class AutopilotCoordinator {
1763
1772
  }
1764
1773
  async fire(sessionId, generation) {
1765
1774
  this.timers.delete(sessionId);
1775
+ if (this.deps.pendingTurn?.(sessionId))
1776
+ return;
1766
1777
  const binding = this.reconcileExecutorBinding(sessionId);
1767
1778
  const current = this.deps.store.find(sessionId);
1768
1779
  if (!current || current.generation !== generation || !current.requestedEnabled)
@@ -2007,6 +2018,8 @@ export class AutopilotCoordinator {
2007
2018
  }, Math.max(0, Date.parse(resumeAt) - Date.parse(this.deps.now()))));
2008
2019
  }
2009
2020
  async enforceSupervisedLifecycle(sessionId, event) {
2021
+ if (this.deps.pendingTurn?.(sessionId))
2022
+ return true;
2010
2023
  if (this.rejectModelPolicyExecution(sessionId))
2011
2024
  return true;
2012
2025
  const binding = this.reconcileExecutorBinding(sessionId);
@@ -2825,7 +2838,10 @@ export class AutopilotCoordinator {
2825
2838
  boundaryState: state.state,
2826
2839
  }
2827
2840
  : null;
2828
- if (!commandExecutor || !fence || this.deps.session(sessionId)?.activeTurnId)
2841
+ if (!commandExecutor ||
2842
+ !fence ||
2843
+ this.deps.session(sessionId)?.activeTurnId ||
2844
+ this.deps.pendingTurn?.(sessionId))
2829
2845
  return;
2830
2846
  const requested = this.executorCommand(fence, commandExecutor, generation, trigger);
2831
2847
  const command = this.scheduleExecutorCommand(sessionId, requested);
@@ -2869,6 +2885,7 @@ export class AutopilotCoordinator {
2869
2885
  !activity.subagents.some((child) => child.canonicalPosition &&
2870
2886
  ['working', 'awaitingAgent', 'awaitingHuman'].includes(child.state)) &&
2871
2887
  current?.requestedEnabled &&
2888
+ !this.deps.pendingTurn?.(sessionId) &&
2872
2889
  !this.deps.pendingInteraction(sessionId) &&
2873
2890
  current.generation === fence.sessionGeneration &&
2874
2891
  current.state === fence.boundaryState &&
@@ -0,0 +1,6 @@
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 {};
@@ -0,0 +1,66 @@
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 { sessionDefaultsSchema, resolveNewSessionDefaults, } from '../../../../shared/contracts/session-defaults.js';
7
+ import { readGlobalSkillProfiles } from '../../skills/application/read-global-profiles.js';
8
+ import { resolveSessionSkillSelection } from '../../sessions/application/resolve-session-skills.js';
9
+ /** Read-only counterpart of the ordinary New session form and skill snapshot. */
10
+ export async function prepareOrgPlanSettings(workspacePath, deps, skillProfile) {
11
+ const unavailable = (code, reason) => ({ kind: 'unavailable', code, reason });
12
+ let saved;
13
+ try {
14
+ const read = await deps.defaults.read();
15
+ saved = read === null ? null : sessionDefaultsSchema.parse(read);
16
+ }
17
+ catch {
18
+ return unavailable('SESSION_DEFAULTS_UNAVAILABLE', 'Saved New session defaults could not be read. Refresh after repairing them.');
19
+ }
20
+ let models;
21
+ try {
22
+ models = await deps.models.list('codex');
23
+ }
24
+ catch {
25
+ return unavailable('MODEL_UNAVAILABLE', 'The Codex model catalog is unavailable. Refresh and retry.');
26
+ }
27
+ const defaults = resolveNewSessionDefaults(saved, 'codex', models);
28
+ if (!models.includes(defaults.model) || !models.includes(defaults.executorModel))
29
+ return unavailable('MODEL_UNAVAILABLE', 'The saved supervisor or executor model is unavailable in Codex. Update New session defaults and retry.');
30
+ try {
31
+ await deps.profiles.require('default');
32
+ const entries = await readGlobalSkillProfiles(deps.skillProfiles);
33
+ const warnings = [];
34
+ let selected = skillProfile ?? defaults.skillProfile;
35
+ const valid = (name) => entries.some((entry) => entry.name === name && 'profile' in entry);
36
+ if (selected && !valid(selected)) {
37
+ if (skillProfile !== undefined)
38
+ return unavailable('SKILL_PROFILE_UNAVAILABLE', 'The selected supervisor skill profile disappeared or is invalid. Refresh and choose again.');
39
+ warnings.push('The saved skill profile is unavailable. Default is selected; choose a supervisor profile before confirming.');
40
+ selected = '';
41
+ }
42
+ const effectiveSkillSelection = await resolveSessionSkillSelection({
43
+ workspacePath,
44
+ provider: 'codex',
45
+ profile: 'default',
46
+ ...(selected ? { skillProfile: selected } : {}),
47
+ }, deps);
48
+ if (!effectiveSkillSelection.skills.some((skill) => skill.name === 'gestalt:org-plan' && skill.enabled))
49
+ return unavailable('GESTALT_CAPABILITIES_UNAVAILABLE', 'The Org-plan skill is unavailable in the ordinary Codex session catalog. Restore Gestalt capabilities and retry.');
50
+ const { workspaceId: _workspaceId, ...settings } = defaults;
51
+ void _workspaceId;
52
+ return {
53
+ kind: 'available',
54
+ settings: { ...settings, provider: 'codex', profile: 'default', skillProfile: selected },
55
+ effectiveSkillSelection,
56
+ skillProfiles: entries.map((entry) => ({
57
+ name: entry.name,
58
+ ...('error' in entry ? { error: entry.error.message } : {}),
59
+ })),
60
+ warnings: [...warnings, ...(effectiveSkillSelection.warnings ?? [])],
61
+ };
62
+ }
63
+ catch {
64
+ return unavailable('SKILL_PROFILE_UNAVAILABLE', 'Supervisor profiles or workspace skills could not be read. Refresh and retry.');
65
+ }
66
+ }