gestalt-mobile 0.50.0 → 0.50.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.
@@ -16,7 +16,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later
16
16
  <link rel="icon" href="/icons/gestalt-mobile-192.png" />
17
17
  <link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
18
18
  <title>Gestalt Mobile</title>
19
- <script type="module" crossorigin src="/assets/index-IkBR-U3-.js"></script>
19
+ <script type="module" crossorigin src="/assets/index-BePEZpgl.js"></script>
20
20
  <link rel="stylesheet" crossorigin href="/assets/index-DEzZEQhF.css">
21
21
  </head>
22
22
  <body>
@@ -807,6 +807,127 @@ describe('production composition', () => {
807
807
  expect(JSON.stringify(await app.inject('/api/sessions'))).not.toContain('Inspect the active supervised Org Plan');
808
808
  await app.close();
809
809
  });
810
+ it.each([
811
+ 'usageLimitExceeded',
812
+ 'contextWindowExceeded',
813
+ 'unauthorized',
814
+ 'responseStreamDisconnected',
815
+ 'futureProviderError',
816
+ ].flatMap((code) => ['error', 'turn/completed', 'child-error'].map((method) => ({ code, method }))))('production pauses durably on Codex $code via $method', async ({ method, code }) => {
817
+ const timers = [];
818
+ let coordinator;
819
+ const fixture = await createProductionAutopilotFixture({
820
+ autopilotSchedule: (callback) => {
821
+ const timer = { callback, cancelled: false };
822
+ timers.push(timer);
823
+ return () => {
824
+ timer.cancelled = true;
825
+ };
826
+ },
827
+ onAutopilotCoordinator: (value) => {
828
+ coordinator = value;
829
+ },
830
+ });
831
+ onTestFinished(() => fixture.app.close());
832
+ timers.find((timer) => !timer.cancelled).callback();
833
+ await vi.waitFor(() => expect(fixture.handles.some((handle) => handle.calls.includes('turn/start'))).toBe(true));
834
+ const session = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
835
+ const handle = fixture.handles.find((candidate) => candidate.calls.includes('turn/start'));
836
+ const failure = {
837
+ code,
838
+ ...(code === 'responseStreamDisconnected' ? { httpStatusCode: 503 } : {}),
839
+ };
840
+ const error = {
841
+ codexErrorInfo: code === 'responseStreamDisconnected' ? { [code]: { httpStatusCode: 503 } } : code,
842
+ message: 'private provider detail',
843
+ };
844
+ handle.notify({
845
+ method: 'error',
846
+ params: {
847
+ threadId: session.threadId,
848
+ turnId: session.activeTurnId,
849
+ error,
850
+ willRetry: true,
851
+ },
852
+ });
853
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot.enabled).toBe(true);
854
+ handle.notify({
855
+ method: 'error',
856
+ params: {
857
+ threadId: 'unrelated-thread',
858
+ turnId: 'unrelated-turn',
859
+ error,
860
+ willRetry: false,
861
+ },
862
+ });
863
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot.enabled).toBe(true);
864
+ if (method === 'child-error') {
865
+ handle.notify({
866
+ method: 'item/started',
867
+ params: {
868
+ threadId: session.threadId,
869
+ item: {
870
+ id: 'spawn',
871
+ type: 'collabAgentToolCall',
872
+ tool: 'spawnAgent',
873
+ receiverThreadIds: ['child'],
874
+ senderThreadId: session.threadId,
875
+ },
876
+ },
877
+ });
878
+ }
879
+ const params = method !== 'turn/completed'
880
+ ? {
881
+ threadId: method === 'child-error' ? 'child' : session.threadId,
882
+ turnId: method === 'child-error' ? 'child-turn' : session.activeTurnId,
883
+ error,
884
+ willRetry: false,
885
+ }
886
+ : {
887
+ threadId: session.threadId,
888
+ turn: { id: session.activeTurnId, status: 'failed', error },
889
+ };
890
+ // Provider diagnostics remain available even when automatic supervision was disabled.
891
+ if (code === 'unauthorized')
892
+ coordinator.disable(fixture.sessionId);
893
+ handle.notify({ method: method === 'child-error' ? 'error' : method, params });
894
+ handle.notify({ method: method === 'child-error' ? 'error' : method, params });
895
+ handle.notify({
896
+ method: 'turn/completed',
897
+ params: {
898
+ threadId: session.threadId,
899
+ turn: { id: session.activeTurnId, status: 'failed', error },
900
+ },
901
+ });
902
+ coordinator.evaluate(fixture.sessionId);
903
+ coordinator.dispose(fixture.sessionId);
904
+ coordinator.restore(fixture.sessionId);
905
+ const result = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
906
+ expect(result.activeTurnId).toBeNull();
907
+ expect(result.autopilot).toMatchObject({
908
+ enabled: false,
909
+ state: 'safetyPaused',
910
+ reason: code === 'usageLimitExceeded' ? 'usageLimitExceeded' : 'providerError',
911
+ providerFailure: failure,
912
+ health: { nextExpectedAction: expect.stringContaining(code) },
913
+ });
914
+ expect(fixture.handles
915
+ .flatMap((candidate) => candidate.calls)
916
+ .filter((call) => call === 'turn/start')).toHaveLength(1);
917
+ const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
918
+ try {
919
+ const rows = database
920
+ .prepare("SELECT payload_json FROM session_events WHERE session_id = ? AND type = 'autopilot.updated'")
921
+ .all(fixture.sessionId);
922
+ expect(JSON.stringify(rows)).not.toContain('private provider detail');
923
+ expect(rows.filter((row) => JSON.parse(row.payload_json).providerFailure?.code === code)).toHaveLength(1);
924
+ }
925
+ finally {
926
+ database.close();
927
+ }
928
+ coordinator.enable(fixture.sessionId);
929
+ expect(coordinator.snapshot(fixture.sessionId).providerFailure).toBeUndefined();
930
+ });
810
931
  it('production same-DB restart rearms future backoff and claims overdue once', async () => {
811
932
  const timers = [];
812
933
  let coordinator;
@@ -2664,6 +2785,7 @@ describe('production composition', () => {
2664
2785
  },
2665
2786
  autopilot: { enabled: true },
2666
2787
  });
2788
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot.reason).toBeUndefined();
2667
2789
  expect(timers.some((timer) => !timer.cancelled && !timer.fired)).toBe(true);
2668
2790
  });
2669
2791
  for (let attempt = 0; attempt < 8 && starts().length === 0; attempt += 1) {
@@ -2681,7 +2803,11 @@ describe('production composition', () => {
2681
2803
  await Promise.resolve();
2682
2804
  expect(starts()).toHaveLength(1);
2683
2805
  });
2684
- it.each([false, true])('continues past a disconnected auxiliary helper after L2 completion, reported=%s', async (reported) => {
2806
+ it.each([
2807
+ { reported: false, completed: false },
2808
+ { reported: true, completed: false },
2809
+ { reported: true, completed: true },
2810
+ ])('continues past a disconnected auxiliary helper after L2 completion, %j', async ({ reported, completed }) => {
2685
2811
  const handles = [];
2686
2812
  const launch = liveAppServer(handles);
2687
2813
  const timers = [];
@@ -2733,9 +2859,11 @@ describe('production composition', () => {
2733
2859
  payload: { enabled: false },
2734
2860
  });
2735
2861
  await writeFile(join(fixture.workspacePath, 'autopilot.org'), acceptedL1WithNextTodoPlanText()
2736
- .replace('* TODO [#B] Next parent', '* WIP [#B] Next parent')
2862
+ .replace('* TODO [#B] Next parent', `* ${completed ? 'DONE' : 'WIP'} [#B] Next parent`)
2737
2863
  .replace('** TODO [#B] Next child', '** DONE [#B] Next child') +
2738
- `
2864
+ (completed
2865
+ ? ''
2866
+ : `
2739
2867
  ** TODO [#B] Next child two
2740
2868
  :PROPERTIES:
2741
2869
  :ID: next-child-two
@@ -2744,7 +2872,7 @@ describe('production composition', () => {
2744
2872
  - Change :: Resume the canonical executor.
2745
2873
  - Tests :: Verify one fenced continuation.
2746
2874
  - Done when :: The next L2 starts.
2747
- `);
2875
+ `));
2748
2876
  await expect
2749
2877
  .poll(async () => (await fixture.app.inject(`/api/sessions/${fixture.sessionId}/plan`)).json()
2750
2878
  .currentStepId)
@@ -2812,7 +2940,7 @@ describe('production composition', () => {
2812
2940
  const rootThreadId = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()
2813
2941
  .threadId;
2814
2942
  expect(starts()[0].params).toMatchObject({
2815
- threadId: reported ? 'executor' : rootThreadId,
2943
+ threadId: reported && !completed ? 'executor' : rootThreadId,
2816
2944
  });
2817
2945
  // Replayed timers cannot duplicate the root report or the later
2818
2946
  // continuation of the same canonical executor.
@@ -2824,7 +2952,7 @@ describe('production composition', () => {
2824
2952
  try {
2825
2953
  expect(database
2826
2954
  .prepare('SELECT count(*) AS count FROM session_events WHERE session_id = ? AND type = ?')
2827
- .get(fixture.sessionId, reported ? 'autopilot.executor-resumed' : 'autopilot.control-issued')).toMatchObject({ count: 1 });
2955
+ .get(fixture.sessionId, reported && !completed ? 'autopilot.executor-resumed' : 'autopilot.control-issued')).toMatchObject({ count: 1 });
2828
2956
  }
2829
2957
  finally {
2830
2958
  database.close();
@@ -24,6 +24,7 @@ import { ProviderModelCatalog } from './platform/catalog/provider-model-catalog.
24
24
  import { createRecentThreadLister } from './platform/codex/recent-thread-lister.js';
25
25
  import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
26
26
  import { normalizeCodexNotification } from './platform/codex/normalizer.js';
27
+ import { decodeCodexFailure } from './platform/codex/codex-failure.js';
27
28
  import { KimiSessionRuntime } from './platform/kimi/kimi-session-runtime.js';
28
29
  import { KimiWebServerManager } from './platform/kimi/kimi-web-server-manager.js';
29
30
  import { KimiModelCatalog } from './platform/kimi/kimi-model-catalog.js';
@@ -787,6 +788,11 @@ export async function composeRelayApp(options) {
787
788
  ? { ...origin, kind: 'root' }
788
789
  : origin;
789
790
  const normalized = normalizeCodexNotification(sessionId, 0, occurredAt, notification, currentSession?.workspacePath, currentSession?.activeTurnId, resolvedOrigin);
791
+ // Pause before activity/completion can schedule another automatic turn.
792
+ // Unknown threads must not stop an unrelated session on the shared server.
793
+ const providerFailure = decodeCodexFailure(notification);
794
+ if (resolvedOrigin.kind !== 'unknown' && providerFailure)
795
+ autopilot.providerFailed(sessionId, providerFailure);
790
796
  const rootCommandId = resolvedOrigin.kind === 'root' ? completedCommandId(notification) : null;
791
797
  if (rootCommandId)
792
798
  autopilot.rootProcessCompleted(sessionId, rootCommandId);
@@ -809,7 +815,8 @@ export async function composeRelayApp(options) {
809
815
  if (session && turnId && session.activeTurnId === turnId) {
810
816
  completedSession = RelaySession.rehydrate(session).completeTurn(turnId, occurredAt).snapshot;
811
817
  sessions.save(completedSession);
812
- autopilot.turnCompleted(sessionId, turnId);
818
+ if (!providerFailure)
819
+ autopilot.turnCompleted(sessionId, turnId);
813
820
  }
814
821
  planMeasurementRefresh?.refreshNow(sessionId);
815
822
  }
@@ -356,6 +356,7 @@ export class AutopilotCoordinator {
356
356
  consecutiveNoProgress: 0,
357
357
  nextEvaluationAt: null,
358
358
  stopReason: null,
359
+ providerFailure: undefined,
359
360
  executor: !replacing && prior.state === 'attentionRequired' ? prior.executor : undefined,
360
361
  blocking: undefined,
361
362
  supervision: recoverSafetyPause(consumeObsoleteWait(replacing || prior.supervision?.outcome === 'attentionRequired'
@@ -640,6 +641,32 @@ export class AutopilotCoordinator {
640
641
  }
641
642
  return this.snapshot(sessionId);
642
643
  }
644
+ /** Terminal provider failures are retained even when automatic supervision is off. */
645
+ providerFailed(sessionId, failure) {
646
+ const now = this.deps.now();
647
+ const state = this.deps.store.find(sessionId) ?? disabledAutopilot(sessionId, now);
648
+ if (state.state === 'safetyPaused' &&
649
+ state.providerFailure?.code === failure.code &&
650
+ state.providerFailure.httpStatusCode === failure.httpStatusCode)
651
+ return false;
652
+ const cancelled = this.cancelScheduledControl(state, now);
653
+ this.cancelTimer(sessionId);
654
+ this.cancelWaitTimer(sessionId);
655
+ this.persist({
656
+ // Timer cancellation also persists cancelled executor commands.
657
+ ...(this.deps.store.find(sessionId) ?? state),
658
+ state: 'safetyPaused',
659
+ requestedEnabled: false,
660
+ generation: state.generation + 1,
661
+ nextEvaluationAt: null,
662
+ ...(cancelled ? { lastControlId: null } : {}),
663
+ stopReason: failure.code === 'usageLimitExceeded' ? 'usageLimitExceeded' : 'providerError',
664
+ providerFailure: failure,
665
+ supervision: undefined,
666
+ updatedAt: now,
667
+ }, cancelled);
668
+ return true;
669
+ }
643
670
  /** Returns whether an incomplete supervised plan may be treated as terminal by the relay. */
644
671
  turnCompleted(sessionId, turnId) {
645
672
  const state = this.deps.store.find(sessionId);
@@ -1508,10 +1535,14 @@ export class AutopilotCoordinator {
1508
1535
  const epoch = epochs.get(target);
1509
1536
  return Boolean(epoch?.reopened || epoch?.completed === false);
1510
1537
  };
1511
- return plan.steps.some((l1) => (l1.state !== 'SUSPENDED' &&
1512
- l1.children.some((l2) => l2.state === 'DONE' &&
1513
- (!reportedL2.has(JSON.stringify([l1.id, l2.id])) ||
1514
- epochNeedsReport(checkpointTarget('l2', l1.id, l2.id))))) ||
1538
+ return plan.steps.some((l1) =>
1539
+ // A finished executor cannot review its own milestone. Even after all
1540
+ // L2 reports, the root must run the review before work can advance.
1541
+ (l1.state === 'DONE' && l1.reviewStatus !== 'REVIEWED') ||
1542
+ (l1.state !== 'SUSPENDED' &&
1543
+ l1.children.some((l2) => l2.state === 'DONE' &&
1544
+ (!reportedL2.has(JSON.stringify([l1.id, l2.id])) ||
1545
+ epochNeedsReport(checkpointTarget('l2', l1.id, l2.id))))) ||
1515
1546
  (l1.state === 'DONE' &&
1516
1547
  l1.reviewStatus === 'REVIEWED' &&
1517
1548
  (!reportedL1.has(l1.id) || epochNeedsReport(checkpointTarget('l1', l1.id)))));
@@ -2438,9 +2469,11 @@ export class AutopilotCoordinator {
2438
2469
  });
2439
2470
  }
2440
2471
  semanticSnapshot(next, control) {
2472
+ const snapshot = this.snapshotFor(next, control);
2441
2473
  return JSON.stringify({
2442
- ...this.snapshotFor(next, control),
2474
+ ...snapshot,
2443
2475
  updatedAt: '',
2476
+ health: { ...snapshot.health, observedAt: '', lastTransitionAt: '' },
2444
2477
  });
2445
2478
  }
2446
2479
  snapshotEvents(next, control) {
@@ -2611,6 +2644,8 @@ export class AutopilotCoordinator {
2611
2644
  if (activity?.confidence === 'fresh' &&
2612
2645
  Date.parse(this.deps.now()) - Date.parse(activity.root.observedAt) <=
2613
2646
  this.deps.policy.staleAfterMs) {
2647
+ if (current.stopReason === 'reconcileFailed')
2648
+ this.persist({ ...current, stopReason: null, updatedAt: this.deps.now() });
2614
2649
  this.evaluate(sessionId);
2615
2650
  }
2616
2651
  else {
@@ -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 { describeProviderFailure, } from '../../../../shared/contracts/provider-failure.js';
6
7
  import { checkpointHandoffRecoveryMessage } from '../../../../shared/contracts/autopilot-recovery.js';
7
8
  import { observableWakeConditions, } from './supervision-protocol.js';
8
9
  export function disabledAutopilot(sessionId, now) {
@@ -70,27 +71,32 @@ export function autopilotSnapshot(state, retryLimit, facts = {
70
71
  : healthy && rootWorking
71
72
  ? 'rootWorking'
72
73
  : 'degraded';
73
- const nextExpectedAction = phase === 'checkpointRecovery'
74
- ? checkpointHandoffRecoveryMessage
75
- : phase === 'rootWorking'
76
- ? 'Wait for the root turn to settle.'
77
- : phase === 'continuationScheduled'
78
- ? 'Run the scheduled continuation.'
79
- : phase === 'waitingForAgentEvent'
80
- ? parkedWait
81
- ? 'Wait for a subscribed agent or process event.'
82
- : 'Wait for the active executor or owned process to settle.'
83
- : phase === 'checkingState'
84
- ? 'Reconcile supervised execution state.'
85
- : phase === 'needsYou'
86
- ? 'Respond to the pending attention request.'
87
- : phase === 'complete'
88
- ? 'No further plan action is required.'
89
- : phase === 'off'
90
- ? 'Enable Autopilot to supervise an incomplete plan.'
91
- : phase === 'safetyPaused'
92
- ? 'Resume manually after reviewing the safety pause.'
93
- : 'Restore a valid continuation before relying on Autopilot.';
74
+ const nextExpectedAction = state.providerFailure &&
75
+ ['providerError', 'usageLimitExceeded'].includes(state.stopReason ?? '')
76
+ ? describeProviderFailure(state.providerFailure)
77
+ : state.stopReason === 'usageLimitExceeded'
78
+ ? 'Codex usage limit reached. Restore available usage or wait for the limit to reset, then resume Autopilot.'
79
+ : phase === 'checkpointRecovery'
80
+ ? checkpointHandoffRecoveryMessage
81
+ : phase === 'rootWorking'
82
+ ? 'Wait for the root turn to settle.'
83
+ : phase === 'continuationScheduled'
84
+ ? 'Run the scheduled continuation.'
85
+ : phase === 'waitingForAgentEvent'
86
+ ? parkedWait
87
+ ? 'Wait for a subscribed agent or process event.'
88
+ : 'Wait for the active executor or owned process to settle.'
89
+ : phase === 'checkingState'
90
+ ? 'Reconcile supervised execution state.'
91
+ : phase === 'needsYou'
92
+ ? 'Respond to the pending attention request.'
93
+ : phase === 'complete'
94
+ ? 'No further plan action is required.'
95
+ : phase === 'off'
96
+ ? 'Enable Autopilot to supervise an incomplete plan.'
97
+ : phase === 'safetyPaused'
98
+ ? 'Resume manually after reviewing the safety pause.'
99
+ : 'Restore a valid continuation before relying on Autopilot.';
94
100
  return {
95
101
  state: state.state,
96
102
  enabled: state.requestedEnabled,
@@ -136,6 +142,10 @@ export function autopilotSnapshot(state, retryLimit, facts = {
136
142
  ...(state.nextEvaluationAt ? { nextEvaluationAt: state.nextEvaluationAt } : {}),
137
143
  ...(state.executor ? { executor: state.executor } : {}),
138
144
  ...(state.blocking ? { blocking: state.blocking } : {}),
145
+ ...(state.providerFailure &&
146
+ ['providerError', 'usageLimitExceeded'].includes(state.stopReason ?? '')
147
+ ? { providerFailure: state.providerFailure }
148
+ : {}),
139
149
  updatedAt: state.updatedAt,
140
150
  };
141
151
  }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { DatabaseSync } from 'node:sqlite';
7
7
  const relevant = /^(?:org-plan\.|autopilot\.|agent\.activity\.|session\.status\.)/;
8
+ const statusTypes = ['autopilot.updated', 'agent.activity.updated', 'session.status.updated'];
8
9
  // Export structural telemetry only. Event types alone do not imply payload safety.
9
10
  const diagnosticFields = new Set([
10
11
  'traceId',
@@ -21,6 +22,8 @@ const diagnosticFields = new Set([
21
22
  'reason',
22
23
  'code',
23
24
  'rpcCode',
25
+ 'providerFailure',
26
+ 'httpStatusCode',
24
27
  'enabled',
25
28
  'requestedEnabled',
26
29
  'desiredState',
@@ -112,9 +115,20 @@ function diagnose(events) {
112
115
  export function exportControlPlaneTrace(databasePath, sessionId, generatedAt = new Date().toISOString()) {
113
116
  const database = new DatabaseSync(databasePath, { readOnly: true });
114
117
  try {
118
+ database.exec('BEGIN');
119
+ // Reserve the diagnostic budget for causal transitions. Polling status
120
+ // snapshots must not evict the failed handoff from an otherwise retained
121
+ // journal. Keep a recent status tail and disclose every omitted row.
122
+ const statusEventLimit = 100;
123
+ const transitionEventLimit = 4900;
124
+ const relevantWhere = "(type LIKE 'org-plan.%' OR type LIKE 'autopilot.%' OR type LIKE 'agent.activity.%' OR type LIKE 'session.status.%')";
125
+ const statusWhere = `type IN (${statusTypes.map(() => '?').join(',')})`;
126
+ const counts = database
127
+ .prepare(`SELECT SUM(CASE WHEN ${statusWhere} THEN 1 ELSE 0 END) AS statuses, COUNT(*) AS total FROM session_events WHERE session_id = ? AND ${relevantWhere}`)
128
+ .get(...statusTypes, sessionId);
115
129
  const rows = database
116
- .prepare("SELECT sequence,occurred_at,type,payload_json FROM session_events WHERE session_id = ? AND (type LIKE 'org-plan.%' OR type LIKE 'autopilot.%' OR type LIKE 'agent.activity.%' OR type LIKE 'session.status.%') ORDER BY sequence DESC LIMIT 5000")
117
- .all(sessionId);
130
+ .prepare(`SELECT * FROM (SELECT sequence,occurred_at,type,payload_json FROM session_events WHERE session_id = ? AND ${statusWhere} ORDER BY sequence DESC LIMIT ?) UNION ALL SELECT * FROM (SELECT sequence,occurred_at,type,payload_json FROM session_events WHERE session_id = ? AND ${relevantWhere} AND NOT (${statusWhere}) ORDER BY sequence DESC LIMIT ?) ORDER BY sequence DESC`)
131
+ .all(sessionId, ...statusTypes, statusEventLimit, sessionId, ...statusTypes, transitionEventLimit);
118
132
  const events = rows
119
133
  .reverse()
120
134
  .filter((row) => relevant.test(row.type))
@@ -128,7 +142,19 @@ export function exportControlPlaneTrace(databasePath, sessionId, generatedAt = n
128
142
  traceId: correlation(payload),
129
143
  };
130
144
  });
131
- return { schemaVersion: 1, sessionId, generatedAt, events, diagnoses: diagnose(events) };
145
+ return {
146
+ schemaVersion: 1,
147
+ sessionId,
148
+ generatedAt,
149
+ events,
150
+ diagnoses: diagnose(events),
151
+ selection: {
152
+ statusEventLimit,
153
+ transitionEventLimit,
154
+ omittedStatusEvents: Math.max(0, (counts.statuses ?? 0) - statusEventLimit),
155
+ omittedTransitionEvents: Math.max(0, counts.total - (counts.statuses ?? 0) - transitionEventLimit),
156
+ },
157
+ };
132
158
  }
133
159
  finally {
134
160
  database.close();
@@ -138,6 +164,7 @@ export function formatControlPlaneTrace(trace) {
138
164
  const lines = [
139
165
  `Control-plane trace for ${trace.sessionId}`,
140
166
  `Generated: ${trace.generatedAt}`,
167
+ `Omitted by export limits: ${trace.selection.omittedStatusEvents} status snapshots, ${trace.selection.omittedTransitionEvents} transitions.`,
141
168
  '',
142
169
  ];
143
170
  for (const event of trace.events) {
@@ -0,0 +1,35 @@
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 { parseProviderFailure, } from '../../../shared/contracts/provider-failure.js';
7
+ const record = (value) => value && typeof value === 'object' && !Array.isArray(value)
8
+ ? value
9
+ : undefined;
10
+ /** Recognize terminal provider evidence, never conversation text or rounded quota percentages. */
11
+ export function decodeCodexFailure(notification) {
12
+ const params = record(notification.params);
13
+ const turn = record(params?.turn);
14
+ const error = notification.method === 'error' && params?.willRetry === false
15
+ ? record(params.error)
16
+ : notification.method === 'turn/completed' && turn?.status === 'failed'
17
+ ? record(turn.error)
18
+ : undefined;
19
+ if (!error)
20
+ return undefined;
21
+ const info = error.codexErrorInfo;
22
+ if (typeof info === 'string')
23
+ return parseProviderFailure({ code: info }) ?? { code: 'other' };
24
+ const variant = record(info);
25
+ if (!variant || Object.keys(variant).length !== 1)
26
+ return { code: 'other' };
27
+ const code = Object.keys(variant)[0];
28
+ const status = record(variant[code])?.httpStatusCode;
29
+ return (parseProviderFailure({
30
+ code,
31
+ ...(typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599
32
+ ? { httpStatusCode: status }
33
+ : {}),
34
+ }) ?? { code: 'other' });
35
+ }
@@ -6,6 +6,7 @@
6
6
  import { disabledAutopilot, } from '../../features/autopilot/domain/autopilot-session.js';
7
7
  import { AutopilotStateError } from '../../features/autopilot/domain/persisted-state-error.js';
8
8
  import { parsePersistedSupervisedLifecycle } from '../../features/autopilot/domain/supervised-lifecycle.js';
9
+ import { parseProviderFailure } from '../../../shared/contracts/provider-failure.js';
9
10
  import { MAX_AUTOPILOT_RECORD_BYTES, parsePlanFingerprint, } from '../../features/autopilot/domain/plan-fingerprint.js';
10
11
  export class SqliteAutopilotStore {
11
12
  db;
@@ -40,6 +41,8 @@ export class SqliteAutopilotStore {
40
41
  'attentionRequired',
41
42
  'noPlanProgress',
42
43
  'reconcileFailed',
44
+ 'usageLimitExceeded',
45
+ 'providerError',
43
46
  'startUnavailable',
44
47
  'actionRateExceeded',
45
48
  'planRemoved',
@@ -76,12 +79,14 @@ export class SqliteAutopilotStore {
76
79
  state.blocking,
77
80
  state.supervision,
78
81
  state.checkpoints,
82
+ state.providerFailure,
79
83
  ].some((value) => value !== undefined)
80
84
  ? JSON.stringify({
81
85
  executor: state.executor,
82
86
  blocking: state.blocking,
83
87
  supervision: state.supervision,
84
88
  checkpoints: state.checkpoints,
89
+ providerFailure: state.providerFailure,
85
90
  })
86
91
  : null;
87
92
  // Use the reader's exact contract before any write (including transaction/outbox writes).
@@ -242,7 +247,14 @@ function parseLifecycle(value) {
242
247
  if (typeof value !== 'string' || Buffer.byteLength(value, 'utf8') > MAX_AUTOPILOT_RECORD_BYTES)
243
248
  return null;
244
249
  try {
245
- return parsePersistedSupervisedLifecycle(JSON.parse(value)) ?? null;
250
+ const parsed = JSON.parse(value);
251
+ const lifecycle = parsePersistedSupervisedLifecycle(parsed);
252
+ if (!lifecycle)
253
+ return null;
254
+ const providerFailure = parseProviderFailure(parsed.providerFailure);
255
+ if (parsed.providerFailure !== undefined && !providerFailure)
256
+ return null;
257
+ return { ...lifecycle, ...(providerFailure ? { providerFailure } : {}) };
246
258
  }
247
259
  catch {
248
260
  return null;
@@ -27,6 +27,10 @@ const renderableAutopilotAuditWhere = `
27
27
  AND (
28
28
  type <> 'autopilot.updated'
29
29
  OR json_extract(payload_json, '$.state') = 'completed'
30
+ OR (
31
+ json_extract(payload_json, '$.state') = 'safetyPaused'
32
+ AND json_extract(payload_json, '$.reason') IN ('usageLimitExceeded', 'providerError')
33
+ )
30
34
  OR (
31
35
  json_extract(payload_json, '$.state') = 'attentionRequired'
32
36
  AND json_extract(payload_json, '$.reason') IN ('noPlanProgress', 'reconcileFailed', 'actionRateExceeded')
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { parseOrgPlanAttention } from './org-plan-attention.js';
7
+ import { describeProviderFailure, parseProviderFailure } from './provider-failure.js';
7
8
  /** Only the bounded attention contract belongs in historical dialogue metadata. */
8
9
  export function autopilotAuditAttention(payload) {
9
10
  const requestId = property(payload, 'requestId');
@@ -51,6 +52,11 @@ export function autopilotAuditLabel(type, payload) {
51
52
  return null;
52
53
  const state = property(payload, 'state');
53
54
  const reason = property(payload, 'reason');
55
+ const failure = parseProviderFailure(property(payload, 'providerFailure'));
56
+ if (state === 'safetyPaused' && failure)
57
+ return `Autopilot paused: ${describeProviderFailure(failure)}`;
58
+ if (state === 'safetyPaused' && reason === 'usageLimitExceeded')
59
+ return 'Autopilot paused: Codex usage limit reached';
54
60
  if (state === 'completed')
55
61
  return 'Completed the supervised plan';
56
62
  // Recovery health updates belong to the status and notification pipeline.
@@ -0,0 +1,50 @@
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
+ const descriptions = {
7
+ contextWindowExceeded: 'The conversation exceeds the model context window. Compact it or start a new session.',
8
+ sessionBudgetExceeded: 'The Codex session budget is exhausted. Review its budget before continuing.',
9
+ usageLimitExceeded: 'Codex usage limit reached. Restore available usage or wait for the limit to reset, then resume Autopilot.',
10
+ rateLimitExceeded: 'The request rate limit was reached. Wait before retrying.',
11
+ flexUnavailable: 'Flex processing is unavailable. Retry later or select another service tier.',
12
+ serverOverloaded: 'The model service is overloaded. Retry later.',
13
+ cyberPolicy: 'Codex blocked the request under its cybersecurity policy.',
14
+ misalignmentPolicyViolation: 'Codex blocked the request under its safety policy.',
15
+ tooManyDenials: 'Execution stopped after too many denied requests. Review the requested actions.',
16
+ httpConnectionFailed: 'The provider HTTP connection failed. Check connectivity and provider availability.',
17
+ responseStreamConnectionFailed: 'Codex could not connect to the response stream.',
18
+ responseStreamDisconnected: 'The provider response stream disconnected before completion.',
19
+ responseTooManyFailedAttempts: 'The provider response failed after repeated attempts.',
20
+ internalServerError: 'Codex encountered an internal server error. Retry later.',
21
+ unauthorized: 'Provider authorization failed. Check the account sign-in or credentials.',
22
+ badRequest: 'The provider rejected the request. Check the selected model and request settings.',
23
+ threadRollbackFailed: 'Codex could not roll back the thread.',
24
+ sandboxError: 'Codex could not execute an action in its sandbox. Review the execution policy.',
25
+ activeTurnNotSteerable: 'The active turn cannot accept steering. Wait for it to finish.',
26
+ other: 'Codex reported an unclassified execution failure.',
27
+ };
28
+ export function parseProviderFailure(value) {
29
+ if (!value || typeof value !== 'object' || Array.isArray(value))
30
+ return undefined;
31
+ const { code, httpStatusCode } = value;
32
+ if (typeof code !== 'string' || !/^[A-Za-z][A-Za-z0-9_]{0,79}$/.test(code))
33
+ return undefined;
34
+ if (httpStatusCode !== undefined &&
35
+ (typeof httpStatusCode !== 'number' ||
36
+ !Number.isInteger(httpStatusCode) ||
37
+ httpStatusCode < 100 ||
38
+ httpStatusCode > 599))
39
+ return undefined;
40
+ return {
41
+ code,
42
+ ...(httpStatusCode !== undefined ? { httpStatusCode: httpStatusCode } : {}),
43
+ };
44
+ }
45
+ export function describeProviderFailure(failure) {
46
+ const description = Object.hasOwn(descriptions, failure.code)
47
+ ? descriptions[failure.code]
48
+ : 'Codex reported an execution failure with no known description.';
49
+ return `${failure.code}${failure.httpStatusCode ? ` (HTTP ${failure.httpStatusCode})` : ''}: ${description}`;
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.50.0",
3
+ "version": "0.50.2",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",