pi-harness-runtime 1.1.470 → 1.1.471

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/harness/pending-countdown.ts +12 -37
  3. package/index.ts +434 -277
  4. package/package.json +1 -1
  5. package/packages/agent-policy/package.json +1 -1
  6. package/packages/auth/package.json +1 -1
  7. package/packages/autonomous-runtime/package.json +1 -1
  8. package/packages/checkpoint/package.json +1 -1
  9. package/packages/clipboard/package.json +1 -1
  10. package/packages/codex-watcher/package.json +1 -1
  11. package/packages/config-capture/package.json +1 -1
  12. package/packages/contracts/package.json +1 -1
  13. package/packages/cookie-sanitizer/package.json +1 -1
  14. package/packages/evaluation-engine/package.json +1 -1
  15. package/packages/event-bus/package.json +1 -1
  16. package/packages/event-store/package.json +1 -1
  17. package/packages/experience-replay/package.json +1 -1
  18. package/packages/file-copy-helper/package.json +1 -1
  19. package/packages/intent-analyzer/package.json +1 -1
  20. package/packages/jev-judge/dist/auto-continue.d.ts +44 -2
  21. package/packages/jev-judge/dist/auto-continue.d.ts.map +1 -1
  22. package/packages/jev-judge/dist/auto-continue.js +81 -13
  23. package/packages/jev-judge/dist/auto-continue.js.map +1 -1
  24. package/packages/jev-judge/dist/index.d.ts +3 -1
  25. package/packages/jev-judge/dist/index.d.ts.map +1 -1
  26. package/packages/jev-judge/dist/index.js +5 -1
  27. package/packages/jev-judge/dist/index.js.map +1 -1
  28. package/packages/jev-judge/dist/question-risk.d.ts +24 -0
  29. package/packages/jev-judge/dist/question-risk.d.ts.map +1 -1
  30. package/packages/jev-judge/dist/question-risk.js +78 -5
  31. package/packages/jev-judge/dist/question-risk.js.map +1 -1
  32. package/packages/jev-judge/dist/wait-lifecycle.d.ts +248 -0
  33. package/packages/jev-judge/dist/wait-lifecycle.d.ts.map +1 -0
  34. package/packages/jev-judge/dist/wait-lifecycle.js +308 -0
  35. package/packages/jev-judge/dist/wait-lifecycle.js.map +1 -0
  36. package/packages/jev-judge/package.json +1 -1
  37. package/packages/jev-judge/src/auto-continue.ts +110 -13
  38. package/packages/jev-judge/src/index.ts +16 -1
  39. package/packages/jev-judge/src/question-risk.ts +96 -5
  40. package/packages/jev-judge/src/wait-lifecycle.ts +488 -0
  41. package/packages/knowledge-retrieval/package.json +1 -1
  42. package/packages/learning-engine/package.json +1 -1
  43. package/packages/logging/package.json +1 -1
  44. package/packages/memory-engine/package.json +1 -1
  45. package/packages/notification/package.json +1 -1
  46. package/packages/paperclip-integration/package.json +1 -1
  47. package/packages/performance-optimizer/package.json +1 -1
  48. package/packages/privilege-broker/package.json +1 -1
  49. package/packages/prompt-compiler/package.json +1 -1
  50. package/packages/providers/package.json +1 -1
  51. package/packages/qdrant-skills/package.json +1 -1
  52. package/packages/quota-manager/package.json +1 -1
  53. package/packages/relay/package.json +1 -1
  54. package/packages/skill-mcp-client/package.json +1 -1
  55. package/packages/skills/package.json +1 -1
  56. package/packages/todo-bd-sync/package.json +1 -1
  57. package/packages/token-estimation/package.json +1 -1
  58. package/packages/tooling-preference/package.json +1 -1
  59. package/packages/trajectory/package.json +1 -1
  60. package/packages/tui/package.json +1 -1
  61. package/packages/two-phase-review/package.json +1 -1
  62. package/packages/types/package.json +1 -1
  63. package/packages/webmcp-tester/package.json +1 -1
  64. package/packages/wiki/package.json +1 -1
  65. package/packages/write-review/package.json +1 -1
package/index.ts CHANGED
@@ -298,7 +298,14 @@ function keyFileFixesOrFallback(feature: string, labels: string[]): string[] {
298
298
 
299
299
  // Shared state for callback handlers (accessible across init functions)
300
300
  const sharedState = {
301
- waitingForUserSince: null as Date | null,
301
+ /**
302
+ * Release the wait of the lifecycle controller.
303
+ *
304
+ * The controller owns the wait: a question that was answered must
305
+ * release it, so a late evaluation of that question cannot change
306
+ * anything.
307
+ */
308
+ cancelWait: null as null | (() => void),
302
309
  todoContinuationController: null as unknown,
303
310
  // The ledger of the validation runs. The two-phase workflow reads it to
304
311
  // know whether the final tier of a test item passed.
@@ -349,7 +356,9 @@ function applyChannelApproval(
349
356
 
350
357
  // The question is answered, so the wait is over. The wait state is only
351
358
  // cleared after a successful resolution.
352
- sharedState.waitingForUserSince = null;
359
+ // The controller owns the wait: the answer ends it, and an evaluation
360
+ // that is still running is invalidated with it.
361
+ sharedState.cancelWait?.();
353
362
  sharedState.updateAutoContinueStatus?.("IDLE");
354
363
  // The countdown of the answered question is over with it.
355
364
  sharedState.pendingCountdown?.stop();
@@ -901,7 +910,7 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
901
910
  // Resolve the provider chain. Every credential stays bound to its own
902
911
  // provider: a TypeSafe key is never sent to OpenRouter and an OpenRouter
903
912
  // key is never sent to the TypeSafe API.
904
- const { resolveJevProviders, classifyQuestionRisk } = await import("./packages/jev-judge/dist/index.js");
913
+ const { resolveJevProviders, classifyQuestionRisk, extractProposedAction } = await import("./packages/jev-judge/dist/index.js");
905
914
  const jevProviders = resolveJevProviders({ keysDir });
906
915
 
907
916
  // Create pending question controller - works independently of Jev
@@ -941,12 +950,20 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
941
950
  // JavaScript, so importing "src/auto-continue.js" would depend on
942
951
  // build artifacts that are not part of the package.
943
952
  const mod = await import("./packages/jev-judge/dist/auto-continue.js");
953
+ // The lifecycle of the wait for a human answer.
954
+ //
955
+ // The controller owns the question that is waiting, the moment it
956
+ // was asked, the countdown and the decision. The runtime reads the
957
+ // state of the wait; it does not keep a second copy of it, so the
958
+ // countdown, the evaluation and the log always measure the same
959
+ // wait.
960
+ const { WaitLifecycleController } = await import(
961
+ "./packages/jev-judge/dist/wait-lifecycle.js"
962
+ );
944
963
  // The instruction of an autonomous decision: it names the selected
945
964
  // option, the scope and the reasoning of the decision.
946
965
  const autonomy = await import("./packages/jev-judge/dist/autonomy-instruction.js");
947
966
 
948
- // Track waiting state
949
- let waitingForUserSince: Date | null = null;
950
967
  let lastUserMessage: Date | null = null;
951
968
  let autoContinueTimer: NodeJS.Timeout | null = null;
952
969
  let _inferenceInProgress = false; // Track for overlap prevention
@@ -954,8 +971,47 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
954
971
  // decision of the judge use the same constants, so the displayed
955
972
  // deadline and the decision can never drift apart.
956
973
  const AUTO_CONTINUE_INTERVAL_MS = 60 * 1000; // Fallback poll: every minute
957
- const MIN_WAIT_MINUTES = 5; // Minimum wait before auto-continue
958
- const MAX_WAIT_MINUTES = 30; // After this the work pauses instead of waiting
974
+ const MIN_WAIT_MINUTES = 5; // The question is decided once, after this wait
975
+ // The lifecycle of the wait.
976
+ //
977
+ // The controller owns the request the wait belongs to, the moment
978
+ // the question was asked, the countdown and the evaluation. It runs
979
+ // the evaluation exactly once: a decision to wait ends the automatic
980
+ // attempt, and a provider failure is an error, not a decision.
981
+ const waitLifecycle = new WaitLifecycleController({
982
+ waitMinutes: MIN_WAIT_MINUTES,
983
+ countdown: {
984
+ get active() {
985
+ return pendingCountdown.active;
986
+ },
987
+ start: (requestId: string, startedAt: number) => {
988
+ _countdownSessionId = _piSessionId;
989
+ pendingCountdown.start(requestId, startedAt);
990
+ },
991
+ stop: () => pendingCountdown.stop(),
992
+ },
993
+ currentSessionId: () => _sessionId,
994
+ evaluate: (request, waitedMs) => evaluatePendingQuestion(request, waitedMs),
995
+ onState: (state, detail) => {
996
+ logToFile("[auto-continue]", `The wait is ${state}: ${detail.reason}`);
997
+ },
998
+ onError: (error) => {
999
+ logToFile("[auto-continue]", "The wait lifecycle failed:", oneLineError(error));
1000
+ },
1001
+ });
1002
+
1003
+ /**
1004
+ * Is the harness waiting for an answer of a human?
1005
+ *
1006
+ * The controller owns that state: the runtime only asks.
1007
+ */
1008
+ function isWaitingForUser(): boolean {
1009
+ return (
1010
+ waitLifecycle.currentState === "waiting" ||
1011
+ waitLifecycle.currentState === "evaluating"
1012
+ );
1013
+ }
1014
+
959
1015
  // A continuation was dispatched and its turn has not settled yet.
960
1016
  // The gate owns that state: the status stays "RUN" until the turn
961
1017
  // settles, and no timer may clear it in the meantime.
@@ -1088,31 +1144,33 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1088
1144
  // judge exactly at the deadline. The fallback poll only takes over
1089
1145
  // when there is no countdown, so a decision is never started twice.
1090
1146
  const pendingCountdown = new PendingQuestionCountdown({
1091
- // The two policies of the wait belong to the countdown, so the
1147
+ // The one policy of the wait belongs to the countdown, so the
1092
1148
  // displayed deadline and the deadline of the judge cannot drift
1093
1149
  // apart.
1094
1150
  waitMinutes: MIN_WAIT_MINUTES,
1095
- recheckIntervalMs: AUTO_CONTINUE_INTERVAL_MS,
1096
1151
  render: (view: CountdownView) => {
1097
1152
  _countdownRowRequestId = view.requestId;
1098
1153
  updateAutoContinueStatus(
1099
1154
  "WAITING",
1100
1155
  view.requestId.slice(0, 8),
1101
- view.mode === "recheck"
1102
- ? `Jev will recheck in ${view.remaining}`
1103
- : `Jev decision in ${view.remaining}`,
1156
+ `Jev decision in ${view.remaining}`,
1104
1157
  );
1105
1158
  },
1106
1159
  onDeadline: (requestId: string) => {
1107
1160
  logToFile("[auto-continue]", "The decision deadline was reached:", requestId);
1108
1161
  checkAndAutoContinue("countdown")
1109
1162
  .then(() => {
1110
- // The decision did not start - another one was still in
1163
+ // The decision did not start: another one was still in
1111
1164
  // flight, or the wait was gone before it ran. The
1112
- // deadline is not lost: the countdown is armed again
1113
- // and the decision follows.
1165
+ // deadline is not lost: the fallback poll takes the
1166
+ // decision over, because the lifecycle evaluates a
1167
+ // request exactly once.
1114
1168
  if (pendingCountdown.fired && pendingCountdown.requestId === requestId) {
1115
- pendingCountdown.startRecheck(requestId);
1169
+ logToFile(
1170
+ "[auto-continue]",
1171
+ "The decision did not start - the fallback poll takes over:",
1172
+ requestId,
1173
+ );
1116
1174
  }
1117
1175
  })
1118
1176
  .catch((error) => {
@@ -1126,7 +1184,7 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1126
1184
  // The wait must still belong to the request: a late tick of
1127
1185
  // an answered or replaced question must not draw its status
1128
1186
  // and must not trigger a decision.
1129
- if (!waitingForUserSince) return false;
1187
+ if (!isWaitingForUser()) return false;
1130
1188
  if (_countdownSessionId !== _piSessionId) return false;
1131
1189
  const current = sharedState.pqController?.getCurrentQuestion?.();
1132
1190
  if (!current) return false;
@@ -1157,31 +1215,26 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1157
1215
  sharedState.pendingCountdown = pendingCountdown;
1158
1216
 
1159
1217
  // Wire shared state for callback handlers
1160
- sharedState.waitingForUserSince = waitingForUserSince;
1218
+ sharedState.cancelWait = () => {
1219
+ waitLifecycle.cancel();
1220
+ };
1161
1221
  sharedState.updateAutoContinueStatus = updateAutoContinueStatus;
1162
1222
 
1163
1223
  /**
1164
- * Start the countdown of a pending question.
1224
+ * The short hash of the current question.
1165
1225
  *
1166
- * The deadline of the decision is derived from the wait that is
1167
- * already running, so the displayed deadline and the decision of
1168
- * the judge can never drift apart.
1226
+ * It identifies the question in the status row without showing the
1227
+ * question itself.
1169
1228
  */
1170
- function startPendingCountdown(requestId: string): void {
1171
- _countdownSessionId = _piSessionId;
1172
- const startedAt = waitingForUserSince?.getTime() ?? Date.now();
1173
- pendingCountdown.start(requestId, startedAt);
1174
- }
1175
-
1176
- /**
1177
- * Start the countdown of the next attempt.
1178
- *
1179
- * The judge asked to wait longer: the countdown counts down to the
1180
- * next attempt instead of to the deadline of the decision.
1181
- */
1182
- function startRecheckCountdown(requestId: string): void {
1183
- _countdownSessionId = _piSessionId;
1184
- pendingCountdown.startRecheck(requestId);
1229
+ function questionHash(): string {
1230
+ return _lastNotifiedQuestion
1231
+ ? Math.abs(
1232
+ _lastNotifiedQuestion.split("").reduce((a, c) => {
1233
+ a = ((a << 5) - a) + c.charCodeAt(0);
1234
+ return a & a;
1235
+ }, 0),
1236
+ ).toString(36)
1237
+ : "";
1185
1238
  }
1186
1239
 
1187
1240
  // Update auto-continue status in TUI footer
@@ -1225,8 +1278,9 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1225
1278
  * not keep the harness from noticing the same question again.
1226
1279
  */
1227
1280
  function clearWaitState(): void {
1228
- waitingForUserSince = null;
1229
- sharedState.waitingForUserSince = null;
1281
+ // The controller owns the wait: it releases the request, the
1282
+ // countdown and the timestamp in one move.
1283
+ waitLifecycle.cancel();
1230
1284
  _lastNotifiedQuestion = "";
1231
1285
  }
1232
1286
 
@@ -1376,7 +1430,7 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1376
1430
 
1377
1431
  // Only trigger if: we found a question AND it's different from last notification
1378
1432
  // Skip routine continuation questions - let Jev/todo controller decide
1379
- if (result.detected && result.questionText && result.questionText !== _lastNotifiedQuestion && !waitingForUserSince) {
1433
+ if (result.detected && result.questionText && result.questionText !== _lastNotifiedQuestion && !isWaitingForUser()) {
1380
1434
  // Skip routine continuation - don't block automatic continuation
1381
1435
  if (result.isRoutine) {
1382
1436
  logToFile("[auto-continue]", "Routine continuation detected, not blocking");
@@ -1385,15 +1439,21 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1385
1439
 
1386
1440
  // Create question in controller
1387
1441
  const questionKind = result.kind || "approval";
1388
- // The risk facts of the proposed action are derived from the
1389
- // whole message, not from the question sentence alone: the
1390
- // sentence often leaves out what the agent is really waiting
1391
- // for. They are recorded with the request: the autonomous
1392
- // decision is only as safe as these facts.
1442
+ // The risk is about the action that is proposed, not about the
1443
+ // whole message: a message that talks about many things
1444
+ // carries words that have nothing to do with the action that
1445
+ // is proposed. The action is extracted from the message, and
1446
+ // a prohibition ("do not delete anything") does not count as
1447
+ // a proposal.
1448
+ const proposedAction = extractProposedAction(
1449
+ result.contextText,
1450
+ result.questionText,
1451
+ );
1393
1452
  const riskFacts = classifyQuestionRisk({
1394
1453
  kind: questionKind,
1395
1454
  askType: result.askType,
1396
- text: result.contextText || result.questionText,
1455
+ text: result.questionText,
1456
+ proposedAction,
1397
1457
  });
1398
1458
  const question = pqController.createQuestion({
1399
1459
  text: result.questionText,
@@ -1416,21 +1476,30 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1416
1476
  logQuestionTransition(question.requestId, "detected", result.askType ?? questionKind);
1417
1477
 
1418
1478
  _lastNotifiedQuestion = result.questionText;
1419
- waitingForUserSince = new Date();
1420
1479
 
1421
1480
  // Use question.requestId as the jobId for callback matching
1422
1481
  const questionJobId = question.requestId;
1423
1482
 
1424
- // The status row counts down to the decision of the judge.
1425
- // The countdown is bound to this request, so a newer
1426
- // question replaces it.
1427
- startPendingCountdown(questionJobId);
1483
+ // The wait starts here. The controller owns the question,
1484
+ // the moment it was asked and the countdown, so the
1485
+ // deadline of the decision and the deadline of the
1486
+ // countdown are the same moment. A question that replaces
1487
+ // this one invalidates the evaluation of this one.
1488
+ waitLifecycle.begin({
1489
+ requestId: questionJobId,
1490
+ sessionId: _sessionId,
1491
+ kind: questionKind,
1492
+ askType: result.askType,
1493
+ text: result.questionText,
1494
+ contextText: result.contextText,
1495
+ alternatives: result.alternatives,
1496
+ });
1428
1497
 
1429
1498
  // Get task context for additional info
1430
1499
  const taskContext = await getTaskContext().catch(() => ({ total: 0, completed: 0, remaining: [] as string[] }));
1431
1500
 
1432
1501
  // Build rich context message
1433
- const waitMinutes = Math.round((Date.now() - waitingForUserSince!.getTime()) / 60000);
1502
+ const waitMinutes = Math.round(waitLifecycle.waitedMinutes());
1434
1503
  const taskInfo = taskContext.total > 0
1435
1504
  ? `Tasks: ${taskContext.completed}/${taskContext.total} done`
1436
1505
  : "No active tasks";
@@ -1584,7 +1653,7 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1584
1653
  }
1585
1654
  }
1586
1655
  lastUserMessage = new Date();
1587
- if (waitingForUserSince) {
1656
+ if (isWaitingForUser()) {
1588
1657
  // The user answered in Pi: the wait and the countdown of
1589
1658
  // the wait are over with it.
1590
1659
  clearWait();
@@ -1598,23 +1667,30 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1598
1667
 
1599
1668
  // Periodic check for auto-continue decision
1600
1669
 
1601
- const checkAndAutoContinue = async (source: "countdown" | "poll" = "poll") => {
1602
- // Prevent overlap if inference is already in progress
1603
- if (_inferenceInProgress) {
1604
- // A deadline that was blocked is armed again by the caller of
1605
- // the countdown, so the decision is not lost.
1606
- return;
1607
- }
1608
-
1609
- if (!waitingForUserSince) return;
1610
-
1611
- // The countdown owns the wait while it runs: the fallback poll
1612
- // only takes over when there is no countdown, so the decision is
1613
- // never started twice.
1614
- if (source === "poll" && pendingCountdown.active) return;
1615
-
1616
- // Capture session ID at check time for post-inference validation
1617
- const checkSessionId = _sessionId;
1670
+ /**
1671
+ * The evaluation of the pending question.
1672
+ *
1673
+ * The controller owns the lifecycle of the wait; this function is
1674
+ * the evaluation itself: it asks the judge once and returns the
1675
+ * result. The application of the outcome happens in the caller, so
1676
+ * a result that belongs to a question that is gone never reaches
1677
+ * the work.
1678
+ */
1679
+ const evaluatePendingQuestion = async (
1680
+ request: {
1681
+ requestId: string;
1682
+ sessionId: string;
1683
+ kind?: string;
1684
+ askType?: string;
1685
+ text?: string;
1686
+ contextText?: string;
1687
+ alternatives?: string[];
1688
+ },
1689
+ waitedMs: number,
1690
+ ): Promise<import("./packages/jev-judge/dist/wait-lifecycle.js").WaitEvaluation> => {
1691
+ // The one elapsed time: the wait that the controller measured
1692
+ // from the moment the question was asked.
1693
+ const waitMinutes = waitedMs / 60000;
1618
1694
  // Use same hash algorithm as detection
1619
1695
  const questionHash = _lastNotifiedQuestion
1620
1696
  ? Math.abs(_lastNotifiedQuestion.split("").reduce((a, c) => {
@@ -1623,13 +1699,8 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1623
1699
  }, 0)).toString(36)
1624
1700
  : "";
1625
1701
 
1626
- const waitMinutes = (Date.now() - waitingForUserSince.getTime()) / 60000;
1627
- // The judge is only asked once the question waited long enough.
1628
- if (!mod.isEligibleForDecision?.(waitMinutes, MIN_WAIT_MINUTES)) return;
1629
-
1630
1702
  // Update status to checking
1631
1703
  updateAutoContinueStatus("CHECKING", questionHash);
1632
-
1633
1704
  try {
1634
1705
  // Mark inference as in progress to prevent overlap
1635
1706
  _inferenceInProgress = true;
@@ -1674,10 +1745,20 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1674
1745
  if (taskContext.total === 0 && !hasPendingQuestion) {
1675
1746
  logToFile("[auto-continue]", "No tasks and no pending questions, skipping auto-continue check");
1676
1747
  _inferenceInProgress = false;
1677
- // The countdown is over: the fallback poll takes over the
1678
- // next attempt.
1679
- pendingCountdown.stop();
1680
- return;
1748
+ // There is nothing to decide about: the work has no task
1749
+ // and no question. The wait ends with it, and no decision
1750
+ // is made: a decision would claim that a human is
1751
+ // needed, and nobody is. The controller releases the
1752
+ // wait, so the result of this evaluation is discarded as
1753
+ // stale and the work is not paused.
1754
+ waitLifecycle.cancel();
1755
+ // The countdown is over with the wait.
1756
+ updateAutoContinueStatus("IDLE");
1757
+ return {
1758
+ outcome: "wait",
1759
+ reasoning: "there is no task and no pending question to decide about",
1760
+ policyApplied: "nothing-to-decide",
1761
+ };
1681
1762
  }
1682
1763
 
1683
1764
  // The question Jev has to decide about. Without it Jev only
@@ -1698,24 +1779,43 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1698
1779
  : classifyQuestionRisk({
1699
1780
  kind: pendingQuestion.kind,
1700
1781
  askType: pendingQuestion.askType,
1701
- text:
1702
- pendingQuestion.contextText ?? pendingQuestion.questionText,
1782
+ text: pendingQuestion.questionText,
1783
+ proposedAction: extractProposedAction(
1784
+ pendingQuestion.contextText,
1785
+ pendingQuestion.questionText,
1786
+ ),
1703
1787
  })
1704
1788
  : undefined;
1705
- const questionContext = pendingQuestion
1706
- ? {
1707
- requestId: pendingQuestion.requestId,
1708
- text: pendingQuestion.questionText,
1709
- kind: pendingQuestion.kind,
1710
- askType: pendingQuestion.askType,
1711
- alternatives: pendingQuestion.alternatives,
1712
- contextText: pendingQuestion.contextText,
1713
- requiresExplicitAuthorization: riskFacts?.requiresExplicitAuthorization,
1714
- destructive: riskFacts?.destructive,
1715
- external: riskFacts?.external,
1716
- reversible: riskFacts?.reversible,
1717
- }
1718
- : undefined;
1789
+ // The question of the request that was evaluated. The request
1790
+ // owns it: the evaluation belongs to that request, not to
1791
+ // whatever question happens to be current.
1792
+ const questionContext = {
1793
+ requestId: request.requestId,
1794
+ text: pendingQuestion?.questionText ?? request.text ?? "",
1795
+ kind: (pendingQuestion?.kind ?? request.kind ?? "approval") as
1796
+ | "routine"
1797
+ | "approval"
1798
+ | "choice"
1799
+ | "clarification"
1800
+ | "explicit",
1801
+ askType: (pendingQuestion?.askType ?? request.askType) as
1802
+ | "approval"
1803
+ | "choice"
1804
+ | "clarification"
1805
+ | "explicit_authorization"
1806
+ | "routine"
1807
+ | undefined,
1808
+ alternatives: request.alternatives ?? pendingQuestion?.alternatives,
1809
+ contextText: request.contextText ?? pendingQuestion?.contextText,
1810
+ proposedAction: extractProposedAction(
1811
+ request.contextText ?? pendingQuestion?.contextText,
1812
+ request.text ?? pendingQuestion?.questionText,
1813
+ ),
1814
+ requiresExplicitAuthorization: riskFacts?.requiresExplicitAuthorization,
1815
+ destructive: riskFacts?.destructive,
1816
+ external: riskFacts?.external,
1817
+ reversible: riskFacts?.reversible,
1818
+ };
1719
1819
 
1720
1820
  const decisionContext = {
1721
1821
  question: questionContext,
@@ -1733,7 +1833,7 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1733
1833
  ? `${pendingFinalTier.length} final tier(s) pending`
1734
1834
  : "no pending final tier",
1735
1835
  waitedMinutes: Math.round(waitMinutes),
1736
- deadlineMinutes: MAX_WAIT_MINUTES,
1836
+ deadlineMinutes: MIN_WAIT_MINUTES,
1737
1837
  lastUserActivity: lastUserMessage || undefined,
1738
1838
  };
1739
1839
 
@@ -1743,38 +1843,15 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1743
1843
  lastUserMessage || undefined,
1744
1844
  new Date(Date.now() - waitMinutes * 60000),
1745
1845
  decisionContext,
1846
+ // The wait is measured from the moment the question was
1847
+ // asked: the evaluation and the countdown see one time.
1848
+ { questionAskedAt: new Date(Date.now() - waitedMs) },
1746
1849
  );
1747
1850
 
1748
- logQuestionTransition(questionContext?.requestId, "eligible", `waited ${Math.round(waitMinutes)}m`);
1851
+ logQuestionTransition(request.requestId, "eligible", `waited ${Math.round(waitMinutes)}m`);
1749
1852
 
1750
1853
  const decision = await judge.decide(taskState);
1751
- logQuestionTransition(questionContext?.requestId, "jev-outcome", decision.outcome ?? decision.action);
1752
-
1753
- // Check session validity and user response before applying
1754
- if (checkSessionId !== _sessionId) {
1755
- // Session changed - cancel pending question
1756
- sharedState.pqController?.cancel("Session switched");
1757
- _inferenceInProgress = false;
1758
- updateAutoContinueStatus("IDLE");
1759
- return;
1760
- }
1761
-
1762
- if (!waitingForUserSince) {
1763
- _inferenceInProgress = false;
1764
- updateAutoContinueStatus("IDLE");
1765
- return;
1766
- }
1767
-
1768
- // Check if question was explicitly rejected - don't auto-continue after "Not yet"
1769
- if (sharedState.pqController?.isResolved()) {
1770
- const resolution = sharedState.pqController?.getResolution();
1771
- if (resolution === "no") {
1772
- logToFile("[auto-continue]", "Question was rejected - not auto-continuing");
1773
- _inferenceInProgress = false;
1774
- updateAutoContinueStatus("IDLE");
1775
- return;
1776
- }
1777
- }
1854
+ logQuestionTransition(request.requestId, "jev-outcome", decision.outcome ?? decision.action);
1778
1855
 
1779
1856
  // The typed outcome of the decision. The action is the
1780
1857
  // fallback for a judge that does not know the outcome yet.
@@ -1786,174 +1863,254 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1786
1863
  else outcome = "wait";
1787
1864
  }
1788
1865
 
1789
- if (outcome === "wait") {
1790
- // A wait decision is bounded: after the deadline the work
1791
- // pauses instead of waiting for a user who is not there.
1792
- // The question stays open: it is not closed with a Jev
1793
- // decision, so the next check can still decide about it.
1794
- logToFile(
1795
- "[auto-continue]",
1796
- `Jev decided to wait (${Math.round(waitMinutes)}m waited, deadline ${MAX_WAIT_MINUTES}m): ${logReasoning(decision.reasoning)}`,
1797
- );
1798
- logQuestionTransition(
1799
- questionContext?.requestId,
1800
- "wait",
1801
- decision.policyApplied ?? "retry",
1802
- );
1803
- if (waitMinutes >= MAX_WAIT_MINUTES) {
1804
- logToFile("[auto-continue]", "Decision deadline reached - pausing the work");
1805
- // The deadline is a terminal path: the pending question
1806
- // is closed, so the notification does not stay open
1807
- // with nobody waiting for it any more.
1808
- const expired = questionContext?.requestId
1809
- ? sharedState.pqController?.expireByTimeout?.(
1810
- questionContext.requestId,
1811
- "deadline-expired",
1812
- ) === true
1813
- : false;
1814
- logQuestionTransition(
1815
- questionContext?.requestId,
1816
- expired ? "expired" : "deadline",
1817
- "deadline-expired",
1818
- );
1819
- (sharedState.todoContinuationController as any)?.explicitPause?.();
1820
- if (questionContext?.requestId) {
1821
- _nc?.notify("Info", {
1822
- jobId: `expired-${questionContext.requestId}`,
1823
- requirement:
1824
- "The request expired: no answer was received before the decision deadline. The work is paused until you answer.",
1825
- }).catch((e) =>
1826
- logToFile("[Notification]", "Expiry notification failed:", String(e)),
1827
- );
1828
- }
1829
- // The deadline belongs to the captured question: a newer
1830
- // question keeps its own wait state.
1831
- if (waitBelongsToRequest(questionContext?.requestId)) {
1832
- // The request expired: the wait and the countdown
1833
- // of the wait are over with it.
1834
- clearWait();
1835
- updateAutoContinueStatus("IDLE");
1836
- }
1837
- } else {
1838
- // The request stays open: the countdown counts down to
1839
- // the next check, so the retry does not wait for the
1840
- // fallback poll.
1841
- if (questionContext?.requestId) {
1842
- startRecheckCountdown(questionContext.requestId);
1843
- } else {
1844
- updateAutoContinueStatus("WAITING");
1845
- }
1846
- }
1847
- } else {
1848
- // Close the question with the Jev decision. The buttons of
1849
- // that request ID become stale and no synthetic user
1850
- // answer is injected: nobody clicked anything.
1851
- //
1852
- // A failed close means the request is no longer pending: a
1853
- // human answered while Jev was still evaluating. The
1854
- // human answer wins, so the stale decision is discarded
1855
- // and no continuation steer is sent.
1856
- const closed = questionContext?.requestId
1857
- ? sharedState.pqController?.resolveByJev?.(
1858
- questionContext.requestId,
1859
- outcome,
1860
- decision.reasoning,
1861
- {
1862
- selectedOption: decision.selectedOption,
1863
- scope: decision.scope,
1864
- reasoning: decision.reasoning,
1865
- },
1866
- ) === true
1867
- : false;
1868
- const application = mod.decideOutcomeApplication(outcome, closed);
1869
-
1870
- if (application === "discard") {
1871
- logToFile(
1872
- "[auto-continue]",
1873
- "Question is no longer pending - discarding the stale Jev decision",
1874
- );
1875
- _inferenceInProgress = false;
1876
- // The wait state belongs to the captured question: a
1877
- // newer question keeps its own wait.
1878
- if (waitBelongsToRequest(questionContext?.requestId)) {
1879
- // The stale decision is discarded: the wait and
1880
- // the countdown of the wait are over with it.
1881
- clearWait();
1882
- updateAutoContinueStatus("IDLE");
1883
- } else {
1884
- logToFile(
1885
- "[auto-continue]",
1886
- "A newer question is active - keeping its wait state",
1887
- );
1888
- }
1889
- return;
1890
- }
1866
+ // The evaluation is done. The controller decides whether the
1867
+ // result still belongs to the question that waits: a result
1868
+ // of an answered or replaced question is discarded there.
1869
+ return {
1870
+ outcome,
1871
+ selectedOption: decision.selectedOption,
1872
+ scope: decision.scope,
1873
+ reasoning: decision.reasoning,
1874
+ policyApplied: decision.policyApplied,
1875
+ riskLevel: decision.riskLevel,
1876
+ error: decision.evaluationError,
1877
+ };
1878
+ } catch (error) {
1879
+ // The evaluation failed. That is an error, not a decision:
1880
+ // nothing was decided, the question stays open and the work
1881
+ // is not continued.
1882
+ _inferenceInProgress = false;
1883
+ logToFile("[auto-continue]", "The evaluation of the question failed:", oneLineError(error));
1884
+ return {
1885
+ outcome: "wait",
1886
+ reasoning: "",
1887
+ error: {
1888
+ kind: "provider",
1889
+ message: error instanceof Error ? error.message : String(error),
1890
+ },
1891
+ };
1892
+ }
1893
+ };
1891
1894
 
1892
- if (application === "pause") {
1893
- // Jev refused the proposed action. The question is
1894
- // closed and the work pauses: no continuation steer
1895
- // is sent, so the agent waits for a human.
1896
- logToFile(
1897
- "[auto-continue]",
1898
- `Question ${questionContext?.requestId} closed by Jev (reject) - pausing the work`,
1899
- );
1900
- (sharedState.todoContinuationController as any)?.explicitPause?.();
1901
- if (waitBelongsToRequest(questionContext?.requestId)) {
1902
- // The work pauses for a human: the wait and the
1903
- // countdown of the wait are over with it.
1904
- clearWait();
1905
- updateAutoContinueStatus("IDLE");
1906
- }
1907
- return;
1908
- }
1895
+ /**
1896
+ * Apply the decision of the judge.
1897
+ *
1898
+ * The decision belongs to the request that was evaluated: the
1899
+ * controller stamps that identity on the result, and the result is
1900
+ * applied only while it is the request that waits. The question
1901
+ * itself may have been answered in the meantime, and then the
1902
+ * decision is discarded.
1903
+ */
1904
+ const applyWaitDecision = async (
1905
+ evaluation: import("./packages/jev-judge/dist/wait-lifecycle.js").WaitEvaluation,
1906
+ ): Promise<void> => {
1907
+ // The decision belongs to the request it was evaluated for.
1908
+ //
1909
+ // The controller stamps that identity on the result. A decision
1910
+ // of a question that was answered, replaced or cancelled in the
1911
+ // meantime belongs to a question that is gone: it must not
1912
+ // resolve, continue, pause or clear anything. The question that
1913
+ // is current now is a different one and owns its own wait.
1914
+ if (!waitLifecycle.ownsEvaluation(evaluation)) {
1915
+ logToFile(
1916
+ "[auto-continue]",
1917
+ "The decision belongs to a question that is gone - discarding it",
1918
+ );
1919
+ return;
1920
+ }
1921
+ const outcome = evaluation.outcome;
1922
+ const requestId = evaluation.requestId;
1923
+ const waitMinutes = waitLifecycle.waitedMinutes();
1924
+ const pendingQuestion = sharedState.pqController?.getCurrentQuestion?.();
1925
+ const questionText = pendingQuestion?.questionText;
1926
+ const reasoning = evaluation.reasoning;
1927
+
1928
+ // Check if question was explicitly rejected - don't auto-continue after "Not yet"
1929
+ if (sharedState.pqController?.isResolved()) {
1930
+ const resolution = sharedState.pqController?.getResolution();
1931
+ if (resolution === "no") {
1932
+ logToFile("[auto-continue]", "Question was rejected - not auto-continuing");
1933
+ updateAutoContinueStatus("IDLE");
1934
+ return;
1935
+ }
1936
+ }
1909
1937
 
1938
+ if (outcome === "wait") {
1939
+ // The decision asks for a human. The work pauses: the
1940
+ // evaluation does not run again, and the question stays open
1941
+ // so the human can still answer it.
1942
+ logToFile(
1943
+ "[auto-continue]",
1944
+ `Jev needs a human (${Math.round(waitMinutes)}m waited): ${logReasoning(reasoning)}`,
1945
+ );
1946
+ logQuestionTransition(
1947
+ requestId,
1948
+ "wait",
1949
+ evaluation.policyApplied ?? "human-required",
1950
+ );
1951
+ (sharedState.todoContinuationController as any)?.explicitPause?.();
1952
+ // The wait is over: the work is paused until a human answers.
1953
+ clearWait();
1954
+ updateAutoContinueStatus("IDLE");
1955
+ return;
1956
+ }
1957
+
1958
+ // Close the question with the Jev decision. The buttons of
1959
+ // that request ID become stale and no synthetic user answer is
1960
+ // injected: nobody clicked anything.
1961
+ //
1962
+ // A failed close means the request is no longer pending: a
1963
+ // human answered while Jev was still evaluating. The human
1964
+ // answer wins, so the stale decision is discarded and no
1965
+ // continuation steer is sent.
1966
+ const closed = requestId
1967
+ ? sharedState.pqController?.resolveByJev?.(
1968
+ requestId,
1969
+ outcome,
1970
+ reasoning,
1971
+ {
1972
+ selectedOption: evaluation.selectedOption,
1973
+ scope: evaluation.scope,
1974
+ reasoning,
1975
+ },
1976
+ ) === true
1977
+ : false;
1978
+ const application = mod.decideOutcomeApplication(outcome, closed);
1979
+
1980
+ if (application === "discard") {
1981
+ logToFile(
1982
+ "[auto-continue]",
1983
+ "Question is no longer pending - discarding the stale Jev decision",
1984
+ );
1985
+ // The wait state belongs to the captured question: a
1986
+ // newer question keeps its own wait.
1987
+ if (waitBelongsToRequest(requestId)) {
1988
+ // The stale decision is discarded: the wait and
1989
+ // the countdown of the wait are over with it.
1990
+ clearWait();
1991
+ updateAutoContinueStatus("IDLE");
1992
+ } else {
1910
1993
  logToFile(
1911
1994
  "[auto-continue]",
1912
- `Question ${questionContext?.requestId} closed by Jev (${outcome})`,
1995
+ "A newer question is active - keeping its wait state",
1913
1996
  );
1914
- logQuestionTransition(questionContext?.requestId, "applied", outcome);
1915
-
1916
- // Update status to continuing
1917
- updateAutoContinueStatus("CONTINUING", questionHash);
1997
+ }
1998
+ return;
1999
+ }
1918
2000
 
1919
- // The steer names the selected option, the scope and the
1920
- // reasoning of the decision. A bare "continue with the
1921
- // remaining tasks" does not answer the question the
1922
- // agent asked, and it would pretend that the user
1923
- // answered.
1924
- const instruction = autonomy.buildAutonomyInstruction({
1925
- outcome,
1926
- questionText: questionContext?.text,
1927
- selectedOption: decision.selectedOption,
1928
- scope: decision.scope,
1929
- reasoning: decision.reasoning,
1930
- riskLevel: decision.riskLevel,
1931
- waitedMinutes: Math.round(waitMinutes),
1932
- deadlineMinutes: MAX_WAIT_MINUTES,
1933
- });
1934
- pi.sendUserMessage(instruction, { deliverAs: "steer" });
1935
- // The question is closed: the wait and the countdown of
1936
- // the wait are over with it.
2001
+ if (application === "pause") {
2002
+ // Jev refused the proposed action. The question is
2003
+ // closed and the work pauses: no continuation steer
2004
+ // is sent, so the agent waits for a human.
2005
+ logToFile(
2006
+ "[auto-continue]",
2007
+ `Question ${requestId} closed by Jev (reject) - pausing the work`,
2008
+ );
2009
+ (sharedState.todoContinuationController as any)?.explicitPause?.();
2010
+ if (waitBelongsToRequest(requestId)) {
2011
+ // The work pauses for a human: the wait and the
2012
+ // countdown of the wait are over with it.
1937
2013
  clearWait();
1938
-
1939
- // The status stays "RUN" until the turn that the steer
1940
- // started has settled. A timer would clear it while the
1941
- // agent is still working, and the status would claim
1942
- // that nothing runs any more.
1943
- _continuation.begin();
2014
+ updateAutoContinueStatus("IDLE");
1944
2015
  }
2016
+ return;
2017
+ }
2018
+
2019
+ logToFile(
2020
+ "[auto-continue]",
2021
+ `Question ${requestId} closed by Jev (${outcome})`,
2022
+ );
2023
+ logQuestionTransition(requestId, "applied", outcome);
2024
+
2025
+ // Update status to continuing
2026
+ updateAutoContinueStatus("CONTINUING", questionHash());
2027
+
2028
+ // The steer names the selected option, the scope and the
2029
+ // reasoning of the decision. A bare "continue with the
2030
+ // remaining tasks" does not answer the question the
2031
+ // agent asked, and it would pretend that the user
2032
+ // answered.
2033
+ const instruction = autonomy.buildAutonomyInstruction({
2034
+ outcome,
2035
+ questionText,
2036
+ selectedOption: evaluation.selectedOption,
2037
+ scope: evaluation.scope,
2038
+ reasoning,
2039
+ riskLevel: evaluation.riskLevel,
2040
+ waitedMinutes: Math.round(waitMinutes),
2041
+ deadlineMinutes: MIN_WAIT_MINUTES,
2042
+ });
2043
+ pi.sendUserMessage(instruction, { deliverAs: "steer" });
2044
+ // The question is closed: the wait and the countdown of
2045
+ // the wait are over with it.
2046
+ clearWait();
2047
+
2048
+ // The status stays "RUN" until the turn that the steer
2049
+ // started has settled. A timer would clear it while the
2050
+ // agent is still working, and the status would claim
2051
+ // that nothing runs any more.
2052
+ _continuation.begin();
2053
+ };
2054
+
2055
+ /**
2056
+ * The decision of the pending question.
2057
+ *
2058
+ * The controller owns the lifecycle: it knows whether the wait is
2059
+ * due, it runs the evaluation exactly once and it discards a
2060
+ * result that belongs to a question that is gone.
2061
+ */
2062
+ const checkAndAutoContinue = async (source: "countdown" | "poll" = "poll") => {
2063
+ // Prevent overlap if inference is already in progress
2064
+ if (_inferenceInProgress) {
2065
+ // A deadline that was blocked is armed again by the caller of
2066
+ // the countdown, so the decision is not lost.
2067
+ return;
2068
+ }
2069
+
2070
+ // The countdown owns the wait while it counts down: the fallback
2071
+ // poll only takes over after the countdown fired, so the decision
2072
+ // is never started twice and a blocked deadline is not lost.
2073
+ if (source === "poll" && pendingCountdown.active && !pendingCountdown.fired) return;
2074
+
2075
+ const result = await waitLifecycle.evaluateDue();
2076
+ if (!result.applied || !result.evaluation) {
2077
+ // Nothing was decided: the wait is not due yet, the
2078
+ // evaluation was stale, or the wait is already in a state
2079
+ // that does not decide.
2080
+ //
2081
+ // The attempt is over either way: the guard against a
2082
+ // second, overlapping evaluation is released, so a later
2083
+ // question can still be decided.
1945
2084
  _inferenceInProgress = false;
1946
- } catch {
2085
+ if (result.discardReason === "other-session") {
2086
+ // The session changed: the question of the old session
2087
+ // is closed with it.
2088
+ sharedState.pqController?.cancel("Session switched");
2089
+ waitLifecycle.cancel();
2090
+ updateAutoContinueStatus("IDLE");
2091
+ }
2092
+ return;
2093
+ }
2094
+
2095
+ if (result.state === "evaluation_error") {
2096
+ // The provider failed. Nothing was decided: the question
2097
+ // stays open for the human and the work is not continued.
2098
+ const message = result.evaluation.error?.message ?? "the evaluation failed";
2099
+ logToFile("[auto-continue]", "The evaluation of the question failed:", message);
1947
2100
  _inferenceInProgress = false;
1948
- // The countdown is over: the fallback poll takes over the next
1949
- // attempt.
1950
- pendingCountdown.stop();
1951
2101
  updateAutoContinueStatus("ERROR");
1952
2102
  addHarnessMessage("Jev", "auto-continue evaluation failed", "err", [
1953
2103
  "How to fix: Check logs at /tmp/pi-harness.log for API errors",
1954
2104
  "Ensure TYPESAFE_API_KEY is valid, then restart.",
1955
2105
  ]);
2106
+ return;
1956
2107
  }
2108
+
2109
+ await applyWaitDecision(result.evaluation);
2110
+ // The decision was applied or discarded. The guard against a
2111
+ // second, overlapping evaluation is released here, so a
2112
+ // decision that was discarded does not block the next question.
2113
+ _inferenceInProgress = false;
1957
2114
  };
1958
2115
 
1959
2116
  // --- todo continuation: Retain one controller per session ----------
@@ -2205,7 +2362,7 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2205
2362
  }
2206
2363
 
2207
2364
  // Don't continue if user is waiting for response
2208
- if (waitingForUserSince) {
2365
+ if (isWaitingForUser()) {
2209
2366
  todoContinuationController?.clearQueue();
2210
2367
  return;
2211
2368
  }