gestalt-mobile 0.53.0 → 0.54.1

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,8 +16,8 @@ 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-CcNWv_qG.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-Dxg3mu2e.css">
19
+ <script type="module" crossorigin src="/assets/index-BoOCaxSo.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-BRDqtTQi.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -808,6 +808,76 @@ describe('production composition', () => {
808
808
  expect(JSON.stringify(await app.inject('/api/sessions'))).not.toContain('Inspect the active supervised Org Plan');
809
809
  await app.close();
810
810
  });
811
+ it('production correlates overload recovery with a settled root turn and cancels it on Off', async () => {
812
+ const timers = [];
813
+ const fixture = await createProductionAutopilotFixture({
814
+ autopilotSchedule: (callback, delay) => {
815
+ const timer = { callback, delay, cancelled: false };
816
+ timers.push(timer);
817
+ return () => {
818
+ timer.cancelled = true;
819
+ };
820
+ },
821
+ });
822
+ onTestFinished(() => fixture.app.close());
823
+ timers.find((timer) => !timer.cancelled).callback();
824
+ await vi.waitFor(() => expect(fixture.handles.some((handle) => handle.calls.includes('turn/start'))).toBe(true));
825
+ const session = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
826
+ const handle = fixture.handles.find((candidate) => candidate.calls.includes('turn/start'));
827
+ const error = { codexErrorInfo: 'serverOverloaded', message: 'private overload body' };
828
+ handle.notify({
829
+ method: 'error',
830
+ params: {
831
+ threadId: session.threadId,
832
+ turnId: session.activeTurnId,
833
+ error,
834
+ willRetry: false,
835
+ },
836
+ });
837
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot
838
+ .providerRetry).toMatchObject({ turnId: session.activeTurnId, attempt: 1, pending: true, settled: false });
839
+ handle.notify({
840
+ method: 'turn/completed',
841
+ params: {
842
+ threadId: session.threadId,
843
+ turn: { id: session.activeTurnId, status: 'failed', error },
844
+ },
845
+ });
846
+ const completed = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
847
+ expect(completed.activeTurnId).toBeNull();
848
+ expect(completed.autopilot.providerRetry).toMatchObject({
849
+ attempt: 1,
850
+ pending: true,
851
+ settled: true,
852
+ });
853
+ const retry = timers.find((timer) => timer.delay === 30_000 && !timer.cancelled);
854
+ expect(retry).toBeDefined();
855
+ await fixture.app.inject({
856
+ method: 'PUT',
857
+ url: `/api/sessions/${fixture.sessionId}/autopilot`,
858
+ payload: { enabled: false },
859
+ });
860
+ expect(retry.cancelled).toBe(true);
861
+ retry.callback();
862
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot).toMatchObject({ enabled: false, state: 'disabled' });
863
+ const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
864
+ try {
865
+ const rows = database
866
+ .prepare("SELECT payload_json FROM session_events WHERE session_id=? AND type='autopilot.provider-failed'")
867
+ .all(fixture.sessionId);
868
+ expect(rows).toHaveLength(1);
869
+ expect(JSON.parse(rows[0].payload_json)).toMatchObject({
870
+ actor: 'root',
871
+ turnId: session.activeTurnId,
872
+ requestedEnabled: true,
873
+ providerFailure: { code: 'serverOverloaded' },
874
+ });
875
+ expect(JSON.stringify(rows)).not.toContain('private overload body');
876
+ }
877
+ finally {
878
+ database.close();
879
+ }
880
+ });
811
881
  it.each([
812
882
  'usageLimitExceeded',
813
883
  'contextWindowExceeded',
@@ -907,8 +977,12 @@ describe('production composition', () => {
907
977
  expect(result.activeTurnId).toBeNull();
908
978
  expect(result.autopilot).toMatchObject({
909
979
  enabled: false,
910
- state: 'safetyPaused',
911
- reason: code === 'usageLimitExceeded' ? 'usageLimitExceeded' : 'providerError',
980
+ state: code === 'unauthorized' ? 'disabled' : 'safetyPaused',
981
+ reason: code === 'unauthorized'
982
+ ? 'manualDisabled'
983
+ : code === 'usageLimitExceeded'
984
+ ? 'usageLimitExceeded'
985
+ : 'providerError',
912
986
  providerFailure: failure,
913
987
  health: { nextExpectedAction: expect.stringContaining(code) },
914
988
  });
@@ -794,7 +794,14 @@ export async function composeRelayApp(options) {
794
794
  // Unknown threads must not stop an unrelated session on the shared server.
795
795
  const providerFailure = decodeCodexFailure(notification);
796
796
  if (resolvedOrigin.kind !== 'unknown' && providerFailure)
797
- autopilot.providerFailed(sessionId, providerFailure);
797
+ autopilot.providerFailed(sessionId, providerFailure, {
798
+ actor: resolvedOrigin.kind === 'root' ? 'root' : 'child',
799
+ turnId: completionTurnId ??
800
+ (typeof notification.params?.turnId === 'string'
801
+ ? notification.params.turnId
802
+ : undefined),
803
+ settled: notification.method === 'turn/completed',
804
+ });
798
805
  const rootCommandId = resolvedOrigin.kind === 'root' ? completedCommandId(notification) : null;
799
806
  if (rootCommandId)
800
807
  autopilot.rootProcessCompleted(sessionId, rootCommandId);
@@ -6,7 +6,7 @@
6
6
  import { currentExecutableL1Index, } from '../../plans/domain/supervised-plan.js';
7
7
  import { parseOrgPlanAgentIdentity } from '../../../../shared/org-plan-position.js';
8
8
  export const AUTOPILOT_PROMPT_VERSION = 'v13';
9
- export const AUTOPILOT_CONTINUATION_PROMPT = 'Inspect the active supervised Org Plan. Refer to every L1 as L<a> and each nested L2 as L<a>.<b>, using one-based positions. Spawn exactly one executor per L1 and pass the exact literal task_name l<a>: l1 for L1, l2 for L2, and so on. Never create an L2-specific task name or append a title, role, nickname, plan name, or generated label. A validated DONE L2 and an accepted L1 are mandatory answer boundaries. The corresponding gestalt_org_plan_checkpoint call must be the last tool call of that root turn: immediately emit exactly one boundary final and end the turn, without followup_task, review, executor launch, or later milestone work. An accepted L1 always ends the root turn with a chat answer: never continue into the next L1 or emit post-acceptance documentation as commentary. Roll up commentary, files, verification, and commands since the previous boundary into that one answer; all later milestone activity belongs to a new root turn. On this later Autopilot turn, resume the same executor after an L2 boundary or launch exactly one fresh canonical executor for the next L1 after an accepted-L1 boundary. Treat a status question as an interruption: answer briefly, then perform the applicable continuation in the same turn. Before sending any blocker response or yielding because progress cannot continue safely, call gestalt_org_plan_attention for the matching decision-table blocker; never rely on blocker prose as the signal. When explicit human permission is required for a physical executor replacement, include executorReplacement with the exact canonicalTaskName; Mobile alone computes and persists the physical generation. Do not call attention for routine progress or a recoverable failure. Before yielding for known long work, call gestalt_autopilot_wait_lease version 2 with relevant observable wake conditions and a bounded maxWaitMs; it is one episode, so reassess before registering another in a later turn. Yield only when its response contains accepted:true; accepted:false means no continuation was registered and requires same-turn supervision. For GitHub PR CI, start an owned gh pr checks --watch process and lease processExited plus processResultAvailable while it runs. When the Autopilot probe is active, register the compatible wait lease, declare genuine attention, or immediately do actionable work; never acknowledge waiting in prose. Do not send a status-only response.';
9
+ export const AUTOPILOT_CONTINUATION_PROMPT = 'Inspect the active supervised Org Plan. Refer to every L1 as L<a> and each nested L2 as L<a>.<b>, using one-based positions. Spawn exactly one executor per L1 and pass the exact literal task_name l<a>: l1 for L1, l2 for L2, and so on. Never create an L2-specific task name or append a title, role, nickname, plan name, or generated label. A validated DONE L2 and an accepted L1 are mandatory answer boundaries. The corresponding gestalt_org_plan_checkpoint call must be the last tool call of that root turn: immediately emit exactly one boundary final and end the turn, without followup_task, review, executor launch, or later milestone work. An accepted L1 always ends the root turn with a chat answer: never continue into the next L1 or emit post-acceptance documentation as commentary. Roll up commentary, files, verification, and commands since the previous boundary into that one answer; all later milestone activity belongs to a new root turn. On this later Autopilot turn, resume the same executor after an L2 boundary or launch exactly one fresh canonical executor for the next L1 after an accepted-L1 boundary. Treat a status question as an interruption: answer briefly, then perform the applicable continuation in the same turn. Before sending any blocker response or yielding because progress cannot continue safely, call gestalt_org_plan_attention for the matching decision-table blocker; never rely on blocker prose as the signal. When explicit human permission is required for a physical executor replacement, include executorReplacement with the exact canonicalTaskName; Mobile alone computes and persists the physical generation. Do not call attention for routine progress or a recoverable failure. Before yielding for known long work, call gestalt_autopilot_wait_lease version 2 with relevant observable wake conditions and a bounded maxWaitMs; it is one episode, so reassess before registering another in a later turn. Yield only when its response contains accepted:true; accepted:false means no continuation was registered and requires same-turn supervision. For GitHub PR CI, start an owned gh pr checks --watch process and lease processExited plus processResultAvailable while it runs. Timestamp watcher state-change and terminal observations in UTC; distinguish observation time from upstream updated_at and process exit time. When the Autopilot probe is active, register the compatible wait lease, declare genuine attention, or immediately do actionable work; never acknowledge waiting in prose. Do not send a status-only response.';
10
10
  export const AUTOPILOT_EXECUTOR_CONTINUATION_PROMPT = 'Continue the same assigned Org L1 from its durable state. A prior turn ending did not complete the objective. Consume any supplied process result and take the next legal L2 action. Whenever an L2 reaches DONE, return its concise structured evidence and end the executor turn so the root can publish that mandatory answer boundary. Also report at the L1 review boundary or through structured attention.';
11
11
  /** Builds a physical launch instruction while keeping durable L1 identity canonical. */
12
12
  export function autopilotExecutorLaunchPrompt(identity) {
@@ -16,6 +16,7 @@ import { classifyAgentActivity, decideAutopilot, executionComplete, } from './po
16
16
  import { consumeCheckpointBoundary, consumeObsoleteWait, consumeObservableWake, consumeWaitDeadline, recordAutomaticContinuation, recoverSafetyPause, registerProactiveWait as registerProtocolWait, reportProbe, semanticProgressKey, startSupervisionProtocol, } from '../domain/supervision-protocol.js';
17
17
  export class AutopilotCoordinator {
18
18
  deps;
19
+ providerTimers = new Map();
19
20
  timers = new Map();
20
21
  completionTimers = new Map();
21
22
  executorTimers = new Map();
@@ -79,6 +80,16 @@ export class AutopilotCoordinator {
79
80
  throw error;
80
81
  return; // snapshot exposes controllerUnavailable; only explicit Off repairs it.
81
82
  }
83
+ if (state?.providerRetry?.pending) {
84
+ // A restart loses the live reconciliation context. Retain the used budget
85
+ // and require explicit recovery instead of manufacturing fresh authority.
86
+ this.persist({
87
+ ...state,
88
+ providerRetry: { ...state.providerRetry, pending: false },
89
+ nextEvaluationAt: null,
90
+ updatedAt: this.deps.now(),
91
+ });
92
+ }
82
93
  const session = this.deps.session(sessionId);
83
94
  if (!state ||
84
95
  !session ||
@@ -293,7 +304,20 @@ export class AutopilotCoordinator {
293
304
  return false;
294
305
  this.cancelWaitTimer(sessionId);
295
306
  this.parkedSubscriptions.delete(sessionId);
296
- this.persist({ ...state, supervision: nextProtocol, updatedAt: this.deps.now() });
307
+ const now = this.deps.now();
308
+ this.persist({ ...state, supervision: nextProtocol, updatedAt: now }, undefined, [
309
+ {
310
+ sessionId,
311
+ type: 'autopilot.wait-woken',
312
+ occurredAt: now,
313
+ payload: {
314
+ leaseId: wake.leaseId,
315
+ reportId: state.supervision.lastReportId,
316
+ wakeCondition: wake.condition,
317
+ resumeAt: state.supervision.waitLease?.resumeAt ?? null,
318
+ },
319
+ },
320
+ ]);
297
321
  this.evaluate(sessionId);
298
322
  return true;
299
323
  }
@@ -310,8 +334,33 @@ export class AutopilotCoordinator {
310
334
  }
311
335
  /** Bridges a completed root-owned background command into its one active wait episode. */
312
336
  rootProcessCompleted(sessionId, processId) {
313
- const lease = this.deps.store.find(sessionId)?.supervision?.waitLease;
314
- if (!lease || !processId || processId.length > 256)
337
+ if (!processId || processId.length > 256)
338
+ return false;
339
+ const state = this.deps.store.find(sessionId);
340
+ if (!state)
341
+ return false;
342
+ const lease = state.supervision?.waitLease;
343
+ const observedAt = this.deps.now();
344
+ // Record receipt even when an earlier deadline already consumed the lease.
345
+ // This is relay observation time, not an inferred process exit timestamp.
346
+ this.commit({
347
+ events: [
348
+ {
349
+ sessionId,
350
+ type: 'autopilot.root-process-observed',
351
+ occurredAt: observedAt,
352
+ payload: {
353
+ processId,
354
+ observedAt,
355
+ leaseId: lease?.id ?? null,
356
+ reportId: state.supervision?.lastReportId ?? null,
357
+ status: 'completed',
358
+ },
359
+ },
360
+ ],
361
+ });
362
+ this.flushOutbox(sessionId);
363
+ if (!lease)
315
364
  return false;
316
365
  const condition = lease.wakeConditions.includes('processResultAvailable')
317
366
  ? 'processResultAvailable'
@@ -332,10 +381,11 @@ export class AutopilotCoordinator {
332
381
  const currentPlan = this.deps.plan(sessionId);
333
382
  if (!currentPlan)
334
383
  return { code: 'AUTOPILOT_PLAN_REQUIRED' };
335
- if (executionComplete(currentPlan.plan))
336
- return { code: 'AUTOPILOT_PLAN_COMPLETE' };
337
384
  const now = this.deps.now();
338
385
  const prior = this.deps.store.find(sessionId) ?? disabledAutopilot(sessionId, now);
386
+ if (executionComplete(currentPlan.plan) &&
387
+ !this.terminalReviewPending(prior, currentPlan.identity))
388
+ return { code: 'AUTOPILOT_PLAN_COMPLETE' };
339
389
  const nextFingerprint = fingerprint(currentPlan.plan);
340
390
  const replacing = Boolean(prior.planIdentity && prior.planIdentity !== currentPlan.identity);
341
391
  if (replacing) {
@@ -357,6 +407,8 @@ export class AutopilotCoordinator {
357
407
  nextEvaluationAt: null,
358
408
  stopReason: null,
359
409
  providerFailure: undefined,
410
+ providerFailureTurnId: undefined,
411
+ providerRetry: undefined,
360
412
  executor: !replacing && prior.state === 'attentionRequired' ? prior.executor : undefined,
361
413
  blocking: undefined,
362
414
  supervision: recoverSafetyPause(consumeObsoleteWait(replacing || prior.supervision?.outcome === 'attentionRequired'
@@ -440,6 +492,7 @@ export class AutopilotCoordinator {
440
492
  prior.state === 'disabled' &&
441
493
  !cancelled &&
442
494
  !prior.supervision?.waitLease &&
495
+ !prior.providerFailure &&
443
496
  (!currentPlan || prior.planIdentity === currentPlan.identity))
444
497
  return this.snapshot(sessionId);
445
498
  const next = {
@@ -451,6 +504,9 @@ export class AutopilotCoordinator {
451
504
  nextEvaluationAt: null,
452
505
  ...(cancelled ? { lastControlId: null } : {}),
453
506
  stopReason: 'manualDisabled',
507
+ providerFailure: undefined,
508
+ providerFailureTurnId: undefined,
509
+ providerRetry: undefined,
454
510
  blocking: undefined,
455
511
  supervision: consumeObsoleteWait(prior.supervision ?? startSupervisionProtocol(this.progressKey(sessionId)), this.progressKey(sessionId)),
456
512
  updatedAt: now,
@@ -496,7 +552,10 @@ export class AutopilotCoordinator {
496
552
  case 'observe':
497
553
  break;
498
554
  case 'reconcile':
499
- next = { ...prior, state: 'monitoring', nextEvaluationAt: null, updatedAt: now };
555
+ // Refreshing evidence does not start a new backoff episode. Retain the
556
+ // durable deadline so frequent reconciling/fresh observations cannot
557
+ // continually postpone the same scheduled control.
558
+ next = { ...prior, state: 'monitoring', updatedAt: now };
500
559
  if (!this.reconciling.has(sessionId)) {
501
560
  this.reconciling.add(sessionId);
502
561
  this.enqueue(sessionId, async () => {
@@ -564,6 +623,8 @@ export class AutopilotCoordinator {
564
623
  type: 'autopilot.continuation-scheduled',
565
624
  payload: {
566
625
  controlId: scheduledControlId,
626
+ reportId: prior.supervision?.lastReportId ?? null,
627
+ nextEvaluationAt: decision.at,
567
628
  ...(prior.checkpoints?.activeHandoffId
568
629
  ? { traceId: prior.checkpoints.activeHandoffId }
569
630
  : {}),
@@ -641,35 +702,161 @@ export class AutopilotCoordinator {
641
702
  }
642
703
  return this.snapshot(sessionId);
643
704
  }
644
- /** Terminal provider failures are retained even when automatic supervision is off. */
645
- providerFailed(sessionId, failure) {
705
+ /** Retain structured failures without turning manual Off into an automatic pause. */
706
+ providerFailed(sessionId, failure, origin) {
646
707
  const now = this.deps.now();
647
708
  const state = this.deps.store.find(sessionId) ?? disabledAutopilot(sessionId, now);
648
- if (state.state === 'safetyPaused' &&
709
+ const retry = state.providerRetry;
710
+ if (retry &&
711
+ !retry.pending &&
712
+ retry.turnId === origin?.turnId &&
713
+ failure.code === 'serverOverloaded')
714
+ return false;
715
+ if (retry && retry.turnId === origin?.turnId && state.providerFailure?.code === failure.code) {
716
+ if (origin?.settled && !retry.settled)
717
+ this.persist({ ...state, providerRetry: { ...retry, settled: true }, updatedAt: now });
718
+ return false;
719
+ }
720
+ if (!state.requestedEnabled &&
721
+ !retry?.pending &&
722
+ state.providerFailureTurnId === origin?.turnId &&
649
723
  state.providerFailure?.code === failure.code &&
650
724
  state.providerFailure.httpStatusCode === failure.httpStatusCode)
651
725
  return false;
726
+ const enabled = state.requestedEnabled || Boolean(retry?.pending);
727
+ const attempt = (retry?.attempt ?? 0) + 1;
728
+ const recoverable = enabled &&
729
+ failure.code === 'serverOverloaded' &&
730
+ origin?.actor === 'root' &&
731
+ Boolean(origin.turnId) &&
732
+ origin.turnId === this.deps.session(sessionId)?.activeTurnId &&
733
+ attempt <= 2;
734
+ const event = {
735
+ sessionId,
736
+ type: 'autopilot.provider-failed',
737
+ occurredAt: now,
738
+ payload: {
739
+ providerFailure: failure,
740
+ requestedEnabled: enabled,
741
+ actor: origin?.actor ?? 'unknown',
742
+ turnId: origin?.turnId ?? null,
743
+ retryAttempt: recoverable ? attempt : null,
744
+ },
745
+ };
746
+ if (!enabled) {
747
+ this.persist({
748
+ ...state,
749
+ providerFailure: failure,
750
+ providerFailureTurnId: origin?.turnId,
751
+ updatedAt: now,
752
+ }, undefined, [event]);
753
+ return true;
754
+ }
652
755
  const cancelled = this.cancelScheduledControl(state, now);
653
756
  this.cancelTimer(sessionId);
654
757
  this.cancelWaitTimer(sessionId);
655
- this.persist({
656
- // Timer cancellation also persists cancelled executor commands.
758
+ const next = {
657
759
  ...(this.deps.store.find(sessionId) ?? state),
658
760
  state: 'safetyPaused',
659
761
  requestedEnabled: false,
660
762
  generation: state.generation + 1,
661
- nextEvaluationAt: null,
763
+ nextEvaluationAt: recoverable
764
+ ? new Date(Date.parse(now) + 30_000 * attempt).toISOString()
765
+ : null,
662
766
  ...(cancelled ? { lastControlId: null } : {}),
663
767
  stopReason: failure.code === 'usageLimitExceeded' ? 'usageLimitExceeded' : 'providerError',
664
768
  providerFailure: failure,
769
+ providerFailureTurnId: origin?.turnId,
770
+ providerRetry: recoverable
771
+ ? {
772
+ turnId: origin.turnId,
773
+ attempt,
774
+ notBefore: new Date(Date.parse(now) + 30_000 * attempt).toISOString(),
775
+ settled: origin.settled,
776
+ pending: true,
777
+ resumeRoot: false,
778
+ }
779
+ : retry
780
+ ? { ...retry, pending: false, resumeRoot: false }
781
+ : undefined,
665
782
  supervision: undefined,
666
783
  updatedAt: now,
667
- }, cancelled);
784
+ };
785
+ this.persist(next, cancelled, [event]);
786
+ if (recoverable)
787
+ this.providerTimers.set(sessionId, this.deps.schedule(() => {
788
+ this.providerTimers.delete(sessionId);
789
+ this.enqueue(sessionId, () => this.retryProvider(sessionId, next.generation));
790
+ }, 30_000 * attempt));
668
791
  return true;
669
792
  }
793
+ async retryProvider(sessionId, generation) {
794
+ const initial = this.deps.store.find(sessionId);
795
+ if (!initial?.providerRetry?.pending || initial.generation !== generation)
796
+ return;
797
+ let compatible = false;
798
+ try {
799
+ compatible = (await this.deps.reconcile(sessionId)).compatible;
800
+ }
801
+ catch {
802
+ /* fail closed */
803
+ }
804
+ const current = this.deps.store.find(sessionId), session = this.deps.session(sessionId), activity = this.deps.activity(sessionId), retained = this.deps.plan(sessionId);
805
+ if (!current?.providerRetry?.pending || current.generation !== generation)
806
+ return;
807
+ const safe = Date.parse(this.deps.now()) >= Date.parse(current.providerRetry.notBefore) &&
808
+ compatible &&
809
+ current.providerRetry.settled &&
810
+ session?.state === 'ready' &&
811
+ !session.activeTurnId &&
812
+ activity?.confidence === 'fresh' &&
813
+ activity.root.state === 'idle' &&
814
+ Date.parse(this.deps.now()) - Date.parse(activity.root.observedAt) <=
815
+ this.deps.policy.staleAfterMs &&
816
+ activity.subagents.every((agent) => agent.state === 'idle' &&
817
+ !agent.ownedProcesses?.some((process) => ['running', 'detached-active'].includes(process.state))) &&
818
+ !this.deps.pendingInteraction(sessionId) &&
819
+ retained?.identity === current.planIdentity &&
820
+ fingerprint(retained.plan) === current.planFingerprint &&
821
+ (!executionComplete(retained.plan) || this.terminalReviewPending(current, retained.identity));
822
+ const now = this.deps.now();
823
+ this.persist({
824
+ ...current,
825
+ providerRetry: { ...current.providerRetry, pending: false, resumeRoot: safe },
826
+ nextEvaluationAt: null,
827
+ ...(safe
828
+ ? {
829
+ state: 'monitoring',
830
+ requestedEnabled: true,
831
+ stopReason: null,
832
+ providerFailure: undefined,
833
+ providerFailureTurnId: undefined,
834
+ supervision: startSupervisionProtocol(this.progressKey(sessionId)),
835
+ }
836
+ : {}),
837
+ updatedAt: now,
838
+ }, undefined, [
839
+ {
840
+ sessionId,
841
+ type: safe ? 'autopilot.provider-retry-ready' : 'autopilot.provider-retry-abandoned',
842
+ occurredAt: now,
843
+ payload: {
844
+ turnId: current.providerRetry.turnId,
845
+ retryAttempt: current.providerRetry.attempt,
846
+ reason: safe ? 'settledRoot' : 'unsafeOrUnconfirmed',
847
+ },
848
+ },
849
+ ]);
850
+ if (safe)
851
+ this.evaluate(sessionId);
852
+ }
670
853
  /** Returns whether an incomplete supervised plan may be treated as terminal by the relay. */
671
854
  turnCompleted(sessionId, turnId) {
672
- const state = this.deps.store.find(sessionId);
855
+ let state = this.deps.store.find(sessionId);
856
+ if (state?.providerRetry?.resumeRoot && turnId && turnId !== state.providerRetry.turnId) {
857
+ state = { ...state, providerRetry: { ...state.providerRetry, resumeRoot: false } };
858
+ this.persist(state);
859
+ }
673
860
  if (turnId && state?.checkpoints?.pendingTurnId && state.checkpoints.pendingTurnId !== turnId)
674
861
  return false;
675
862
  const plan = this.deps.plan(sessionId)?.plan;
@@ -993,10 +1180,11 @@ export class AutopilotCoordinator {
993
1180
  const currentPlan = this.deps.plan(sessionId);
994
1181
  if (!currentPlan)
995
1182
  return { code: 'AUTOPILOT_PLAN_REQUIRED' };
996
- if (executionComplete(currentPlan.plan))
997
- return { code: 'AUTOPILOT_PLAN_COMPLETE' };
998
1183
  const now = this.deps.now();
999
1184
  const prior = this.deps.store.find(sessionId) ?? disabledAutopilot(sessionId, now);
1185
+ if (executionComplete(currentPlan.plan) &&
1186
+ !this.terminalReviewPending(prior, currentPlan.identity))
1187
+ return { code: 'AUTOPILOT_PLAN_COMPLETE' };
1000
1188
  if (prior.planIdentity === currentPlan.identity &&
1001
1189
  !prior.requestedEnabled &&
1002
1190
  prior.stopReason === 'manualDisabled')
@@ -1138,6 +1326,14 @@ export class AutopilotCoordinator {
1138
1326
  this.cancelWaitTimer(sessionId);
1139
1327
  this.parkedSubscriptions.delete(sessionId);
1140
1328
  const prior = this.deps.store.find(sessionId);
1329
+ if (prior?.providerRetry?.pending)
1330
+ this.persist({
1331
+ ...prior,
1332
+ providerRetry: { ...prior.providerRetry, pending: false },
1333
+ nextEvaluationAt: null,
1334
+ generation: prior.generation + 1,
1335
+ updatedAt: this.deps.now(),
1336
+ });
1141
1337
  if (!prior || !prior.requestedEnabled)
1142
1338
  return;
1143
1339
  const now = this.deps.now();
@@ -1196,11 +1392,54 @@ export class AutopilotCoordinator {
1196
1392
  return true;
1197
1393
  }
1198
1394
  persist(next, control, events = []) {
1395
+ const prior = this.deps.store.find(next.sessionId);
1396
+ const previousLease = prior?.supervision?.waitLease;
1397
+ const nextLease = next.supervision?.waitLease;
1398
+ const diagnostics = [];
1399
+ if (nextLease && nextLease.id !== previousLease?.id)
1400
+ diagnostics.push({
1401
+ sessionId: next.sessionId,
1402
+ type: 'autopilot.wait-registered',
1403
+ occurredAt: next.updatedAt,
1404
+ payload: {
1405
+ leaseId: nextLease.id,
1406
+ reportId: next.supervision?.lastReportId,
1407
+ resumeAt: nextLease.resumeAt ?? null,
1408
+ wakeConditions: nextLease.wakeConditions,
1409
+ },
1410
+ });
1411
+ if (previousLease &&
1412
+ previousLease.id !== nextLease?.id &&
1413
+ !events.some((event) => event.type === 'autopilot.wait-expired' || event.type === 'autopilot.wait-woken'))
1414
+ diagnostics.push({
1415
+ sessionId: next.sessionId,
1416
+ type: 'autopilot.wait-ended',
1417
+ occurredAt: next.updatedAt,
1418
+ payload: {
1419
+ leaseId: previousLease.id,
1420
+ reportId: prior?.supervision?.lastReportId,
1421
+ resumeAt: previousLease.resumeAt ?? null,
1422
+ reason: next.stopReason ?? 'superseded',
1423
+ state: next.state,
1424
+ },
1425
+ });
1426
+ if (control?.status === 'cancelled' &&
1427
+ this.deps.store.findControl(next.sessionId, control.controlId)?.status !== 'cancelled')
1428
+ diagnostics.push({
1429
+ sessionId: next.sessionId,
1430
+ type: 'autopilot.control-cancelled',
1431
+ occurredAt: next.updatedAt,
1432
+ payload: {
1433
+ controlId: control.controlId,
1434
+ reportId: prior?.supervision?.lastReportId ?? null,
1435
+ reason: next.stopReason ?? 'superseded',
1436
+ },
1437
+ });
1199
1438
  const snapshotEvents = this.snapshotEvents(next, control);
1200
1439
  this.commit({
1201
1440
  state: next,
1202
1441
  ...(control ? { control } : {}),
1203
- events: [...snapshotEvents, ...events],
1442
+ events: [...snapshotEvents, ...diagnostics, ...events],
1204
1443
  });
1205
1444
  this.storeRecoveryAttempts.delete(next.sessionId);
1206
1445
  if (snapshotEvents.length)
@@ -1239,9 +1478,19 @@ export class AutopilotCoordinator {
1239
1478
  return;
1240
1479
  }
1241
1480
  const session = this.deps.session(sessionId);
1481
+ const decision = this.decision(sessionId, current);
1482
+ if (!session?.activeTurnId &&
1483
+ !this.deps.pendingInteraction(sessionId) &&
1484
+ decision.kind === 'reconcile') {
1485
+ // The deadline can coincide with a roster refresh. Reconcile before
1486
+ // dispatch, preserving this control and its elapsed backoff. A fresh
1487
+ // result re-arms it; unavailable evidence uses the bounded watchdog.
1488
+ this.evaluate(sessionId);
1489
+ return;
1490
+ }
1242
1491
  if (session?.activeTurnId ||
1243
1492
  this.deps.pendingInteraction(sessionId) ||
1244
- this.decision(sessionId, current).kind !== 'scheduleContinuation') {
1493
+ decision.kind !== 'scheduleContinuation') {
1245
1494
  const now = this.deps.now();
1246
1495
  const cancelled = this.cancelScheduledControl(current, now);
1247
1496
  this.persist({
@@ -1352,6 +1601,8 @@ export class AutopilotCoordinator {
1352
1601
  }
1353
1602
  }
1354
1603
  cancelTimer(sessionId) {
1604
+ this.providerTimers.get(sessionId)?.();
1605
+ this.providerTimers.delete(sessionId);
1355
1606
  this.timers.get(sessionId)?.();
1356
1607
  this.timers.delete(sessionId);
1357
1608
  this.completionTimers.get(sessionId)?.();
@@ -1404,7 +1655,15 @@ export class AutopilotCoordinator {
1404
1655
  return;
1405
1656
  }
1406
1657
  this.parkedSubscriptions.delete(sessionId);
1407
- this.persist({ ...state, supervision: protocol, updatedAt: this.deps.now() });
1658
+ const observedAt = this.deps.now();
1659
+ this.persist({ ...state, supervision: protocol, updatedAt: observedAt }, undefined, [
1660
+ {
1661
+ sessionId,
1662
+ type: 'autopilot.wait-expired',
1663
+ occurredAt: observedAt,
1664
+ payload: { leaseId, reportId: state.supervision.lastReportId, resumeAt, observedAt },
1665
+ },
1666
+ ]);
1408
1667
  this.evaluate(sessionId);
1409
1668
  }, Math.max(0, Date.parse(resumeAt) - Date.parse(this.deps.now()))));
1410
1669
  }
@@ -1525,7 +1784,19 @@ export class AutopilotCoordinator {
1525
1784
  }
1526
1785
  }
1527
1786
  }
1787
+ terminalReviewPending(state, planIdentity) {
1788
+ return Boolean(state.planIdentity === planIdentity &&
1789
+ state.checkpoints?.planIdentity === planIdentity &&
1790
+ state.checkpoints.protocolVersion === 1 &&
1791
+ !state.checkpoints.terminalReviewAccepted);
1792
+ }
1528
1793
  requiresRootBoundary(state, plan) {
1794
+ if (state.providerRetry?.resumeRoot)
1795
+ return true;
1796
+ // Completed milestone reports do not complete terminal review or its fixes.
1797
+ // Keep their continuation at root; a settled last executor cannot own it.
1798
+ if (executionComplete(plan) && this.terminalReviewPending(state, state.planIdentity ?? ''))
1799
+ return true;
1529
1800
  if (state.checkpoints?.rootContinuationFromTurnId)
1530
1801
  return true;
1531
1802
  const reportedL2 = new Set(state.checkpoints?.reportedL2Ids ?? []);
@@ -71,8 +71,7 @@ export function autopilotSnapshot(state, retryLimit, facts = {
71
71
  : healthy && rootWorking
72
72
  ? 'rootWorking'
73
73
  : 'degraded';
74
- const nextExpectedAction = state.providerFailure &&
75
- ['providerError', 'usageLimitExceeded'].includes(state.stopReason ?? '')
74
+ const nextExpectedAction = state.providerFailure
76
75
  ? describeProviderFailure(state.providerFailure)
77
76
  : state.stopReason === 'usageLimitExceeded'
78
77
  ? 'Codex usage limit reached. Restore available usage or wait for the limit to reset, then resume Autopilot.'
@@ -142,10 +141,8 @@ export function autopilotSnapshot(state, retryLimit, facts = {
142
141
  ...(state.nextEvaluationAt ? { nextEvaluationAt: state.nextEvaluationAt } : {}),
143
142
  ...(state.executor ? { executor: state.executor } : {}),
144
143
  ...(state.blocking ? { blocking: state.blocking } : {}),
145
- ...(state.providerFailure &&
146
- ['providerError', 'usageLimitExceeded'].includes(state.stopReason ?? '')
147
- ? { providerFailure: state.providerFailure }
148
- : {}),
144
+ ...(state.providerFailure ? { providerFailure: state.providerFailure } : {}),
145
+ ...(state.providerRetry ? { providerRetry: state.providerRetry } : {}),
149
146
  updatedAt: state.updatedAt,
150
147
  };
151
148
  }
@@ -9,6 +9,13 @@ const relevant = /^(?:org-plan\.|autopilot\.|agent\.activity\.|session\.status\.
9
9
  const statusTypes = ['autopilot.updated', 'agent.activity.updated', 'session.status.updated'];
10
10
  // Export structural telemetry only. Event types alone do not imply payload safety.
11
11
  const diagnosticFields = new Set([
12
+ 'leaseId',
13
+ 'reportId',
14
+ 'resumeAt',
15
+ 'wakeCondition',
16
+ 'wakeConditions',
17
+ 'nextEvaluationAt',
18
+ 'processId',
12
19
  'traceId',
13
20
  'handoffId',
14
21
  'controlId',
@@ -24,6 +31,8 @@ const diagnosticFields = new Set([
24
31
  'code',
25
32
  'rpcCode',
26
33
  'providerFailure',
34
+ 'actor',
35
+ 'retryAttempt',
27
36
  'httpStatusCode',
28
37
  'enabled',
29
38
  'requestedEnabled',
@@ -84,7 +93,7 @@ function objectPayload(value) {
84
93
  }
85
94
  }
86
95
  function correlation(payload) {
87
- for (const key of ['traceId', 'handoffId', 'controlId', 'turnId', 'requestId'])
96
+ for (const key of ['traceId', 'handoffId', 'controlId', 'leaseId', 'turnId', 'requestId'])
88
97
  if (typeof payload[key] === 'string' && payload[key])
89
98
  return String(payload[key]);
90
99
  return null;