gestalt-mobile 0.65.5 → 0.65.7

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.
@@ -71,8 +71,8 @@ import { decodeAgentActivityFacts, decodeToolEfficiencyFacts, } from './platform
71
71
  import { ToolEfficiencyProjection } from './features/agent-activity/tool-efficiency-projection.js';
72
72
  import { SqliteToolEfficiencyStore } from './platform/persistence/sqlite-tool-efficiency-store.js';
73
73
  import { completedCommandId, compactOrgPlanCheckpointKind, isAgentCapacityRecoveryCall, isAutopilotWaitLeaseCall, resolvedServerRequestId, toPendingInteraction, } from './platform/codex/server-request.js';
74
- import { parseOrgPlanCheckpoint, toOrgPlanCheckpointToolResponse, } from '../shared/contracts/org-plan-checkpoint.js';
75
- import { hasActiveL1Writer, resolveOrgPlanCheckpointSignal, validateOrgPlanCheckpoint, } from './features/org-plan-checkpoint/application/validate.js';
74
+ import { toOrgPlanCheckpointToolResponse } from '../shared/contracts/org-plan-checkpoint.js';
75
+ import { CheckpointCoordination } from './features/org-plan-checkpoint/application/coordinate.js';
76
76
  import { isValidInteractionResponse, isValidQuizInteractionResponse, } from './features/sessions/interaction/response-validator.js';
77
77
  import { promoteRecentThread } from './features/sessions/promote-recent-thread/use-case.js';
78
78
  import { FilesystemSkillProfileStore } from './platform/skills/filesystem-skill-profile-store.js';
@@ -102,7 +102,7 @@ import { AutopilotCoordinator } from './features/autopilot/application/service.j
102
102
  import { deriveSessionStatus } from './features/sessions/session-status.js';
103
103
  import { AUTOPILOT_CONTINUATION_PROMPT, AUTOPILOT_EXECUTOR_CONTINUATION_PROMPT, autopilotExecutorLaunchPrompt, defaultAutopilotPolicy, } from './features/autopilot/application/policy.js';
104
104
  import { createRelyingPartyConfig } from './config.js';
105
- import { parseOrgPlanAttention, parseOrgPlanAttentionToolResponse, toOrgPlanAttentionAcknowledgement, } from '../shared/contracts/org-plan-attention.js';
105
+ import { parseOrgPlanAttention, toOrgPlanAttentionAcknowledgement, } from '../shared/contracts/org-plan-attention.js';
106
106
  import { autopilotWaitLeaseToolResponse, } from '../shared/contracts/autopilot-wait-lease.js';
107
107
  import { agentCapacityRecoveryToolResponse } from '../shared/contracts/agent-capacity-recovery.js';
108
108
  import { isOrgPlanHealthCall, parseOrgPlanHealthArguments, } from '../shared/contracts/org-plan-health.js';
@@ -111,6 +111,8 @@ import { ExecutorModelEvidenceReader } from './features/plans/application/execut
111
111
  import { ExecutorLaunchValidationReader } from './features/plans/application/executor-launch-validation.js';
112
112
  import { requireModelPolicyAdmission } from './features/plans/domain/model-policy-admission.js';
113
113
  import { currentExecutableL1Index } from './features/plans/domain/supervised-plan.js';
114
+ import { AttentionResolution } from './features/org-plan-attention/application/resolve.js';
115
+ import { AttentionAcknowledgement } from './features/org-plan-attention/application/acknowledgement.js';
114
116
  import { pwaIconUrl } from './features/pwa/register-routes.js';
115
117
  const generatedProtocolVersion = 'codex-cli 0.144.3';
116
118
  const checkpointDiagnostic = debuglog('gestalt-mobile:checkpoint');
@@ -151,10 +153,6 @@ export async function composeRelayApp(options) {
151
153
  const idempotency = new SqliteIdempotencyStore(database);
152
154
  const autopilotStore = new SqliteAutopilotStore(database);
153
155
  const takeoverStore = new SqliteSupervisionTakeoverStore(database, autopilotStore);
154
- const attentionResolutionOperations = new Map();
155
- const checkpointHandoffTimers = new Map();
156
- const attentionAcknowledgementTimers = new Map();
157
- const checkpointHandoffRecoveries = new Set();
158
156
  const supervisedPlans = new SupervisedPlanRegistry();
159
157
  const supervisorOwnership = (sessionId) => {
160
158
  const identity = supervisedPlans.identity(sessionId) ?? autopilotStore.find(sessionId)?.planIdentity;
@@ -655,104 +653,75 @@ export async function composeRelayApp(options) {
655
653
  publishInteractionResolved(sessionId, interaction.requestId, occurredAt, outcome);
656
654
  }
657
655
  };
658
- const checkpointTimerKey = (sessionId, requestId) => `${sessionId}:${requestId}`;
659
- const cancelCheckpointHandoffTimer = (sessionId, requestId) => {
660
- const key = checkpointTimerKey(sessionId, requestId);
661
- const timer = checkpointHandoffTimers.get(key);
662
- if (!timer)
663
- return;
664
- clearTimeout(timer.handle);
665
- checkpointHandoffTimers.delete(key);
666
- };
667
- /** Fail a held checkpoint exactly once and retain its durable root boundary. */
668
- const failCheckpointHandoff = (sessionId, requestId, turnId) => {
669
- cancelCheckpointHandoffTimer(sessionId, requestId);
670
- const occurredAt = new Date().toISOString();
671
- if (!interactions.resolve(sessionId, requestId, occurredAt, 'failed'))
672
- return false;
673
- autopilot.checkpointHandoffFailed(sessionId, turnId);
674
- events.publish(journal.append(sessionId, 'org-plan.checkpoint-handoff-failed', {
675
- requestId,
676
- reason: 'checkpointHandoffFailed',
677
- ...(autopilotStore.find(sessionId)?.checkpoints?.activeHandoffId
678
- ? { traceId: autopilotStore.find(sessionId).checkpoints.activeHandoffId }
679
- : {}),
680
- }, occurredAt));
681
- publishAttentionSettlement(sessionId, requestId, occurredAt, 'failed');
682
- // Neither this timeout nor a failed transport may schedule continuation.
683
- // If a successful response is already blocked in the writable stream, drop
684
- // its local ownership so any late write cannot be mistaken for an ack.
685
- const rejected = runtime?.rejectServerRequest(sessionId, requestId, new Error('CHECKPOINT_HANDOFF_FAILED'));
686
- if (rejected === false) {
687
- const recoveryKey = checkpointTimerKey(sessionId, requestId);
688
- const ownedRuntime = runtime;
689
- const session = sessions.find(sessionId);
690
- if (ownedRuntime &&
691
- session?.activeTurnId === turnId &&
692
- !checkpointHandoffRecoveries.has(recoveryKey)) {
693
- checkpointHandoffRecoveries.add(recoveryKey);
694
- void (async () => {
695
- try {
696
- // Recycle only the session-local writer. Its close cancels the
697
- // blocked output, and only successful reconstruction releases the
698
- // durable checkpoint through the runtime-recovery boundary.
699
- if (runtime !== ownedRuntime || sessions.find(sessionId)?.activeTurnId !== turnId)
700
- return;
701
- const rebuilt = await ownedRuntime.recycle(session, new Date().toISOString());
702
- if (runtime !== ownedRuntime)
703
- return;
704
- const recovered = turnId && rebuilt.activeTurnId === turnId
705
- ? RelaySession.rehydrate(rebuilt).completeTurn(turnId, new Date().toISOString())
706
- .snapshot
707
- : rebuilt;
708
- saveSession(recovered);
709
- activity.observe({
710
- sessionId,
711
- occurredAt: new Date().toISOString(),
712
- kind: 'turnCompleted',
713
- });
714
- autopilot.recoverCheckpointHandoff(sessionId);
715
- }
716
- catch {
717
- // The durable failure remains visible; a later normal recovery can retry.
718
- }
719
- finally {
720
- checkpointHandoffRecoveries.delete(recoveryKey);
721
- }
722
- })();
723
- }
724
- }
725
- return true;
726
- };
727
- const armCheckpointHandoffDeadline = (sessionId, requestId, turnId) => {
728
- cancelCheckpointHandoffTimer(sessionId, requestId);
729
- const key = checkpointTimerKey(sessionId, requestId);
730
- const token = Symbol(key);
731
- const handle = setTimeout(() => {
732
- if (checkpointHandoffTimers.get(key)?.token !== token)
733
- return;
734
- checkpointHandoffTimers.delete(key);
735
- failCheckpointHandoff(sessionId, requestId, turnId);
736
- }, options.checkpointHandoffDeadlineMs ?? 5_000);
737
- handle.unref?.();
738
- checkpointHandoffTimers.set(key, { handle, token });
739
- };
740
- const cancelAttentionAcknowledgementTimer = (sessionId, requestId) => {
741
- const key = checkpointTimerKey(sessionId, requestId);
742
- const timer = attentionAcknowledgementTimers.get(key);
743
- if (!timer)
744
- return;
745
- clearTimeout(timer.handle);
746
- attentionAcknowledgementTimers.delete(key);
747
- };
748
- const armAttentionAcknowledgementDeadline = (sessionId, requestId) => {
749
- cancelAttentionAcknowledgementTimer(sessionId, requestId);
750
- const key = checkpointTimerKey(sessionId, requestId);
751
- const token = Symbol(key);
752
- const handle = setTimeout(() => {
753
- if (attentionAcknowledgementTimers.get(key)?.token !== token)
754
- return;
755
- attentionAcknowledgementTimers.delete(key);
656
+ const checkpoints = new CheckpointCoordination({
657
+ plans: {
658
+ refresh: async (id) => (await planStatusSource.refresh(id))?.kind === 'updated',
659
+ find: (id) => supervisedPlans.find(id),
660
+ identity: (id) => supervisedPlans.identity(id),
661
+ publicationReason: (id) => supervisedPlans.publicationReason(id),
662
+ completedTargets: (id) => autopilotStore
663
+ .find(id)
664
+ ?.checkpoints?.completionEpochs?.filter((epoch) => epoch.completed && !epoch.reopened)
665
+ .map((epoch) => epoch.target),
666
+ pendingTarget: (id) => autopilotStore.find(id)?.checkpoints?.pendingTarget,
667
+ },
668
+ activity: (id) => activity.snapshot(id, new Date().toISOString()),
669
+ pending: {
670
+ add: (id, interaction) => interactions.add(id, interaction),
671
+ find: (id, requestId) => interactions.find(id, requestId),
672
+ list: (id) => interactions.list(id),
673
+ resolve: (id, requestId, at, outcome) => interactions.resolve(id, requestId, at, outcome),
674
+ },
675
+ autopilot: {
676
+ accept: (id, checkpoint, turnId, at) => autopilot.checkpointAccepted(id, checkpoint, turnId, at),
677
+ failed: (id, turnId) => autopilot.checkpointHandoffFailed(id, turnId),
678
+ recover: (id) => autopilot.recoverCheckpointHandoff(id),
679
+ },
680
+ writer: {
681
+ resolve: (id, requestId, response) => runtime?.resolveServerRequest(id, requestId, response) === true,
682
+ reject: (id, requestId, error) => runtime?.rejectServerRequest(id, requestId, error),
683
+ recovery: (id) => {
684
+ const ownedRuntime = runtime;
685
+ const session = sessions.find(id);
686
+ if (!ownedRuntime || !session)
687
+ return null;
688
+ return {
689
+ activeTurnId: session.activeTurnId,
690
+ current: () => runtime === ownedRuntime,
691
+ recycle: (at) => ownedRuntime.recycle(session, at),
692
+ };
693
+ },
694
+ },
695
+ currentTurn: (id) => sessions.find(id)?.activeTurnId,
696
+ saveSession: (session) => saveSession(session),
697
+ turnCompleted: (sessionId, occurredAt) => activity.observe({ sessionId, occurredAt, kind: 'turnCompleted' }),
698
+ publishFailure: (sessionId, requestId, occurredAt) => {
699
+ events.publish(journal.append(sessionId, 'org-plan.checkpoint-handoff-failed', {
700
+ requestId,
701
+ reason: 'checkpointHandoffFailed',
702
+ ...(autopilotStore.find(sessionId)?.checkpoints?.activeHandoffId
703
+ ? { traceId: autopilotStore.find(sessionId).checkpoints.activeHandoffId }
704
+ : {}),
705
+ }, occurredAt));
706
+ },
707
+ publishSettlement: publishAttentionSettlement,
708
+ failureResponse: checkpointFailureResponse,
709
+ now: () => new Date().toISOString(),
710
+ deadlineMs: options.checkpointHandoffDeadlineMs ?? 5_000,
711
+ schedule: (callback, delayMs) => {
712
+ const handle = setTimeout(callback, delayMs);
713
+ handle.unref?.();
714
+ return () => clearTimeout(handle);
715
+ },
716
+ });
717
+ const attentionAcknowledgement = new AttentionAcknowledgement({
718
+ deadlineMs: options.attentionAcknowledgementDeadlineMs ?? 5_000,
719
+ schedule: (callback, delayMs) => {
720
+ const handle = setTimeout(callback, delayMs);
721
+ handle.unref?.();
722
+ return () => clearTimeout(handle);
723
+ },
724
+ recoverWriter: (sessionId, requestId) => {
756
725
  const ownedRuntime = runtime;
757
726
  const session = sessions.find(sessionId);
758
727
  if (!ownedRuntime || !session || !ownedRuntime.abandonServerRequest(sessionId, requestId))
@@ -761,21 +730,10 @@ export async function composeRelayApp(options) {
761
730
  .recycle(session, new Date().toISOString())
762
731
  .then((recovered) => saveSession(recovered))
763
732
  .catch(() => {
764
- // The durable attention survives; normal session recovery can reacquire the writer.
733
+ // Durable attention survives; normal recovery can reacquire the writer.
765
734
  });
766
- }, options.attentionAcknowledgementDeadlineMs ?? 5_000);
767
- handle.unref?.();
768
- attentionAcknowledgementTimers.set(key, { handle, token });
769
- };
770
- const failPendingCheckpointHandoffs = (sessionId, recoverBoundary) => {
771
- for (const interaction of interactions.list(sessionId)) {
772
- if (interaction.kind !== 'orgPlanCheckpoint')
773
- continue;
774
- failCheckpointHandoff(sessionId, interaction.requestId, interaction.turnId ?? null);
775
- }
776
- if (recoverBoundary)
777
- autopilot.recoverCheckpointHandoff(sessionId);
778
- };
735
+ },
736
+ });
779
737
  let closing = false;
780
738
  let runtime = null;
781
739
  const takeover = new SupervisionTakeover({
@@ -1103,10 +1061,9 @@ export async function composeRelayApp(options) {
1103
1061
  let rawInteraction = toPendingInteraction(request);
1104
1062
  const compactCheckpointKind = compactOrgPlanCheckpointKind(request);
1105
1063
  if (compactCheckpointKind || rawInteraction?.kind === 'orgPlanCheckpoint') {
1106
- // A checkpoint is a read barrier, not a race against the debounced watcher.
1107
- const refreshed = await planStatusSource.refresh(sessionId);
1108
- if (refreshed?.kind !== 'updated')
1109
- return (runtime?.resolveServerRequest(sessionId, String(request.id), checkpointFailureResponse('planProjectionUnavailable')) === true);
1064
+ const refreshed = await checkpoints.refresh(sessionId, String(request.id));
1065
+ if (refreshed !== null)
1066
+ return refreshed;
1110
1067
  }
1111
1068
  const session = withPendingInteractions(sessions.find(sessionId));
1112
1069
  if (!session)
@@ -1249,24 +1206,10 @@ export async function composeRelayApp(options) {
1249
1206
  }) === true);
1250
1207
  }
1251
1208
  if (!rawInteraction && compactCheckpointKind) {
1252
- const retained = supervisedPlans.find(sessionId);
1253
- const identity = supervisedPlans.identity(sessionId);
1254
- const checkpoint = retained && identity
1255
- ? resolveOrgPlanCheckpointSignal(compactCheckpointKind, retained, identity, supervisedPlans.publicationReason(sessionId), autopilotStore
1256
- .find(sessionId)
1257
- ?.checkpoints?.completionEpochs?.filter((epoch) => epoch.completed && !epoch.reopened)
1258
- .map((epoch) => epoch.target), autopilotStore.find(sessionId)?.checkpoints?.pendingTarget)
1259
- : null;
1260
- if (checkpoint)
1261
- rawInteraction = {
1262
- requestId: String(request.id),
1263
- kind: 'orgPlanCheckpoint',
1264
- payload: checkpoint,
1265
- };
1266
- else
1267
- return (runtime?.resolveServerRequest(sessionId, String(request.id), toOrgPlanCheckpointToolResponse('failed', {
1268
- reasonCode: 'checkpointBoundaryAmbiguous',
1269
- })) === true);
1209
+ const expanded = checkpoints.expand(sessionId, String(request.id), compactCheckpointKind);
1210
+ if ('handled' in expanded)
1211
+ return expanded.handled;
1212
+ rawInteraction = expanded.interaction;
1270
1213
  }
1271
1214
  if (!rawInteraction && isOrgPlanTakeoverCall(request)) {
1272
1215
  const result = origin.kind === 'root' &&
@@ -1324,84 +1267,18 @@ export async function composeRelayApp(options) {
1324
1267
  }
1325
1268
  return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, autopilotWaitLeaseToolResponse()) === true);
1326
1269
  }
1327
- if (rawInteraction.kind === 'orgPlanCheckpoint') {
1328
- const checkpoint = parseOrgPlanCheckpoint(rawInteraction.payload);
1329
- const retained = supervisedPlans.find(sessionId);
1330
- const identity = supervisedPlans.identity(sessionId);
1331
- const rootOwned = origin.kind === 'root' && origin.physicalTurnId === session.activeTurnId;
1332
- if (!checkpoint ||
1333
- !retained ||
1334
- !identity ||
1335
- checkpoint.planIdentity !== identity ||
1336
- !rootOwned)
1337
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse(!checkpoint
1338
- ? compactCheckpointKind === 'l1Accepted'
1339
- ? 'acceptedL1NotResolved'
1340
- : 'checkpointPayloadInvalid'
1341
- : !retained
1342
- ? 'planProjectionUnavailable'
1343
- : !identity || checkpoint.planIdentity !== identity
1344
- ? 'planIdentityMismatch'
1345
- : 'rootNotOwner')) === true);
1346
- const validation = validateOrgPlanCheckpoint({
1347
- checkpoint,
1348
- plan: retained,
1349
- planIdentity: identity,
1350
- rootOwned,
1351
- hasActiveL1Writer: (position) => hasActiveL1Writer(activity.snapshot(sessionId, new Date().toISOString()), position),
1270
+ if (rawInteraction.kind === 'orgPlanCheckpoint')
1271
+ return checkpoints.accept(sessionId, rawInteraction, {
1272
+ activeTurnId: session.activeTurnId,
1273
+ rootOwned: origin.kind === 'root' && origin.physicalTurnId === session.activeTurnId,
1274
+ compactKind: compactCheckpointKind,
1352
1275
  });
1353
- if (!validation.valid || !session.activeTurnId)
1354
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse(validation.valid ? 'rootTurnNotActive' : validation.reasonCode, {
1355
- ...(!validation.valid && validation.expected
1356
- ? { expected: validation.expected }
1357
- : {}),
1358
- ...(!validation.valid && validation.observed
1359
- ? { observed: validation.observed }
1360
- : {}),
1361
- })) === true);
1362
- let recordStatus = 'failed';
1363
- try {
1364
- recordStatus = autopilot.checkpointAccepted(sessionId, checkpoint, session.activeTurnId, new Date().toISOString());
1365
- }
1366
- catch {
1367
- if (!autopilot.checkpointHandoffFailed(sessionId, session.activeTurnId))
1368
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse('checkpointPersistenceFailed')) === true);
1369
- const interaction = {
1370
- ...rawInteraction,
1371
- turnId: session.activeTurnId,
1372
- requestedAt: new Date().toISOString(),
1373
- };
1374
- interactions.add(sessionId, interaction);
1375
- failCheckpointHandoff(sessionId, rawInteraction.requestId, session.activeTurnId);
1376
- return true;
1377
- }
1378
- if (recordStatus === 'failed')
1379
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse('checkpointStateConflict')) === true);
1380
- if (recordStatus === 'alreadyRecorded')
1381
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, toOrgPlanCheckpointToolResponse('alreadyRecorded')) === true);
1382
- const interaction = {
1383
- ...rawInteraction,
1384
- turnId: session.activeTurnId,
1385
- requestedAt: new Date().toISOString(),
1386
- };
1387
- interactions.add(sessionId, interaction);
1388
- armCheckpointHandoffDeadline(sessionId, rawInteraction.requestId, session.activeTurnId);
1389
- try {
1390
- runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, toOrgPlanCheckpointToolResponse('recorded'));
1391
- }
1392
- catch {
1393
- // The accepted hold remains owned by the bounded deadline.
1394
- }
1395
- // `true` retains the checkpoint-specific held request. Its timer
1396
- // is cancelled solely by the JSON-RPC write-settlement callback.
1397
- return true;
1398
- }
1399
1276
  if (rawInteraction.kind === 'orgPlanAttention') {
1400
1277
  try {
1401
1278
  acceptPendingInteraction(sessionId, rawInteraction, session, true);
1402
1279
  const acknowledged = runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, toOrgPlanAttentionAcknowledgement()) === true;
1403
1280
  if (acknowledged)
1404
- armAttentionAcknowledgementDeadline(sessionId, rawInteraction.requestId);
1281
+ attentionAcknowledgement.arm(sessionId, rawInteraction.requestId);
1405
1282
  return acknowledged;
1406
1283
  }
1407
1284
  catch {
@@ -1410,14 +1287,14 @@ export async function composeRelayApp(options) {
1410
1287
  reason: 'persistenceFailed',
1411
1288
  })) === true;
1412
1289
  if (rejected)
1413
- armAttentionAcknowledgementDeadline(sessionId, rawInteraction.requestId);
1290
+ attentionAcknowledgement.arm(sessionId, rawInteraction.requestId);
1414
1291
  return rejected;
1415
1292
  }
1416
1293
  }
1417
1294
  return acceptPendingInteraction(sessionId, rawInteraction, session);
1418
1295
  }, (sessionId) => {
1419
1296
  activity.disconnected(sessionId, new Date().toISOString());
1420
- failPendingCheckpointHandoffs(sessionId, false);
1297
+ checkpoints.failPending(sessionId, false);
1421
1298
  dismissPendingInteractions(sessionId, new Date().toISOString(), 'failed');
1422
1299
  recoverExitedSession(sessionId);
1423
1300
  }, undefined, planStatusSource, acceptPlanUpdate, options.planMeasurementBaseUrl, 30_000, 64, root, (session) => sessionModelConfig.resolve(session), {
@@ -1565,21 +1442,9 @@ export async function composeRelayApp(options) {
1565
1442
  })
1566
1443
  : null;
1567
1444
  runtime?.onServerResponseSettled((sessionId, requestId, outcome) => {
1568
- if (attentionAcknowledgementTimers.has(checkpointTimerKey(sessionId, requestId))) {
1569
- cancelAttentionAcknowledgementTimer(sessionId, requestId);
1570
- return;
1571
- }
1572
- const interaction = interactions.find(sessionId, requestId);
1573
- if (interaction?.kind !== 'orgPlanCheckpoint')
1445
+ if (attentionAcknowledgement.responseSettled(sessionId, requestId))
1574
1446
  return;
1575
- if (outcome !== 'resultWritten') {
1576
- failCheckpointHandoff(sessionId, requestId, interaction.turnId ?? null);
1577
- return;
1578
- }
1579
- cancelCheckpointHandoffTimer(sessionId, requestId);
1580
- const occurredAt = new Date().toISOString();
1581
- if (interactions.resolve(sessionId, requestId, occurredAt, 'answered'))
1582
- publishAttentionSettlement(sessionId, requestId, occurredAt, 'answered');
1447
+ checkpoints.responseSettled(sessionId, requestId, outcome);
1583
1448
  });
1584
1449
  if (runtime && planMeasurementHelperPath) {
1585
1450
  planMeasurementRefresh = new PlanMeasurementRefresh(async (sessionId) => {
@@ -1680,6 +1545,56 @@ export async function composeRelayApp(options) {
1680
1545
  }
1681
1546
  };
1682
1547
  }
1548
+ const attentionResolution = new AttentionResolution({
1549
+ operations: {
1550
+ find: (id, requestId) => interactions.find(id, requestId),
1551
+ terminalOperation: (id, requestId) => interactions.terminalOperation(id, requestId),
1552
+ claimOperation: (id, requestId, key) => interactions.claimOperation(id, requestId, key),
1553
+ resolved: (id, requestId) => interactions.resolved(id, requestId),
1554
+ resolutionState: (id, requestId) => interactions.resolutionState(id, requestId),
1555
+ beginDelivery: (id, requestId, key) => interactions.beginDelivery(id, requestId, key),
1556
+ retryDelivery: (id, requestId, key, state) => interactions.retryDelivery(id, requestId, key, state),
1557
+ settleOperation: (id, requestId, key, at, outcome) => interactions.settleOperation(id, requestId, key, at, outcome),
1558
+ },
1559
+ replay: {
1560
+ find: (scope, key) => idempotency.get(scope, key),
1561
+ remember: (scope, key, body) => idempotency.put(scope, key, 202, body),
1562
+ },
1563
+ writer: {
1564
+ available: () => runtime !== null,
1565
+ capable: (id) => sessions.find(id)?.attentionToolCapability === 'supported',
1566
+ state: (id, requestId) => runtime.attentionWriterState(id, requestId),
1567
+ resolve: (id, requestId, response) => runtime.resolveServerRequest(id, requestId, response),
1568
+ guidance: (sessionId) => {
1569
+ const session = sessions.find(sessionId);
1570
+ if (!runtime || !session)
1571
+ return null;
1572
+ return async (text, operationKey) => {
1573
+ const writer = await runtime.ensureWriter(session, new Date().toISOString());
1574
+ if (writer.session.activeTurnId)
1575
+ await runtime.queueTurnInput(writer.session, writer.session.activeTurnId, text, operationKey);
1576
+ else {
1577
+ const started = await runtime.startTurn(writer.session, text, operationKey, new Date().toISOString());
1578
+ sessions.save(started);
1579
+ activity.observe({
1580
+ sessionId,
1581
+ occurredAt: started.updatedAt,
1582
+ kind: 'turnStarted',
1583
+ threadId: started.threadId,
1584
+ turnId: started.activeTurnId,
1585
+ });
1586
+ }
1587
+ };
1588
+ },
1589
+ },
1590
+ policy: {
1591
+ authorizeReplacement: (id, taskName) => autopilot.authorizeExecutorReplacement(id, taskName).accepted,
1592
+ enable: (id) => autopilot.enable(id),
1593
+ disable: (id) => autopilot.disable(id),
1594
+ },
1595
+ publishSettlement: publishAttentionSettlement,
1596
+ now: () => new Date().toISOString(),
1597
+ });
1683
1598
  let authorization;
1684
1599
  if (passkeyAuthEnabled) {
1685
1600
  try {
@@ -2186,149 +2101,7 @@ export async function composeRelayApp(options) {
2186
2101
  : null;
2187
2102
  },
2188
2103
  },
2189
- resolver: {
2190
- resolve: async ({ sessionId, requestId, operationKey, response }) => {
2191
- const scope = `org-plan-attention:${sessionId}:${requestId}`;
2192
- const stored = idempotency.get(scope, operationKey);
2193
- if (stored)
2194
- return JSON.parse(stored.body);
2195
- const terminal = interactions.terminalOperation(sessionId, requestId);
2196
- if (terminal)
2197
- return terminal.operationKey === operationKey
2198
- ? terminal.outcome === 'failed'
2199
- ? { kind: 'writerCleared', resolvedAt: terminal.resolvedAt }
2200
- : { kind: 'replayed', resolvedAt: terminal.resolvedAt }
2201
- : { kind: 'staleOperation' };
2202
- const key = `${scope}:${operationKey}`;
2203
- const inFlight = attentionResolutionOperations.get(key);
2204
- if (inFlight)
2205
- return inFlight;
2206
- const operation = (async () => {
2207
- const interaction = interactions.find(sessionId, requestId);
2208
- if (!interaction || interaction.kind !== 'orgPlanAttention')
2209
- return { kind: 'noActive' };
2210
- const decision = parseOrgPlanAttentionToolResponse(response);
2211
- const attention = parseOrgPlanAttention(interaction.payload);
2212
- if (!decision || !attention)
2213
- return { kind: 'staleOperation' };
2214
- const claim = interactions.claimOperation(sessionId, requestId, operationKey);
2215
- if (claim === 'resolved') {
2216
- const resolved = interactions.resolved(sessionId, requestId);
2217
- return resolved
2218
- ? { kind: 'replayed', resolvedAt: resolved.resolvedAt }
2219
- : { kind: 'staleOperation' };
2220
- }
2221
- if (claim === 'stale')
2222
- return { kind: 'staleOperation' };
2223
- if (claim === 'missing')
2224
- return { kind: 'noActive' };
2225
- const acknowledged = interactions.resolutionState(sessionId, requestId) === 'acknowledged';
2226
- if (acknowledged) {
2227
- if (!interactions.beginDelivery(sessionId, requestId, operationKey))
2228
- return { kind: 'staleOperation' };
2229
- if (decision.action === 'resume' && attention.executorReplacement) {
2230
- const authorization = autopilot.authorizeExecutorReplacement(sessionId, attention.executorReplacement.canonicalTaskName);
2231
- if (!authorization.accepted) {
2232
- interactions.retryDelivery(sessionId, requestId, operationKey, 'acknowledged');
2233
- return { kind: 'replacementRejected' };
2234
- }
2235
- }
2236
- // The dynamic tool already returned its acknowledgement. The
2237
- // later human response must reach the supervisor as new input.
2238
- if (decision.action === 'resume' && decision.guidance) {
2239
- const session = sessions.find(sessionId);
2240
- if (!runtime || !session) {
2241
- interactions.retryDelivery(sessionId, requestId, operationKey, 'acknowledged');
2242
- return { kind: 'writerUnavailable' };
2243
- }
2244
- try {
2245
- const writer = await runtime.ensureWriter(session, new Date().toISOString());
2246
- const text = `The user resolved the Autopilot attention request. Guidance:\n${decision.guidance}`;
2247
- if (writer.session.activeTurnId)
2248
- await runtime.queueTurnInput(writer.session, writer.session.activeTurnId, text, operationKey);
2249
- else {
2250
- const started = await runtime.startTurn(writer.session, text, operationKey, new Date().toISOString());
2251
- sessions.save(started);
2252
- activity.observe({
2253
- sessionId,
2254
- occurredAt: started.updatedAt,
2255
- kind: 'turnStarted',
2256
- threadId: started.threadId,
2257
- turnId: started.activeTurnId,
2258
- });
2259
- }
2260
- }
2261
- catch {
2262
- interactions.retryDelivery(sessionId, requestId, operationKey, 'acknowledged');
2263
- return { kind: 'writerUnavailable' };
2264
- }
2265
- }
2266
- const resolvedAt = new Date().toISOString();
2267
- if (!interactions.settleOperation(sessionId, requestId, operationKey, resolvedAt, 'answered'))
2268
- return { kind: 'staleOperation' };
2269
- const accepted = { kind: 'accepted', resolvedAt };
2270
- idempotency.put(scope, operationKey, 202, JSON.stringify({ kind: 'replayed', resolvedAt }));
2271
- publishAttentionSettlement(sessionId, requestId, resolvedAt, 'answered');
2272
- if (decision.action === 'disableAutopilot')
2273
- autopilot.disable(sessionId);
2274
- else
2275
- autopilot.enable(sessionId);
2276
- return accepted;
2277
- }
2278
- // A durable capability belongs to the session/thread, not the
2279
- // relay process. A supported stopped writer is retryable;
2280
- // missing capability identifies a pre-rollout legacy thread.
2281
- if (sessions.find(sessionId)?.attentionToolCapability !== 'supported')
2282
- return { kind: 'legacyUnsupported' };
2283
- if (!runtime)
2284
- return { kind: 'writerUnavailable' };
2285
- if (!interactions.beginDelivery(sessionId, requestId, operationKey))
2286
- return { kind: 'staleOperation' };
2287
- if (decision.action === 'resume' && attention.executorReplacement) {
2288
- const authorization = autopilot.authorizeExecutorReplacement(sessionId, attention.executorReplacement.canonicalTaskName);
2289
- if (!authorization.accepted) {
2290
- interactions.retryDelivery(sessionId, requestId, operationKey);
2291
- return { kind: 'replacementRejected' };
2292
- }
2293
- }
2294
- const writer = runtime.attentionWriterState(sessionId, requestId);
2295
- if (writer === 'unavailable') {
2296
- interactions.retryDelivery(sessionId, requestId, operationKey);
2297
- return { kind: 'writerUnavailable' };
2298
- }
2299
- const resolvedAt = new Date().toISOString();
2300
- if (writer === 'cleared') {
2301
- if (!interactions.settleOperation(sessionId, requestId, operationKey, resolvedAt, 'failed'))
2302
- return { kind: 'staleOperation' };
2303
- publishAttentionSettlement(sessionId, requestId, resolvedAt, 'failed');
2304
- return { kind: 'writerCleared', resolvedAt };
2305
- }
2306
- if (!runtime.resolveServerRequest(sessionId, requestId, response)) {
2307
- // The state check and delivery are synchronous, but retain a
2308
- // defensive retry path for a future runtime implementation.
2309
- interactions.retryDelivery(sessionId, requestId, operationKey);
2310
- return { kind: 'writerUnavailable' };
2311
- }
2312
- if (!interactions.settleOperation(sessionId, requestId, operationKey, resolvedAt, 'answered'))
2313
- return { kind: 'staleOperation' };
2314
- const accepted = { kind: 'accepted', resolvedAt };
2315
- idempotency.put(scope, operationKey, 202, JSON.stringify({ kind: 'replayed', resolvedAt }));
2316
- publishAttentionSettlement(sessionId, requestId, resolvedAt, 'answered');
2317
- if (decision.action === 'disableAutopilot')
2318
- autopilot.disable(sessionId);
2319
- else
2320
- autopilot.enable(sessionId);
2321
- return accepted;
2322
- })();
2323
- attentionResolutionOperations.set(key, operation);
2324
- try {
2325
- return await operation;
2326
- }
2327
- finally {
2328
- attentionResolutionOperations.delete(key);
2329
- }
2330
- },
2331
- },
2104
+ resolver: attentionResolution,
2332
2105
  transitions: attentionTransitions,
2333
2106
  },
2334
2107
  gitSummary: {
@@ -2383,7 +2156,7 @@ export async function composeRelayApp(options) {
2383
2156
  // A prior process cannot resolve its original JSON-RPC request. Turn
2384
2157
  // that bounded handoff into one durable failure and release the
2385
2158
  // checkpoint only through the explicit runtime-recovery boundary.
2386
- failPendingCheckpointHandoffs(session.id, true);
2159
+ checkpoints.failPending(session.id, true);
2387
2160
  });
2388
2161
  };
2389
2162
  app.addHook('onListen', async () => {
@@ -2434,22 +2207,8 @@ export async function composeRelayApp(options) {
2434
2207
  for (const session of sessions.list()) {
2435
2208
  autopilot.dispose(session.id);
2436
2209
  activity.dispose(session.id);
2437
- for (const key of [...checkpointHandoffTimers.keys()]) {
2438
- if (key.startsWith(`${session.id}:`)) {
2439
- const timer = checkpointHandoffTimers.get(key);
2440
- if (timer)
2441
- clearTimeout(timer.handle);
2442
- checkpointHandoffTimers.delete(key);
2443
- }
2444
- }
2445
- for (const key of [...attentionAcknowledgementTimers.keys()]) {
2446
- if (key.startsWith(`${session.id}:`)) {
2447
- const timer = attentionAcknowledgementTimers.get(key);
2448
- if (timer)
2449
- clearTimeout(timer.handle);
2450
- attentionAcknowledgementTimers.delete(key);
2451
- }
2452
- }
2210
+ checkpoints.disposeSession(session.id);
2211
+ attentionAcknowledgement.disposeSession(session.id);
2453
2212
  // Relay shutdown only releases this process's writer. A typed attention
2454
2213
  // request remains a durable human-visible blocker for the next relay
2455
2214
  // instance; only an app-server-cleared request is a failed audit outcome.