gestalt-mobile 0.62.0 → 0.62.2

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 CHANGED
@@ -248,8 +248,10 @@ permissions are never broadened to repair them. Kimi behavior is unchanged.
248
248
  Managed launch provides `GESTALT_MANAGER_BIN`. Direct Mobile launch discovers
249
249
  `gestalt` on `PATH`, or accepts an absolute executable path through that same
250
250
  environment variable. Without a manager or installed xerj, chat starts normally.
251
- `XERJ_READY_TIMEOUT_MS` bounds optional readiness, including discovery and the
252
- actual connection, with a five-second default. Startup never installs xerj,
251
+ `XERJ_READY_TIMEOUT_MS` bounds optional backend preparation with a five-second
252
+ default. XERJ's native MCP handshake gets a separate five-second allowance;
253
+ connection verification gets another bounded five seconds after thread startup.
254
+ Slow preparation cannot consume the handshake budget. Startup never installs xerj,
253
255
  downloads models or indexes repositories. Install explicitly with
254
256
  `gestalt xerj install`; inspect readiness with `gestalt xerj status`.
255
257
 
@@ -560,6 +562,24 @@ durable history, deletes only the exact smoke-created Codex threads through the
560
562
  app-server afterwards, and always removes its temporary state. It reports
561
563
  `SKIP` when the isolated profile is unavailable.
562
564
 
565
+ ## Transient model capacity failures
566
+
567
+ When a Codex root turn ends with `serverOverloaded` or `rateLimitExceeded`,
568
+ Mobile waits one minute before attempting to continue the same task with
569
+ `Continue.`. Recovery is bounded to two attempts per failure episode and requires
570
+ a settled turn, a live writer, reconciled idle agents and no pending interaction.
571
+
572
+ Autopilot retains its plan and authority checks. Ordinary sessions can recover
573
+ with Autopilot off; recovery never enables it. A new user message, interruption,
574
+ session stop/release, explicit Autopilot toggle or changed session cancels the
575
+ pending continuation. Relay shutdown discards pending ordinary-session retries.
576
+ Account usage limits, session budgets, context exhaustion and authorization or
577
+ policy failures require intervention and are not automatically retried.
578
+
579
+ Traces include `session.provider-retry-*` events for ordinary-session recovery,
580
+ and `autopilot.provider-*` events for supervised recovery. These retain structured
581
+ codes and turn identifiers without provider error prose or task text.
582
+
563
583
  ## Control-plane traces
564
584
 
565
585
  When an existing Chat is selected, the header menu offers **DEBUG**. Its confirmation shows the source session's live identifiers and installed component versions. Confirming captures a redacted JSON trace immediately. Debug creation does not start, steer, resume, or replace the source runtime.
@@ -1511,6 +1511,111 @@ describe('production composition', () => {
1511
1511
  expect(JSON.stringify(await app.inject('/api/sessions'))).not.toContain('Inspect the active supervised Org Plan');
1512
1512
  await app.close();
1513
1513
  });
1514
+ it.each(['autopilot', 'ordinary', 'manual-send', 'stopped'])('production provider recovery uses minimal continuation and respects %s ownership', async (mode) => {
1515
+ const timers = [];
1516
+ const fixture = await createProductionAutopilotFixture({
1517
+ autopilotSchedule: (callback, delay) => {
1518
+ const timer = { callback, delay, cancelled: false };
1519
+ timers.push(timer);
1520
+ return () => {
1521
+ timer.cancelled = true;
1522
+ };
1523
+ },
1524
+ });
1525
+ onTestFinished(() => fixture.app.close());
1526
+ const initial = timers.find((timer) => !timer.cancelled);
1527
+ initial.cancelled = true;
1528
+ initial.callback();
1529
+ const starts = () => fixture.handles
1530
+ .flatMap((handle) => handle.requests)
1531
+ .filter((request) => request.method === 'turn/start');
1532
+ await vi.waitFor(() => expect(starts()).toHaveLength(1));
1533
+ const session = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
1534
+ const handle = fixture.handles.find((candidate) => candidate.calls.includes('turn/start'));
1535
+ if (mode !== 'autopilot')
1536
+ await fixture.app.inject({
1537
+ method: 'PUT',
1538
+ url: `/api/sessions/${fixture.sessionId}/autopilot`,
1539
+ payload: { enabled: false },
1540
+ });
1541
+ handle.notify({
1542
+ method: 'error',
1543
+ params: {
1544
+ threadId: session.threadId,
1545
+ turnId: session.activeTurnId,
1546
+ error: { codexErrorInfo: 'serverOverloaded', message: 'private capacity detail' },
1547
+ willRetry: false,
1548
+ },
1549
+ });
1550
+ handle.notify({
1551
+ method: 'turn/completed',
1552
+ params: {
1553
+ threadId: session.threadId,
1554
+ turn: {
1555
+ id: session.activeTurnId,
1556
+ status: 'failed',
1557
+ },
1558
+ },
1559
+ });
1560
+ const retry = timers.find((timer) => !timer.cancelled && timer.delay === 60_000);
1561
+ expect(retry).toBeDefined();
1562
+ expect(starts()).toHaveLength(1);
1563
+ if (mode === 'manual-send') {
1564
+ expect((await fixture.app.inject({
1565
+ method: 'POST',
1566
+ url: `/api/sessions/${fixture.sessionId}/turns`,
1567
+ payload: { text: 'new instruction' },
1568
+ })).statusCode).toBe(202);
1569
+ retry.callback();
1570
+ expect(starts()).toHaveLength(2);
1571
+ expect(starts().at(-1).params).toMatchObject({
1572
+ input: [{ type: 'text', text: 'new instruction' }],
1573
+ });
1574
+ }
1575
+ else if (mode === 'stopped') {
1576
+ expect((await fixture.app.inject({
1577
+ method: 'POST',
1578
+ url: `/api/sessions/${fixture.sessionId}/stop`,
1579
+ })).statusCode).toBe(202);
1580
+ retry.callback();
1581
+ expect(starts()).toHaveLength(1);
1582
+ }
1583
+ else {
1584
+ vi.useFakeTimers({ toFake: ['Date'] });
1585
+ onTestFinished(() => {
1586
+ vi.useRealTimers();
1587
+ });
1588
+ vi.setSystemTime(Date.now() + 60_000);
1589
+ retry.cancelled = true;
1590
+ retry.callback();
1591
+ if (mode === 'autopilot') {
1592
+ await vi.waitFor(() => expect(timers.some((timer) => !timer.cancelled)).toBe(true));
1593
+ const continuation = timers.find((timer) => !timer.cancelled);
1594
+ vi.setSystemTime(Date.now() + continuation.delay);
1595
+ continuation.cancelled = true;
1596
+ continuation.callback();
1597
+ }
1598
+ await vi.waitFor(async () => {
1599
+ const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'), {
1600
+ readOnly: true,
1601
+ });
1602
+ const rows = database
1603
+ .prepare("SELECT type,payload_json FROM session_events WHERE session_id=? AND type LIKE 'session.provider-retry-%'")
1604
+ .all(fixture.sessionId);
1605
+ database.close();
1606
+ expect(starts(), JSON.stringify(rows)).toHaveLength(2);
1607
+ });
1608
+ expect(starts().at(-1).params).toMatchObject({
1609
+ input: [{ type: 'text', text: 'Continue.' }],
1610
+ });
1611
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot
1612
+ .enabled).toBe(mode === 'autopilot');
1613
+ const trace = exportControlPlaneTrace(join(fixture.dataDir, 'relay.sqlite'), fixture.sessionId);
1614
+ if (mode === 'ordinary')
1615
+ expect(trace.events.some((event) => event.type === 'session.provider-retry-started')).toBe(true);
1616
+ expect(JSON.stringify(trace)).not.toContain('private capacity detail');
1617
+ }
1618
+ });
1514
1619
  it('production correlates overload recovery with a settled root turn and cancels it on Off', async () => {
1515
1620
  const timers = [];
1516
1621
  const fixture = await createProductionAutopilotFixture({
@@ -1553,7 +1658,7 @@ describe('production composition', () => {
1553
1658
  pending: true,
1554
1659
  settled: true,
1555
1660
  });
1556
- const retry = timers.find((timer) => timer.delay === 30_000 && !timer.cancelled);
1661
+ const retry = timers.find((timer) => timer.delay === 60_000 && !timer.cancelled);
1557
1662
  expect(retry).toBeDefined();
1558
1663
  await fixture.app.inject({
1559
1664
  method: 'PUT',
@@ -32,6 +32,8 @@ import { createRecentThreadLister } from './platform/codex/recent-thread-lister.
32
32
  import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
33
33
  import { normalizeCodexNotification } from './platform/codex/normalizer.js';
34
34
  import { decodeCodexFailure } from './platform/codex/codex-failure.js';
35
+ import { providerContinuationPrompt } from '../shared/contracts/provider-failure.js';
36
+ import { SessionProviderRecovery } from './features/sessions/application/provider-recovery.js';
35
37
  import { parseMcpStartupStatus } from '../shared/contracts/mcp-startup-failure.js';
36
38
  import { KimiSessionRuntime } from './platform/kimi/kimi-session-runtime.js';
37
39
  import { KimiWebServerManager } from './platform/kimi/kimi-web-server-manager.js';
@@ -346,10 +348,12 @@ export async function composeRelayApp(options) {
346
348
  sessions.find(sessionId)?.activeTurnId ||
347
349
  blockingInteractions(sessionId).length)
348
350
  throw new Error('AUTOPILOT_START_UNAVAILABLE');
349
- const continuationPrompt = launchIdentity
350
- ? autopilotExecutorLaunchPrompt(launchIdentity, supervisedPlans.find(sessionId))
351
- : AUTOPILOT_CONTINUATION_PROMPT;
352
351
  const recovery = autopilotStore.find(sessionId);
352
+ const continuationPrompt = recovery?.providerRetry?.resumeRoot
353
+ ? providerContinuationPrompt
354
+ : launchIdentity
355
+ ? autopilotExecutorLaunchPrompt(launchIdentity, supervisedPlans.find(sessionId))
356
+ : AUTOPILOT_CONTINUATION_PROMPT;
353
357
  const executorRecovery = recovery?.supervision?.outcome === 'probeRequired' &&
354
358
  recovery.executor?.commands?.some((command) => command.status === 'issued' && !command.processAction);
355
359
  const recoveryInstruction = executorRecovery
@@ -745,6 +749,49 @@ export async function composeRelayApp(options) {
745
749
  };
746
750
  let closing = false;
747
751
  let runtime = null;
752
+ const providerRecovery = new SessionProviderRecovery({
753
+ find: (id) => sessions.find(id),
754
+ authority: (id) => {
755
+ const state = autopilotStore.find(id);
756
+ if (closing ||
757
+ !runtime?.ownsWriter(id) ||
758
+ blockingInteractions(id).length ||
759
+ (state && (state.requestedEnabled || state.state !== 'disabled')))
760
+ return null;
761
+ // Idle observations can advance Autopilot's generation even while Off.
762
+ // An explicit toggle/send clears this failure identity instead.
763
+ return state?.providerFailureTurnId ?? 'no-failure';
764
+ },
765
+ reconcile: async (id) => {
766
+ await activity.refresh(id);
767
+ const snapshot = activity.snapshot(id, new Date().toISOString());
768
+ return (snapshot.confidence === 'fresh' &&
769
+ snapshot.root.state === 'idle' &&
770
+ snapshot.subagents.every((agent) => agent.state === 'idle' &&
771
+ !agent.ownedProcesses?.some((process) => ['running', 'detached-active'].includes(process.state))));
772
+ },
773
+ schedule: options.autopilotSchedule ??
774
+ ((callback, delay) => {
775
+ const timer = setTimeout(callback, delay);
776
+ return () => clearTimeout(timer);
777
+ }),
778
+ start: async (session, current) => {
779
+ if (!runtime || !current())
780
+ throw new Error('PROVIDER_RETRY_CANCELLED');
781
+ const started = await runtime.startTurn(session, providerContinuationPrompt, `provider-retry-${randomUUID()}`, new Date().toISOString(), current);
782
+ saveSession(started);
783
+ activity.observe({
784
+ sessionId: started.id,
785
+ occurredAt: started.updatedAt,
786
+ kind: 'turnStarted',
787
+ threadId: started.threadId,
788
+ turnId: started.activeTurnId,
789
+ });
790
+ },
791
+ publish: (id, type, payload) => {
792
+ events.publish(journal.append(id, type, payload, new Date().toISOString()));
793
+ },
794
+ });
748
795
  let kimiRuntime = null;
749
796
  const executorPolicyContext = (sessionId) => {
750
797
  const session = sessions.find(sessionId);
@@ -892,14 +939,25 @@ export async function composeRelayApp(options) {
892
939
  const normalized = normalizeCodexNotification(sessionId, 0, occurredAt, notification, currentSession?.workspacePath, currentSession?.activeTurnId, resolvedOrigin);
893
940
  // Pause before activity/completion can schedule another automatic turn.
894
941
  // Unknown threads must not stop an unrelated session on the shared server.
895
- const providerFailure = decodeCodexFailure(notification);
942
+ // Codex may emit the terminal error separately and omit it from the
943
+ // completion. Carry forward only evidence for this exact active root.
944
+ const settledFailure = resolvedOrigin.kind === 'root' &&
945
+ completionTurnId === currentSession?.activeTurnId &&
946
+ notification.params?.turn?.status ===
947
+ 'failed'
948
+ ? autopilotStore.find(sessionId)
949
+ : null;
950
+ const providerFailure = decodeCodexFailure(notification) ??
951
+ (settledFailure?.providerFailureTurnId === completionTurnId
952
+ ? settledFailure?.providerFailure
953
+ : undefined);
896
954
  if (resolvedOrigin.kind !== 'unknown' && providerFailure)
897
955
  autopilot.providerFailed(sessionId, providerFailure, {
898
956
  actor: resolvedOrigin.kind === 'root' ? 'root' : 'child',
899
957
  turnId: completionTurnId ??
900
958
  (typeof notification.params?.turnId === 'string'
901
959
  ? notification.params.turnId
902
- : undefined),
960
+ : resolvedOrigin.physicalTurnId),
903
961
  settled: notification.method === 'turn/completed',
904
962
  });
905
963
  const rootCommandId = resolvedOrigin.kind === 'root' ? completedCommandId(notification) : null;
@@ -939,8 +997,13 @@ export async function composeRelayApp(options) {
939
997
  // these facts project the idle root; its first evaluation can therefore
940
998
  // still see the pre-completion activity snapshot. This second evaluation
941
999
  // is idempotently fenced by the durable control row.
942
- if (completedSession)
1000
+ if (completedSession) {
1001
+ if (providerFailure && completionTurnId)
1002
+ providerRecovery.failed(completedSession, completionTurnId, providerFailure);
1003
+ else
1004
+ providerRecovery.cancel(sessionId);
943
1005
  autopilot.evaluate(sessionId);
1006
+ }
944
1007
  // Lifecycle notifications are fast transition evidence, while
945
1008
  // thread/list is the bounded topology authority. Reconcile after the
946
1009
  // mutation so canonical identity and every retained child reach both
@@ -1510,6 +1573,7 @@ export async function composeRelayApp(options) {
1510
1573
  // An exited child has released our writer. Do not repeatedly resume a
1511
1574
  // durable thread: another Codex client may acquire it between callbacks.
1512
1575
  recoverExitedSession = (sessionId) => {
1576
+ providerRecovery.cancel(sessionId);
1513
1577
  supervisor.cancel(sessionId);
1514
1578
  const session = sessions.find(sessionId);
1515
1579
  if (session) {
@@ -1741,6 +1805,7 @@ export async function composeRelayApp(options) {
1741
1805
  : undefined,
1742
1806
  startTurn: runtime || kimiRuntime
1743
1807
  ? async (session, text, clientUserMessageId) => {
1808
+ providerRecovery.cancel(session.id);
1744
1809
  autopilot.manualSend(session.id);
1745
1810
  const owner = ownerRuntime(session);
1746
1811
  if (!owner)
@@ -1759,6 +1824,7 @@ export async function composeRelayApp(options) {
1759
1824
  : undefined,
1760
1825
  releaseWriter: runtime || kimiRuntime
1761
1826
  ? (id) => {
1827
+ providerRecovery.cancel(id);
1762
1828
  dismissPendingInteractions(id, new Date().toISOString());
1763
1829
  const session = sessions.find(id);
1764
1830
  const owner = session ? ownerRuntime(session) : null;
@@ -1796,12 +1862,14 @@ export async function composeRelayApp(options) {
1796
1862
  activityHistory: (sessionId, throughSequence) => journal.activityHistory(sessionId, throughSequence),
1797
1863
  interruptTurn: runtime || kimiRuntime
1798
1864
  ? (session, turnId) => {
1865
+ providerRecovery.cancel(session.id);
1799
1866
  const owner = ownerRuntime(session);
1800
1867
  return owner ? owner.interruptTurn(session, turnId) : Promise.resolve();
1801
1868
  }
1802
1869
  : undefined,
1803
1870
  queueTurnInput: runtime || kimiRuntime
1804
1871
  ? (session, turnId, text, clientUserMessageId) => {
1872
+ providerRecovery.cancel(session.id);
1805
1873
  autopilot.manualSend(session.id);
1806
1874
  const owner = ownerRuntime(session);
1807
1875
  if (!owner)
@@ -1849,10 +1917,12 @@ export async function composeRelayApp(options) {
1849
1917
  })
1850
1918
  : undefined,
1851
1919
  release: (session) => {
1920
+ providerRecovery.cancel(session.id);
1852
1921
  autopilot.cancel(session.id, 'sessionEnded');
1853
1922
  return RelaySession.rehydrate(session).release(new Date().toISOString()).snapshot;
1854
1923
  },
1855
1924
  remove: (id) => {
1925
+ providerRecovery.cancel(id);
1856
1926
  autopilot.cancel(id, 'sessionEnded');
1857
1927
  activity.dispose(id);
1858
1928
  sessions.remove(id);
@@ -1860,6 +1930,7 @@ export async function composeRelayApp(options) {
1860
1930
  idempotency,
1861
1931
  close: runtime || kimiRuntime
1862
1932
  ? async (id) => {
1933
+ providerRecovery.cancel(id);
1863
1934
  autopilot.cancel(id, 'sessionEnded');
1864
1935
  await hostTests?.cancelSession(id);
1865
1936
  planMeasurementRefresh?.stop(id);
@@ -1872,6 +1943,7 @@ export async function composeRelayApp(options) {
1872
1943
  : undefined,
1873
1944
  replyInteraction: runtime || kimiRuntime
1874
1945
  ? async (sessionId, requestId, value) => {
1946
+ providerRecovery.cancel(sessionId);
1875
1947
  const session = sessions.find(sessionId);
1876
1948
  const owner = session ? ownerRuntime(session) : null;
1877
1949
  if (await owner?.resolveServerRequest(sessionId, requestId, value))
@@ -2244,6 +2316,7 @@ export async function composeRelayApp(options) {
2244
2316
  });
2245
2317
  app.addHook('onClose', async () => {
2246
2318
  closing = true;
2319
+ providerRecovery.dispose();
2247
2320
  await hostTests?.close();
2248
2321
  await xerjIndexer.close();
2249
2322
  for (const [sessionId, timer] of capacityRecoveryTimers) {
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { parseOrgPlanAgentIdentity } from '../../../../shared/org-plan-position.js';
7
7
  import { assessModelPolicyAdmission } from '../../plans/domain/model-policy-admission.js';
8
+ import { isTransientProviderFailure, providerRetryDelayMs, providerRetryLimit, } from '../../../../shared/contracts/provider-failure.js';
8
9
  import { requirePlanFingerprint } from '../domain/plan-fingerprint.js';
9
10
  import { AutopilotStateError } from '../domain/persisted-state-error.js';
10
11
  import { canTransitionExecutorCommand, retainExecutorCommands, } from '../domain/executor-commands.js';
@@ -912,7 +913,7 @@ export class AutopilotCoordinator {
912
913
  if (retry &&
913
914
  !retry.pending &&
914
915
  retry.turnId === origin?.turnId &&
915
- failure.code === 'serverOverloaded')
916
+ isTransientProviderFailure(failure))
916
917
  return false;
917
918
  if (retry && retry.turnId === origin?.turnId && state.providerFailure?.code === failure.code) {
918
919
  if (origin?.settled && !retry.settled)
@@ -928,11 +929,11 @@ export class AutopilotCoordinator {
928
929
  const enabled = state.requestedEnabled || Boolean(retry?.pending);
929
930
  const attempt = (retry?.attempt ?? 0) + 1;
930
931
  const recoverable = enabled &&
931
- failure.code === 'serverOverloaded' &&
932
+ isTransientProviderFailure(failure) &&
932
933
  origin?.actor === 'root' &&
933
934
  Boolean(origin.turnId) &&
934
935
  origin.turnId === this.deps.session(sessionId)?.activeTurnId &&
935
- attempt <= 2;
936
+ attempt <= providerRetryLimit;
936
937
  const event = {
937
938
  sessionId,
938
939
  type: 'autopilot.provider-failed',
@@ -963,7 +964,7 @@ export class AutopilotCoordinator {
963
964
  requestedEnabled: false,
964
965
  generation: state.generation + 1,
965
966
  nextEvaluationAt: recoverable
966
- ? new Date(Date.parse(now) + 30_000 * attempt).toISOString()
967
+ ? new Date(Date.parse(now) + providerRetryDelayMs).toISOString()
967
968
  : null,
968
969
  ...(cancelled ? { lastControlId: null } : {}),
969
970
  stopReason: failure.code === 'usageLimitExceeded' ? 'usageLimitExceeded' : 'providerError',
@@ -973,7 +974,7 @@ export class AutopilotCoordinator {
973
974
  ? {
974
975
  turnId: origin.turnId,
975
976
  attempt,
976
- notBefore: new Date(Date.parse(now) + 30_000 * attempt).toISOString(),
977
+ notBefore: new Date(Date.parse(now) + providerRetryDelayMs).toISOString(),
977
978
  settled: origin.settled,
978
979
  pending: true,
979
980
  resumeRoot: false,
@@ -989,7 +990,7 @@ export class AutopilotCoordinator {
989
990
  this.providerTimers.set(sessionId, this.deps.schedule(() => {
990
991
  this.providerTimers.delete(sessionId);
991
992
  this.enqueue(sessionId, () => this.retryProvider(sessionId, next.generation));
992
- }, 30_000 * attempt));
993
+ }, providerRetryDelayMs));
993
994
  return true;
994
995
  }
995
996
  async retryProvider(sessionId, generation) {
@@ -6,7 +6,7 @@
6
6
  import { readTransportDiagnostics } from '../../platform/persistence/sqlite-transport-diagnostics.js';
7
7
  import { DatabaseSync } from 'node:sqlite';
8
8
  import { parseMcpStartupStatus } from '../../../shared/contracts/mcp-startup-failure.js';
9
- const relevant = /^(?:org-plan\.|autopilot\.|agent\.activity\.|session\.status\.)/;
9
+ const relevant = /^(?:org-plan\.|autopilot\.|agent\.activity\.|session\.status\.|session\.provider-retry-)/;
10
10
  const statusTypes = ['autopilot.updated', 'agent.activity.updated', 'session.status.updated'];
11
11
  // Export structural telemetry only. Event types alone do not imply payload safety.
12
12
  const diagnosticFields = new Set([
@@ -133,7 +133,7 @@ export function exportControlPlaneTrace(databasePath, sessionId, generatedAt = n
133
133
  // journal. Keep a recent status tail and disclose every omitted row.
134
134
  const statusEventLimit = 100;
135
135
  const transitionEventLimit = 4900;
136
- const relevantWhere = "(type LIKE 'org-plan.%' OR type LIKE 'autopilot.%' OR type LIKE 'agent.activity.%' OR type LIKE 'session.status.%')";
136
+ const relevantWhere = "(type LIKE 'org-plan.%' OR type LIKE 'autopilot.%' OR type LIKE 'agent.activity.%' OR type LIKE 'session.status.%' OR type LIKE 'session.provider-retry-%')";
137
137
  const statusWhere = `type IN (${statusTypes.map(() => '?').join(',')})`;
138
138
  const counts = database
139
139
  .prepare(`SELECT SUM(CASE WHEN ${statusWhere} THEN 1 ELSE 0 END) AS statuses, COUNT(*) AS total FROM session_events WHERE session_id = ? AND ${relevantWhere}`)
@@ -0,0 +1,109 @@
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 { isTransientProviderFailure, providerRetryDelayMs, providerRetryLimit, } from '../../../../shared/contracts/provider-failure.js';
7
+ /** Live task recovery never enables Autopilot or recreates work after relay shutdown. */
8
+ export class SessionProviderRecovery {
9
+ deps;
10
+ episodes = new Map();
11
+ constructor(deps) {
12
+ this.deps = deps;
13
+ }
14
+ failed(session, turnId, failure) {
15
+ if (!isTransientProviderFailure(failure)) {
16
+ this.cancel(session.id);
17
+ return;
18
+ }
19
+ const authority = this.deps.authority(session.id);
20
+ if (!session.threadId ||
21
+ session.state !== 'ready' ||
22
+ session.desiredState !== 'active' ||
23
+ session.activeTurnId ||
24
+ authority === null)
25
+ return;
26
+ const previous = this.episodes.get(session.id);
27
+ if (previous?.turnId === turnId)
28
+ return;
29
+ const attempt = (previous?.attempt ?? 0) + 1;
30
+ previous?.cancel();
31
+ if (attempt > providerRetryLimit) {
32
+ if (previous)
33
+ previous.turnId = turnId;
34
+ this.deps.publish(session.id, 'session.provider-retry-exhausted', {
35
+ turnId,
36
+ retryAttempt: providerRetryLimit,
37
+ });
38
+ return;
39
+ }
40
+ const episode = {
41
+ threadId: session.threadId,
42
+ turnId,
43
+ updatedAt: session.updatedAt,
44
+ attempt,
45
+ authority,
46
+ pending: true,
47
+ cancel: () => { },
48
+ };
49
+ this.episodes.set(session.id, episode);
50
+ episode.cancel = this.deps.schedule(() => {
51
+ void this.retry(session.id, episode);
52
+ }, providerRetryDelayMs);
53
+ this.deps.publish(session.id, 'session.provider-retry-scheduled', {
54
+ turnId,
55
+ retryAttempt: attempt,
56
+ providerFailure: failure,
57
+ });
58
+ }
59
+ /** Manual sends, interruptions, successful turns and lifecycle changes end an episode. */
60
+ cancel(id) {
61
+ this.episodes.get(id)?.cancel();
62
+ this.episodes.delete(id);
63
+ }
64
+ dispose() {
65
+ for (const id of this.episodes.keys())
66
+ this.cancel(id);
67
+ }
68
+ current(id, episode) {
69
+ const session = this.deps.find(id);
70
+ return Boolean(this.episodes.get(id) === episode &&
71
+ session?.threadId === episode.threadId &&
72
+ session.updatedAt === episode.updatedAt &&
73
+ session.state === 'ready' &&
74
+ session.desiredState === 'active' &&
75
+ !session.activeTurnId &&
76
+ this.deps.authority(id) === episode.authority);
77
+ }
78
+ async retry(id, episode) {
79
+ if (this.episodes.get(id) !== episode || !episode.pending)
80
+ return;
81
+ episode.pending = false; // Duplicate timer delivery cannot dispatch a second start.
82
+ let started = false;
83
+ let reason = 'sessionChanged';
84
+ try {
85
+ if (this.current(id, episode)) {
86
+ reason = 'activityNotIdle';
87
+ if (await this.deps.reconcile(id)) {
88
+ reason = 'sessionChanged';
89
+ if (this.current(id, episode)) {
90
+ reason = 'startUnconfirmed';
91
+ await this.deps.start(this.deps.find(id), () => this.current(id, episode));
92
+ started = true;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ catch {
98
+ // An unconfirmed start is never replayed. A new terminal provider event
99
+ // may request the next bounded attempt; transport prose is not persisted.
100
+ }
101
+ if (this.episodes.get(id) !== episode)
102
+ return;
103
+ this.deps.publish(id, started ? 'session.provider-retry-started' : 'session.provider-retry-abandoned', {
104
+ turnId: episode.turnId,
105
+ retryAttempt: episode.attempt,
106
+ ...(started ? {} : { reason }),
107
+ });
108
+ }
109
+ }
@@ -28,7 +28,7 @@ export class CodexCapabilities {
28
28
  const serenaPath = input.skills.find((skill) => skill.name === 'gestalt:serena')?.path;
29
29
  const state = {
30
30
  repositories: new RepositoryReadiness(input.cwd),
31
- deadline: Math.max(input.deadline, serena.ready ? serena.deadline : input.deadline),
31
+ deadline: Math.max(input.deadline, xerj.ready ? xerj.deadline : input.deadline, serena.ready ? serena.deadline : input.deadline),
32
32
  get ready() {
33
33
  return xerj.ready || serena.ready;
34
34
  },
@@ -290,7 +290,7 @@ export class CodexSessionRuntime {
290
290
  const pending = resource.pendingRequests.get(requestId);
291
291
  return pending && !pending.settling ? 'available' : 'cleared';
292
292
  }
293
- async startTurn(session, text, clientUserMessageId, now) {
293
+ async startTurn(session, text, clientUserMessageId, now, mayStart) {
294
294
  const resumeRequested = this.retrieval?.needsResume?.(session);
295
295
  if (resumeRequested === true || (resumeRequested && (await resumeRequested))) {
296
296
  // The same root resumes only at an idle boundary. Never recycle a writer
@@ -310,6 +310,8 @@ export class CodexSessionRuntime {
310
310
  const resource = this.sessions.get(session.id);
311
311
  if (!resource || !session.threadId)
312
312
  throw new Error('CODEX_SESSION_NOT_RUNNING');
313
+ if (mayStart && !mayStart())
314
+ throw new Error('CODEX_TURN_START_CANCELLED');
313
315
  const result = decodeTurnStart(await resource.process.rpc.request('turn/start', {
314
316
  threadId: session.threadId,
315
317
  input: [
@@ -7,6 +7,7 @@ import { readFile } from 'node:fs/promises';
7
7
  import { ReadinessEvidence } from './readiness-evidence.js';
8
8
  export const xerjServerName = 'gestalt-xerj';
9
9
  export const xerjTools = ['xerj_search', 'xerj_map', 'xerj_code_search'];
10
+ const connectionTimeoutMs = 5_000;
10
11
  /** Ephemeral native thread configuration; no installation or daemon ownership. */
11
12
  export class CodexXerj {
12
13
  capability;
@@ -89,6 +90,10 @@ export class CodexXerj {
89
90
  const guidance = await beforeDeadline(readFile(skill.path, 'utf8'), input.deadline);
90
91
  if (guidance.length > 16_384)
91
92
  return state;
93
+ // Backend preparation must not leave the native MCP handshake with only
94
+ // a few milliseconds. These are separate, individually bounded phases.
95
+ state.deadline = Date.now() + connectionTimeoutMs;
96
+ state.verificationTimeoutMs = connectionTimeoutMs;
92
97
  state.skillsConfig = state.skillsConfig.map((entry) => ({
93
98
  ...entry,
94
99
  enabled: entry.path === skill.path ? true : entry.enabled,
@@ -106,7 +111,7 @@ export class CodexXerj {
106
111
  enabled: true,
107
112
  required: false,
108
113
  startup_readiness: 'connection',
109
- startup_timeout_ms: Math.max(1, input.deadline - Date.now()),
114
+ startup_timeout_ms: connectionTimeoutMs,
110
115
  enabled_tools: xerjTools,
111
116
  default_tools_approval_mode: 'approve',
112
117
  },
@@ -125,13 +130,17 @@ export class CodexXerj {
125
130
  async verify(rpc, threadId, state) {
126
131
  if (!state.ready)
127
132
  return false;
133
+ // thread/start can consume the handshake allowance before this method runs.
134
+ const deadline = state.verificationTimeoutMs
135
+ ? Date.now() + state.verificationTimeoutMs
136
+ : state.deadline;
128
137
  try {
129
- while (Date.now() < state.deadline) {
138
+ while (Date.now() < deadline) {
130
139
  const result = (await beforeDeadline(rpc.request('mcpServerStatus/list', {
131
140
  threadId,
132
141
  serverName: xerjServerName,
133
142
  detail: 'full',
134
- }), state.deadline));
143
+ }), deadline));
135
144
  const server = result.data?.find((entry) => entry.name === xerjServerName);
136
145
  if (server?.runtimeStatus === 'connected' &&
137
146
  !server.toolsError &&
@@ -143,7 +152,7 @@ export class CodexXerj {
143
152
  state.evidence?.connection('unavailable');
144
153
  return false;
145
154
  }
146
- await beforeDeadline(new Promise((resolve) => setTimeout(resolve, 25)), state.deadline);
155
+ await beforeDeadline(new Promise((resolve) => setTimeout(resolve, 25)), deadline);
147
156
  }
148
157
  state.evidence?.connection('unavailable');
149
158
  return false;
@@ -0,0 +1,41 @@
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 { createHash, randomUUID } from 'node:crypto';
7
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ /** Classify bounded native prose; never retain it or copy arbitrary native fields. */
10
+ export function xerjIndexDiagnostic(message) {
11
+ const text = typeof message === 'string' ? message.slice(0, 16_384) : '';
12
+ const code = text.includes('refusing ambiguous assignment')
13
+ ? 'ambiguous-assignment'
14
+ : /\b(timeout|timed out)\b/i.test(text)
15
+ ? 'timeout'
16
+ : /\b(unauthorized|forbidden|authentication)\b/i.test(text)
17
+ ? 'authentication'
18
+ : /\b(connection refused|connection reset|unreachable)\b/i.test(text)
19
+ ? 'connection'
20
+ : /\b(out of memory|no space left|disk full)\b/i.test(text)
21
+ ? 'capacity'
22
+ : 'unknown-warning';
23
+ return {
24
+ id: randomUUID(),
25
+ occurredAt: new Date().toISOString(),
26
+ code,
27
+ messageDigest: text ? createHash('sha256').update(text).digest('hex') : null,
28
+ };
29
+ }
30
+ /** One private atomic record per root; repeated warnings cannot grow a log. */
31
+ export async function saveXerjIndexDiagnostic(directory, diagnostic) {
32
+ await mkdir(directory, { recursive: true, mode: 0o700 });
33
+ const temporary = join(directory, `.gestalt-index-diagnostic.${randomUUID()}.tmp`);
34
+ try {
35
+ await writeFile(temporary, `${JSON.stringify(diagnostic)}\n`, { flag: 'wx', mode: 0o600 });
36
+ await rename(temporary, join(directory, '.gestalt-index-diagnostic.json'));
37
+ }
38
+ finally {
39
+ await rm(temporary, { force: true });
40
+ }
41
+ }
@@ -11,6 +11,7 @@ import { homedir } from 'node:os';
11
11
  import { checkXerjIndexConfig, saveXerjIndexConfig, xerjContentArguments, xerjIndexConfig, } from './xerj-index-config.js';
12
12
  import { xerjDeadline } from './managed-xerj.js';
13
13
  import { ReadinessEvidence } from './readiness-evidence.js';
14
+ import { saveXerjIndexDiagnostic, xerjIndexDiagnostic } from './xerj-index-diagnostic.js';
14
15
  // Native gitignore syntax, editable by the host operator. Hidden directories and
15
16
  // symlinks are already skipped by XERJ. Never replace an existing root policy.
16
17
  export const xerjDefaultIgnores = `# Gestalt source discovery. Edit these native XERJ rules to change scope.
@@ -65,6 +66,9 @@ export class XerjIndexer {
65
66
  closed = false;
66
67
  saveConfiguration;
67
68
  configurationSaved;
69
+ diagnosticDirectory;
70
+ pendingDiagnostic;
71
+ diagnosticSaved;
68
72
  constructor(root, mode, capability, environment = process.env, report = console.warn) {
69
73
  this.capability = capability;
70
74
  this.environment = environment;
@@ -119,6 +123,7 @@ export class XerjIndexer {
119
123
  }
120
124
  const directory = join(this.environment.CODEX_HOME ?? join(homedir(), '.codex-gestalt'), 'xerj-data', 'autoindex', namespace);
121
125
  const config = xerjIndexConfig(root, namespace, ready.endpoint);
126
+ this.diagnosticDirectory = directory;
122
127
  const compatibility = await checkXerjIndexConfig(directory, config);
123
128
  if (this.closed)
124
129
  return;
@@ -239,22 +244,47 @@ export class XerjIndexer {
239
244
  });
240
245
  }
241
246
  else if (event.event === 'warning') {
242
- if (typeof event.message === 'string' &&
243
- event.message.includes('refusing ambiguous assignment')) {
244
- this.fail('XERJ incremental dataset assignment failed; the index is stale. See the XERJ recovery guide for this upstream limitation.');
247
+ const diagnostic = xerjIndexDiagnostic(event.message);
248
+ this.value = { ...this.value, diagnostic };
249
+ this.pendingDiagnostic = diagnostic;
250
+ this.diagnosticSaved ??= this.saveDiagnostics();
251
+ const reference = ` Diagnostic: ${diagnostic.id} (${diagnostic.code}).`;
252
+ if (diagnostic.code === 'ambiguous-assignment') {
253
+ this.fail('XERJ incremental dataset assignment failed; the index is stale. See the XERJ recovery guide for this upstream limitation.' +
254
+ reference);
245
255
  return;
246
256
  }
247
- this.fail('XERJ reported an indexing warning. Inspect the index with gestalt xerj autoindex status; source changes trigger another pass.');
257
+ this.fail('XERJ reported an indexing warning. Inspect the index with gestalt xerj autoindex status; source changes trigger another pass.' +
258
+ reference);
248
259
  }
249
260
  }
250
261
  catch {
251
262
  /* Native diagnostics are not public status or application logs. */
252
263
  }
253
264
  }
265
+ async saveDiagnostics() {
266
+ try {
267
+ // Coalesce bursts to the latest warning instead of queuing unbounded writes.
268
+ while (this.pendingDiagnostic && this.diagnosticDirectory) {
269
+ const diagnostic = this.pendingDiagnostic;
270
+ this.pendingDiagnostic = undefined;
271
+ try {
272
+ await saveXerjIndexDiagnostic(this.diagnosticDirectory, diagnostic);
273
+ }
274
+ catch {
275
+ this.report('XERJ could not save its redacted indexing diagnostic.');
276
+ }
277
+ }
278
+ }
279
+ finally {
280
+ this.diagnosticSaved = undefined;
281
+ }
282
+ }
254
283
  async close() {
255
284
  this.closed = true;
256
285
  await this.task;
257
286
  await this.configurationSaved;
287
+ await this.diagnosticSaved;
258
288
  const child = this.child;
259
289
  if (child && child.exitCode === null && child.signalCode === null) {
260
290
  await new Promise((resolve) => {
@@ -3,6 +3,13 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ export const providerRetryDelayMs = 60_000;
7
+ export const providerRetryLimit = 2;
8
+ export const providerContinuationPrompt = 'Continue.';
9
+ /** Capacity errors can clear quickly; account, context and policy limits require intervention. */
10
+ export function isTransientProviderFailure(failure) {
11
+ return failure.code === 'serverOverloaded' || failure.code === 'rateLimitExceeded';
12
+ }
6
13
  const descriptions = {
7
14
  contextWindowExceeded: 'The conversation exceeds the model context window. Compact it or start a new session.',
8
15
  sessionBudgetExceeded: 'The Codex session budget is exhausted. Review its budget before continuing.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.62.0",
3
+ "version": "0.62.2",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",