gestalt-mobile 0.65.4 → 0.65.6

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' &&
@@ -1294,10 +1237,9 @@ export async function composeRelayApp(options) {
1294
1237
  scheduleAgentCapacityRecovery(sessionId, () => runtime?.resolveServerRequest(sessionId, String(request.id), agentCapacityRecoveryToolResponse()) === true));
1295
1238
  }
1296
1239
  if (!rawInteraction && isAutopilotWaitLeaseCall(request)) {
1297
- const rootOwned = origin.kind === 'root' && origin.physicalTurnId === session.activeTurnId;
1298
- if (rootOwned)
1299
- autopilot.rejectProbe(sessionId);
1300
- return (runtime?.resolveServerRequest(sessionId, String(request.id), autopilotWaitLeaseToolResponse(false)) === true);
1240
+ // Invalid tool arguments are recoverable in this turn. They do not
1241
+ // establish that supervision is stalled or revoke continuation.
1242
+ return (runtime?.resolveServerRequest(sessionId, String(request.id), autopilotWaitLeaseToolResponse(false, 'invalidWaitLease')) === true);
1301
1243
  }
1302
1244
  if (!rawInteraction)
1303
1245
  return false;
@@ -1319,92 +1261,24 @@ export async function composeRelayApp(options) {
1319
1261
  wakeConditions: lease.wakeConditions,
1320
1262
  }));
1321
1263
  if (registration !== true) {
1322
- if (rootOwned && registration === false)
1323
- autopilot.rejectProbe(sessionId);
1324
1264
  return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, autopilotWaitLeaseToolResponse(false, registration === 'wakeAlreadySatisfied'
1325
1265
  ? 'wakeAlreadySatisfied'
1326
1266
  : 'automaticContinuationUnavailable')) === true);
1327
1267
  }
1328
1268
  return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, autopilotWaitLeaseToolResponse()) === true);
1329
1269
  }
1330
- if (rawInteraction.kind === 'orgPlanCheckpoint') {
1331
- const checkpoint = parseOrgPlanCheckpoint(rawInteraction.payload);
1332
- const retained = supervisedPlans.find(sessionId);
1333
- const identity = supervisedPlans.identity(sessionId);
1334
- const rootOwned = origin.kind === 'root' && origin.physicalTurnId === session.activeTurnId;
1335
- if (!checkpoint ||
1336
- !retained ||
1337
- !identity ||
1338
- checkpoint.planIdentity !== identity ||
1339
- !rootOwned)
1340
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse(!checkpoint
1341
- ? compactCheckpointKind === 'l1Accepted'
1342
- ? 'acceptedL1NotResolved'
1343
- : 'checkpointPayloadInvalid'
1344
- : !retained
1345
- ? 'planProjectionUnavailable'
1346
- : !identity || checkpoint.planIdentity !== identity
1347
- ? 'planIdentityMismatch'
1348
- : 'rootNotOwner')) === true);
1349
- const validation = validateOrgPlanCheckpoint({
1350
- checkpoint,
1351
- plan: retained,
1352
- planIdentity: identity,
1353
- rootOwned,
1354
- 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,
1355
1275
  });
1356
- if (!validation.valid || !session.activeTurnId)
1357
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse(validation.valid ? 'rootTurnNotActive' : validation.reasonCode, {
1358
- ...(!validation.valid && validation.expected
1359
- ? { expected: validation.expected }
1360
- : {}),
1361
- ...(!validation.valid && validation.observed
1362
- ? { observed: validation.observed }
1363
- : {}),
1364
- })) === true);
1365
- let recordStatus = 'failed';
1366
- try {
1367
- recordStatus = autopilot.checkpointAccepted(sessionId, checkpoint, session.activeTurnId, new Date().toISOString());
1368
- }
1369
- catch {
1370
- if (!autopilot.checkpointHandoffFailed(sessionId, session.activeTurnId))
1371
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse('checkpointPersistenceFailed')) === true);
1372
- const interaction = {
1373
- ...rawInteraction,
1374
- turnId: session.activeTurnId,
1375
- requestedAt: new Date().toISOString(),
1376
- };
1377
- interactions.add(sessionId, interaction);
1378
- failCheckpointHandoff(sessionId, rawInteraction.requestId, session.activeTurnId);
1379
- return true;
1380
- }
1381
- if (recordStatus === 'failed')
1382
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, checkpointFailureResponse('checkpointStateConflict')) === true);
1383
- if (recordStatus === 'alreadyRecorded')
1384
- return (runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, toOrgPlanCheckpointToolResponse('alreadyRecorded')) === true);
1385
- const interaction = {
1386
- ...rawInteraction,
1387
- turnId: session.activeTurnId,
1388
- requestedAt: new Date().toISOString(),
1389
- };
1390
- interactions.add(sessionId, interaction);
1391
- armCheckpointHandoffDeadline(sessionId, rawInteraction.requestId, session.activeTurnId);
1392
- try {
1393
- runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, toOrgPlanCheckpointToolResponse('recorded'));
1394
- }
1395
- catch {
1396
- // The accepted hold remains owned by the bounded deadline.
1397
- }
1398
- // `true` retains the checkpoint-specific held request. Its timer
1399
- // is cancelled solely by the JSON-RPC write-settlement callback.
1400
- return true;
1401
- }
1402
1276
  if (rawInteraction.kind === 'orgPlanAttention') {
1403
1277
  try {
1404
1278
  acceptPendingInteraction(sessionId, rawInteraction, session, true);
1405
1279
  const acknowledged = runtime?.resolveServerRequest(sessionId, rawInteraction.requestId, toOrgPlanAttentionAcknowledgement()) === true;
1406
1280
  if (acknowledged)
1407
- armAttentionAcknowledgementDeadline(sessionId, rawInteraction.requestId);
1281
+ attentionAcknowledgement.arm(sessionId, rawInteraction.requestId);
1408
1282
  return acknowledged;
1409
1283
  }
1410
1284
  catch {
@@ -1413,14 +1287,14 @@ export async function composeRelayApp(options) {
1413
1287
  reason: 'persistenceFailed',
1414
1288
  })) === true;
1415
1289
  if (rejected)
1416
- armAttentionAcknowledgementDeadline(sessionId, rawInteraction.requestId);
1290
+ attentionAcknowledgement.arm(sessionId, rawInteraction.requestId);
1417
1291
  return rejected;
1418
1292
  }
1419
1293
  }
1420
1294
  return acceptPendingInteraction(sessionId, rawInteraction, session);
1421
1295
  }, (sessionId) => {
1422
1296
  activity.disconnected(sessionId, new Date().toISOString());
1423
- failPendingCheckpointHandoffs(sessionId, false);
1297
+ checkpoints.failPending(sessionId, false);
1424
1298
  dismissPendingInteractions(sessionId, new Date().toISOString(), 'failed');
1425
1299
  recoverExitedSession(sessionId);
1426
1300
  }, undefined, planStatusSource, acceptPlanUpdate, options.planMeasurementBaseUrl, 30_000, 64, root, (session) => sessionModelConfig.resolve(session), {
@@ -1568,21 +1442,9 @@ export async function composeRelayApp(options) {
1568
1442
  })
1569
1443
  : null;
1570
1444
  runtime?.onServerResponseSettled((sessionId, requestId, outcome) => {
1571
- if (attentionAcknowledgementTimers.has(checkpointTimerKey(sessionId, requestId))) {
1572
- cancelAttentionAcknowledgementTimer(sessionId, requestId);
1573
- return;
1574
- }
1575
- const interaction = interactions.find(sessionId, requestId);
1576
- if (interaction?.kind !== 'orgPlanCheckpoint')
1577
- return;
1578
- if (outcome !== 'resultWritten') {
1579
- failCheckpointHandoff(sessionId, requestId, interaction.turnId ?? null);
1445
+ if (attentionAcknowledgement.responseSettled(sessionId, requestId))
1580
1446
  return;
1581
- }
1582
- cancelCheckpointHandoffTimer(sessionId, requestId);
1583
- const occurredAt = new Date().toISOString();
1584
- if (interactions.resolve(sessionId, requestId, occurredAt, 'answered'))
1585
- publishAttentionSettlement(sessionId, requestId, occurredAt, 'answered');
1447
+ checkpoints.responseSettled(sessionId, requestId, outcome);
1586
1448
  });
1587
1449
  if (runtime && planMeasurementHelperPath) {
1588
1450
  planMeasurementRefresh = new PlanMeasurementRefresh(async (sessionId) => {
@@ -1683,6 +1545,56 @@ export async function composeRelayApp(options) {
1683
1545
  }
1684
1546
  };
1685
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
+ });
1686
1598
  let authorization;
1687
1599
  if (passkeyAuthEnabled) {
1688
1600
  try {
@@ -2189,149 +2101,7 @@ export async function composeRelayApp(options) {
2189
2101
  : null;
2190
2102
  },
2191
2103
  },
2192
- resolver: {
2193
- resolve: async ({ sessionId, requestId, operationKey, response }) => {
2194
- const scope = `org-plan-attention:${sessionId}:${requestId}`;
2195
- const stored = idempotency.get(scope, operationKey);
2196
- if (stored)
2197
- return JSON.parse(stored.body);
2198
- const terminal = interactions.terminalOperation(sessionId, requestId);
2199
- if (terminal)
2200
- return terminal.operationKey === operationKey
2201
- ? terminal.outcome === 'failed'
2202
- ? { kind: 'writerCleared', resolvedAt: terminal.resolvedAt }
2203
- : { kind: 'replayed', resolvedAt: terminal.resolvedAt }
2204
- : { kind: 'staleOperation' };
2205
- const key = `${scope}:${operationKey}`;
2206
- const inFlight = attentionResolutionOperations.get(key);
2207
- if (inFlight)
2208
- return inFlight;
2209
- const operation = (async () => {
2210
- const interaction = interactions.find(sessionId, requestId);
2211
- if (!interaction || interaction.kind !== 'orgPlanAttention')
2212
- return { kind: 'noActive' };
2213
- const decision = parseOrgPlanAttentionToolResponse(response);
2214
- const attention = parseOrgPlanAttention(interaction.payload);
2215
- if (!decision || !attention)
2216
- return { kind: 'staleOperation' };
2217
- const claim = interactions.claimOperation(sessionId, requestId, operationKey);
2218
- if (claim === 'resolved') {
2219
- const resolved = interactions.resolved(sessionId, requestId);
2220
- return resolved
2221
- ? { kind: 'replayed', resolvedAt: resolved.resolvedAt }
2222
- : { kind: 'staleOperation' };
2223
- }
2224
- if (claim === 'stale')
2225
- return { kind: 'staleOperation' };
2226
- if (claim === 'missing')
2227
- return { kind: 'noActive' };
2228
- const acknowledged = interactions.resolutionState(sessionId, requestId) === 'acknowledged';
2229
- if (acknowledged) {
2230
- if (!interactions.beginDelivery(sessionId, requestId, operationKey))
2231
- return { kind: 'staleOperation' };
2232
- if (decision.action === 'resume' && attention.executorReplacement) {
2233
- const authorization = autopilot.authorizeExecutorReplacement(sessionId, attention.executorReplacement.canonicalTaskName);
2234
- if (!authorization.accepted) {
2235
- interactions.retryDelivery(sessionId, requestId, operationKey, 'acknowledged');
2236
- return { kind: 'replacementRejected' };
2237
- }
2238
- }
2239
- // The dynamic tool already returned its acknowledgement. The
2240
- // later human response must reach the supervisor as new input.
2241
- if (decision.action === 'resume' && decision.guidance) {
2242
- const session = sessions.find(sessionId);
2243
- if (!runtime || !session) {
2244
- interactions.retryDelivery(sessionId, requestId, operationKey, 'acknowledged');
2245
- return { kind: 'writerUnavailable' };
2246
- }
2247
- try {
2248
- const writer = await runtime.ensureWriter(session, new Date().toISOString());
2249
- const text = `The user resolved the Autopilot attention request. Guidance:\n${decision.guidance}`;
2250
- if (writer.session.activeTurnId)
2251
- await runtime.queueTurnInput(writer.session, writer.session.activeTurnId, text, operationKey);
2252
- else {
2253
- const started = await runtime.startTurn(writer.session, text, operationKey, new Date().toISOString());
2254
- sessions.save(started);
2255
- activity.observe({
2256
- sessionId,
2257
- occurredAt: started.updatedAt,
2258
- kind: 'turnStarted',
2259
- threadId: started.threadId,
2260
- turnId: started.activeTurnId,
2261
- });
2262
- }
2263
- }
2264
- catch {
2265
- interactions.retryDelivery(sessionId, requestId, operationKey, 'acknowledged');
2266
- return { kind: 'writerUnavailable' };
2267
- }
2268
- }
2269
- const resolvedAt = new Date().toISOString();
2270
- if (!interactions.settleOperation(sessionId, requestId, operationKey, resolvedAt, 'answered'))
2271
- return { kind: 'staleOperation' };
2272
- const accepted = { kind: 'accepted', resolvedAt };
2273
- idempotency.put(scope, operationKey, 202, JSON.stringify({ kind: 'replayed', resolvedAt }));
2274
- publishAttentionSettlement(sessionId, requestId, resolvedAt, 'answered');
2275
- if (decision.action === 'disableAutopilot')
2276
- autopilot.disable(sessionId);
2277
- else
2278
- autopilot.enable(sessionId);
2279
- return accepted;
2280
- }
2281
- // A durable capability belongs to the session/thread, not the
2282
- // relay process. A supported stopped writer is retryable;
2283
- // missing capability identifies a pre-rollout legacy thread.
2284
- if (sessions.find(sessionId)?.attentionToolCapability !== 'supported')
2285
- return { kind: 'legacyUnsupported' };
2286
- if (!runtime)
2287
- return { kind: 'writerUnavailable' };
2288
- if (!interactions.beginDelivery(sessionId, requestId, operationKey))
2289
- return { kind: 'staleOperation' };
2290
- if (decision.action === 'resume' && attention.executorReplacement) {
2291
- const authorization = autopilot.authorizeExecutorReplacement(sessionId, attention.executorReplacement.canonicalTaskName);
2292
- if (!authorization.accepted) {
2293
- interactions.retryDelivery(sessionId, requestId, operationKey);
2294
- return { kind: 'replacementRejected' };
2295
- }
2296
- }
2297
- const writer = runtime.attentionWriterState(sessionId, requestId);
2298
- if (writer === 'unavailable') {
2299
- interactions.retryDelivery(sessionId, requestId, operationKey);
2300
- return { kind: 'writerUnavailable' };
2301
- }
2302
- const resolvedAt = new Date().toISOString();
2303
- if (writer === 'cleared') {
2304
- if (!interactions.settleOperation(sessionId, requestId, operationKey, resolvedAt, 'failed'))
2305
- return { kind: 'staleOperation' };
2306
- publishAttentionSettlement(sessionId, requestId, resolvedAt, 'failed');
2307
- return { kind: 'writerCleared', resolvedAt };
2308
- }
2309
- if (!runtime.resolveServerRequest(sessionId, requestId, response)) {
2310
- // The state check and delivery are synchronous, but retain a
2311
- // defensive retry path for a future runtime implementation.
2312
- interactions.retryDelivery(sessionId, requestId, operationKey);
2313
- return { kind: 'writerUnavailable' };
2314
- }
2315
- if (!interactions.settleOperation(sessionId, requestId, operationKey, resolvedAt, 'answered'))
2316
- return { kind: 'staleOperation' };
2317
- const accepted = { kind: 'accepted', resolvedAt };
2318
- idempotency.put(scope, operationKey, 202, JSON.stringify({ kind: 'replayed', resolvedAt }));
2319
- publishAttentionSettlement(sessionId, requestId, resolvedAt, 'answered');
2320
- if (decision.action === 'disableAutopilot')
2321
- autopilot.disable(sessionId);
2322
- else
2323
- autopilot.enable(sessionId);
2324
- return accepted;
2325
- })();
2326
- attentionResolutionOperations.set(key, operation);
2327
- try {
2328
- return await operation;
2329
- }
2330
- finally {
2331
- attentionResolutionOperations.delete(key);
2332
- }
2333
- },
2334
- },
2104
+ resolver: attentionResolution,
2335
2105
  transitions: attentionTransitions,
2336
2106
  },
2337
2107
  gitSummary: {
@@ -2386,7 +2156,7 @@ export async function composeRelayApp(options) {
2386
2156
  // A prior process cannot resolve its original JSON-RPC request. Turn
2387
2157
  // that bounded handoff into one durable failure and release the
2388
2158
  // checkpoint only through the explicit runtime-recovery boundary.
2389
- failPendingCheckpointHandoffs(session.id, true);
2159
+ checkpoints.failPending(session.id, true);
2390
2160
  });
2391
2161
  };
2392
2162
  app.addHook('onListen', async () => {
@@ -2437,22 +2207,8 @@ export async function composeRelayApp(options) {
2437
2207
  for (const session of sessions.list()) {
2438
2208
  autopilot.dispose(session.id);
2439
2209
  activity.dispose(session.id);
2440
- for (const key of [...checkpointHandoffTimers.keys()]) {
2441
- if (key.startsWith(`${session.id}:`)) {
2442
- const timer = checkpointHandoffTimers.get(key);
2443
- if (timer)
2444
- clearTimeout(timer.handle);
2445
- checkpointHandoffTimers.delete(key);
2446
- }
2447
- }
2448
- for (const key of [...attentionAcknowledgementTimers.keys()]) {
2449
- if (key.startsWith(`${session.id}:`)) {
2450
- const timer = attentionAcknowledgementTimers.get(key);
2451
- if (timer)
2452
- clearTimeout(timer.handle);
2453
- attentionAcknowledgementTimers.delete(key);
2454
- }
2455
- }
2210
+ checkpoints.disposeSession(session.id);
2211
+ attentionAcknowledgement.disposeSession(session.id);
2456
2212
  // Relay shutdown only releases this process's writer. A typed attention
2457
2213
  // request remains a durable human-visible blocker for the next relay
2458
2214
  // instance; only an app-server-cleared request is a failed audit outcome.