pi-harness-runtime 1.1.514 → 1.1.516

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 (127) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/harness/approval-decision-store.ts +94 -0
  3. package/harness/delegated-approval-runtime.ts +375 -0
  4. package/harness/delegated-approval-types.ts +179 -0
  5. package/harness/delegation-store.ts +108 -0
  6. package/harness/exploration-checkpoint-tool.ts +216 -0
  7. package/harness/exploration-guard-runtime.ts +23 -0
  8. package/harness/jev-rejection-escalation.ts +248 -0
  9. package/harness/plan-handoff-bridge.ts +27 -6
  10. package/harness/plan-handoff-receiver.ts +258 -0
  11. package/harness/plan-handoff-registration.ts +28 -13
  12. package/index.ts +516 -23
  13. package/package.json +1 -4
  14. package/packages/agent-policy/package.json +1 -1
  15. package/packages/auth/package.json +1 -1
  16. package/packages/autonomous-runtime/package.json +1 -1
  17. package/packages/checkpoint/package.json +1 -1
  18. package/packages/clipboard/package.json +1 -1
  19. package/packages/codex-watcher/package.json +1 -1
  20. package/packages/config-capture/package.json +1 -1
  21. package/packages/contracts/package.json +1 -1
  22. package/packages/cookie-sanitizer/dist/atomic-write.d.ts +16 -0
  23. package/packages/cookie-sanitizer/dist/atomic-write.d.ts.map +1 -1
  24. package/packages/cookie-sanitizer/dist/atomic-write.js +28 -0
  25. package/packages/cookie-sanitizer/dist/atomic-write.js.map +1 -1
  26. package/packages/cookie-sanitizer/dist/index.d.ts +1 -1
  27. package/packages/cookie-sanitizer/dist/index.d.ts.map +1 -1
  28. package/packages/cookie-sanitizer/dist/index.js +1 -1
  29. package/packages/cookie-sanitizer/dist/index.js.map +1 -1
  30. package/packages/cookie-sanitizer/package.json +1 -1
  31. package/packages/cookie-sanitizer/src/atomic-write.ts +29 -0
  32. package/packages/cookie-sanitizer/src/index.ts +1 -0
  33. package/packages/evaluation-engine/package.json +1 -1
  34. package/packages/event-bus/package.json +1 -1
  35. package/packages/event-store/package.json +1 -1
  36. package/packages/experience-replay/package.json +1 -1
  37. package/packages/exploration-guard/dist/checkpoint.d.ts +12 -0
  38. package/packages/exploration-guard/dist/checkpoint.d.ts.map +1 -1
  39. package/packages/exploration-guard/dist/checkpoint.js +33 -1
  40. package/packages/exploration-guard/dist/checkpoint.js.map +1 -1
  41. package/packages/exploration-guard/dist/observation.d.ts +7 -0
  42. package/packages/exploration-guard/dist/observation.d.ts.map +1 -1
  43. package/packages/exploration-guard/dist/observation.js +90 -27
  44. package/packages/exploration-guard/dist/observation.js.map +1 -1
  45. package/packages/exploration-guard/dist/tracker.d.ts.map +1 -1
  46. package/packages/exploration-guard/dist/tracker.js +3 -1
  47. package/packages/exploration-guard/dist/tracker.js.map +1 -1
  48. package/packages/exploration-guard/dist/types.d.ts +1 -1
  49. package/packages/exploration-guard/dist/types.d.ts.map +1 -1
  50. package/packages/exploration-guard/package.json +1 -1
  51. package/packages/exploration-guard/src/checkpoint.ts +44 -1
  52. package/packages/exploration-guard/src/observation.ts +120 -26
  53. package/packages/exploration-guard/src/tracker.ts +3 -1
  54. package/packages/exploration-guard/src/types.ts +1 -1
  55. package/packages/file-copy-helper/package.json +1 -1
  56. package/packages/intent-analyzer/package.json +1 -1
  57. package/packages/jev-judge/dist/continuation-controller.d.ts +43 -0
  58. package/packages/jev-judge/dist/continuation-controller.d.ts.map +1 -1
  59. package/packages/jev-judge/dist/continuation-controller.js +54 -7
  60. package/packages/jev-judge/dist/continuation-controller.js.map +1 -1
  61. package/packages/jev-judge/package.json +1 -1
  62. package/packages/jev-judge/src/continuation-controller.ts +89 -7
  63. package/packages/learning-engine/package.json +1 -1
  64. package/packages/logging/package.json +1 -1
  65. package/packages/memory-engine/package.json +1 -1
  66. package/packages/notification/dist/adapters/telegram-adapter.d.ts.map +1 -1
  67. package/packages/notification/dist/adapters/telegram-adapter.js +1 -0
  68. package/packages/notification/dist/adapters/telegram-adapter.js.map +1 -1
  69. package/packages/notification/dist/notification-center.d.ts.map +1 -1
  70. package/packages/notification/dist/notification-center.js +7 -0
  71. package/packages/notification/dist/notification-center.js.map +1 -1
  72. package/packages/notification/dist/notification-policy.d.ts.map +1 -1
  73. package/packages/notification/dist/notification-policy.js +6 -0
  74. package/packages/notification/dist/notification-policy.js.map +1 -1
  75. package/packages/notification/dist/types.d.ts +9 -1
  76. package/packages/notification/dist/types.d.ts.map +1 -1
  77. package/packages/notification/package.json +1 -1
  78. package/packages/notification/src/adapters/telegram-adapter.ts +1 -0
  79. package/packages/notification/src/notification-center.ts +7 -0
  80. package/packages/notification/src/notification-policy.ts +6 -0
  81. package/packages/notification/src/types.ts +8 -0
  82. package/packages/paperclip-integration/package.json +1 -1
  83. package/packages/performance-optimizer/package.json +1 -1
  84. package/packages/plan-handoff/dist/mailbox.d.ts +7 -0
  85. package/packages/plan-handoff/dist/mailbox.d.ts.map +1 -1
  86. package/packages/plan-handoff/dist/mailbox.js +9 -0
  87. package/packages/plan-handoff/dist/mailbox.js.map +1 -1
  88. package/packages/plan-handoff/package.json +1 -1
  89. package/packages/plan-handoff/src/mailbox.ts +12 -0
  90. package/packages/privilege-broker/package.json +1 -1
  91. package/packages/prompt-compiler/package.json +1 -1
  92. package/packages/providers/package.json +1 -1
  93. package/packages/qdrant-skills/package.json +1 -1
  94. package/packages/quota-manager/package.json +1 -1
  95. package/packages/relay/package.json +1 -1
  96. package/packages/skill-mcp-client/package.json +1 -1
  97. package/packages/skills/package.json +1 -1
  98. package/packages/todo-bd-sync/package.json +1 -1
  99. package/packages/token-estimation/package.json +1 -1
  100. package/packages/tooling-preference/package.json +1 -1
  101. package/packages/trajectory/package.json +1 -1
  102. package/packages/tui/package.json +1 -1
  103. package/packages/two-phase-review/package.json +1 -1
  104. package/packages/types/package.json +1 -1
  105. package/packages/webmcp-tester/package.json +1 -1
  106. package/packages/wiki/package.json +1 -1
  107. package/packages/write-review/package.json +1 -1
  108. package/prompts/slash-commands.md +0 -2
  109. package/packages/knowledge-retrieval/dist/index.d.ts +0 -8
  110. package/packages/knowledge-retrieval/dist/index.d.ts.map +0 -1
  111. package/packages/knowledge-retrieval/dist/index.js +0 -7
  112. package/packages/knowledge-retrieval/dist/index.js.map +0 -1
  113. package/packages/knowledge-retrieval/dist/mcp-client.d.ts +0 -61
  114. package/packages/knowledge-retrieval/dist/mcp-client.d.ts.map +0 -1
  115. package/packages/knowledge-retrieval/dist/mcp-client.js +0 -131
  116. package/packages/knowledge-retrieval/dist/mcp-client.js.map +0 -1
  117. package/packages/knowledge-retrieval/dist/types.d.ts +0 -105
  118. package/packages/knowledge-retrieval/dist/types.d.ts.map +0 -1
  119. package/packages/knowledge-retrieval/dist/types.js +0 -7
  120. package/packages/knowledge-retrieval/dist/types.js.map +0 -1
  121. package/packages/knowledge-retrieval/package.json +0 -22
  122. package/packages/knowledge-retrieval/src/index.ts +0 -18
  123. package/packages/knowledge-retrieval/src/mcp-client.ts +0 -211
  124. package/packages/knowledge-retrieval/src/types.ts +0 -112
  125. package/prompts/tencentdb-connect.md +0 -35
  126. package/prompts/tencentdb-setup.md +0 -101
  127. package/prompts/tencentdb.md +0 -88
package/index.ts CHANGED
@@ -38,11 +38,25 @@ import {
38
38
  type PlanHandoffAgent,
39
39
  } from "./harness/plan-handoff-registration.ts";
40
40
  import { deliverPlanToWorkspace } from "./harness/plan-handoff-delivery.ts";
41
+ import {
42
+ planDeliveryText,
43
+ startPlanReceiver,
44
+ type PlanReceiver,
45
+ } from "./harness/plan-handoff-receiver.ts";
41
46
  import {
42
47
  offerRecipientSelection,
43
48
  resolveRecipientSelection,
44
49
  } from "./harness/plan-handoff-recipient-selection.ts";
45
50
  import { ExplorationGuardRuntime } from "./harness/exploration-guard-runtime.ts";
51
+ import {
52
+ JevRejectionEscalationRuntime,
53
+ } from "./harness/jev-rejection-escalation.ts";
54
+ import { DelegatedApprovalRuntime } from "./harness/delegated-approval-runtime.ts";
55
+ import { DelegationStore } from "./harness/delegation-store.ts";
56
+ import { ApprovalDecisionStore } from "./harness/approval-decision-store.ts";
57
+ import { operationKindFor } from "./harness/delegated-approval-types.ts";
58
+ import type { NotificationResult } from "./packages/notification/src/types.ts";
59
+ import { registerExplorationCheckpointTool } from "./harness/exploration-checkpoint-tool.ts";
46
60
  import {
47
61
  describeCandidates,
48
62
  type AgentRegistration,
@@ -178,6 +192,7 @@ import { parseMiniMaxQuotaText } from "./harness/e2e/minimax-quota-parser.js";
178
192
  import {
179
193
  CookieWatcher,
180
194
  DEFAULT_DROP_DIR as COOKIE_DROP_DIR,
195
+ atomicWriteFileSync,
181
196
  inspectCookieSource,
182
197
  } from "./packages/cookie-sanitizer/src/index.ts";
183
198
  import {
@@ -628,6 +643,16 @@ let activeExtensionContext: ExtensionContext | null = null;
628
643
  */
629
644
  let planHandoffAgent: PlanHandoffAgent | null = null;
630
645
 
646
+ /**
647
+ * The receiver of the plans of this instance.
648
+ *
649
+ * The receiver reads the mailbox of this instance and hands a plan that is
650
+ * addressed to it to the session. Without it a plan that was routed to
651
+ * this instance would stay in the mailbox, and the instance that sent the
652
+ * plan would execute it instead.
653
+ */
654
+ let planReceiver: PlanReceiver | null = null;
655
+
631
656
  /**
632
657
  * The guard of the exploration of the running request.
633
658
  *
@@ -979,6 +1004,27 @@ const sharedState = {
979
1004
  * the human twice about the same backlog.
980
1005
  */
981
1006
  scopeProposedFor: null as number | null,
1007
+ /**
1008
+ * The runtime of the escalation of a refusal of the judge.
1009
+ *
1010
+ * A refusal of the judge is asked of the human with working buttons,
1011
+ * so the work stays blocked until the human answers.
1012
+ */
1013
+ jevRejectionEscalation: null as JevRejectionEscalationRuntime | null,
1014
+ /**
1015
+ * The runtime of the delegated timeout.
1016
+ *
1017
+ * The deadline of a question is not an answer: the work continues only
1018
+ * when the user delegated that outcome in advance.
1019
+ */
1020
+ delegatedApproval: null as DelegatedApprovalRuntime | null,
1021
+ /**
1022
+ * The resume of the delegated timeout.
1023
+ *
1024
+ * It is set where the executor of the automatic resumes lives, so the
1025
+ * runtime does not depend on the order of the setup.
1026
+ */
1027
+ delegatedResume: null as null | (() => void),
982
1028
  };
983
1029
 
984
1030
  /**
@@ -1194,6 +1240,41 @@ function applyChannelApproval(
1194
1240
  return false;
1195
1241
  }
1196
1242
 
1243
+ // An escalation of a refusal of the judge is not a question of the
1244
+ // work either: the answer decides the action that the judge refused.
1245
+ // The work stays blocked until the human answers, so the answer does
1246
+ // not steer a message into the conversation.
1247
+ const escalation = sharedState.jevRejectionEscalation?.forQuestion(requestId);
1248
+ if (escalation) {
1249
+ const outcome = action === "approve" ? ("yes" as const) : ("no" as const);
1250
+ const result = controller.applyApproval(action, requestId, channel, {
1251
+ notifyUser: false,
1252
+ });
1253
+ if (!result?.applied) {
1254
+ logToFile(
1255
+ "[Approval]",
1256
+ `Stale or duplicate ${channel} click for ${requestId}: ${result?.reason ?? "ignored"}`,
1257
+ );
1258
+ return false;
1259
+ }
1260
+ logToFile("[Approval]", `${channel} decision '${action}' applied to ${requestId}`);
1261
+ logQuestionTransition(requestId, "answered", `${channel}:${action}`);
1262
+ // The question is answered, so the wait is over. The state of the
1263
+ // session says so, and the countdown of the question is over with
1264
+ // it.
1265
+ sharedState.cancelWait?.();
1266
+ sharedState.updateAutoContinueStatus?.("IDLE");
1267
+ sharedState.pendingCountdown?.stop();
1268
+ if (!sharedState.jevRejectionEscalation?.answer(requestId, outcome)) {
1269
+ logToFile(
1270
+ "[Approval]",
1271
+ `The escalation ${requestId} was answered already - the answer is stale`,
1272
+ );
1273
+ return false;
1274
+ }
1275
+ return true;
1276
+ }
1277
+
1197
1278
  // A question of a scope proposal is not a question of the work of the
1198
1279
  // request: it asks whether the backlog may follow. The answer decides
1199
1280
  // the proposal, and the work of the request stays what it was.
@@ -1251,6 +1332,17 @@ function applyChannelApproval(
1251
1332
  // The countdown of the answered question is over with it.
1252
1333
  sharedState.pendingCountdown?.stop();
1253
1334
 
1335
+ // A delegated question was answered by the human, and its deadline
1336
+ // must not decide anything any more: the answer of the human wins
1337
+ // over the timeout.
1338
+ const delegated = sharedState.delegatedApproval?.get(requestId);
1339
+ if (delegated) {
1340
+ sharedState.delegatedApproval?.answer(
1341
+ requestId,
1342
+ result.resolution === "yes" ? "yes" : "no",
1343
+ );
1344
+ }
1345
+
1254
1346
  if (result.resolution === "yes") {
1255
1347
  (sharedState.todoContinuationController as any)?.resume?.();
1256
1348
  } else {
@@ -2269,6 +2361,20 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2269
2361
  },
2270
2362
  onDeadline: (requestId: string) => {
2271
2363
  logToFile("[auto-continue]", "The decision deadline was reached:", requestId);
2364
+ // A delegated question is decided by the delegation, not by
2365
+ // the judge: the deadline continues the work under the
2366
+ // configured default of the user, and the judge is not
2367
+ // asked a question that already has its answer.
2368
+ const delegated = sharedState.delegatedApproval?.get(requestId);
2369
+ if (delegated) {
2370
+ logToFile(
2371
+ "[auto-continue]",
2372
+ "The deadline of the delegated question was reached:",
2373
+ requestId,
2374
+ );
2375
+ sharedState.delegatedApproval?.expire(requestId);
2376
+ return;
2377
+ }
2272
2378
  checkAndAutoContinue("countdown")
2273
2379
  .then(() => {
2274
2380
  // The decision did not start: another one was still in
@@ -2336,6 +2442,119 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2336
2442
  });
2337
2443
  sharedState.pendingCountdown = pendingCountdown;
2338
2444
 
2445
+ // The escalation of a refusal of the judge: the human is asked with
2446
+ // working [Yes] / [No] buttons, and the work stays blocked until
2447
+ // the human decides.
2448
+ sharedState.jevRejectionEscalation = new JevRejectionEscalationRuntime({
2449
+ registerQuestion: (context, text) => {
2450
+ const question = pqController.createQuestion({
2451
+ text,
2452
+ sessionId: _sessionId,
2453
+ workspacePath: _piSessionCwd || "/",
2454
+ jobId: context.originalRequestId,
2455
+ kind: "approval",
2456
+ askType: "approval",
2457
+ contextText: text,
2458
+ // The escalation is asked after the judge refused: it
2459
+ // waits for the human and not for a decision of the
2460
+ // request.
2461
+ relevance: "final-request",
2462
+ risk: {
2463
+ requiresExplicitAuthorization: true,
2464
+ destructive: false,
2465
+ reversible: true,
2466
+ external: false,
2467
+ },
2468
+ });
2469
+ return question.requestId;
2470
+ },
2471
+ deliver: async (questionId, text) => {
2472
+ const results = await _nc?.notifyWithApproval(
2473
+ "JevRejectedAction",
2474
+ {
2475
+ jobId: questionId,
2476
+ questionId,
2477
+ questionKind: "approval",
2478
+ requirement: text,
2479
+ },
2480
+ // The buttons answer the action proposal, not the
2481
+ // recommendation of the judge.
2482
+ { approveLabel: "Yes", rejectLabel: "No" },
2483
+ );
2484
+ return ((results ?? []) as NotificationResult[]).map((result) => ({
2485
+ success: result.success,
2486
+ channel: result.channel,
2487
+ error: result.error,
2488
+ }));
2489
+ },
2490
+ onApproved: (state) => {
2491
+ logToFile(
2492
+ "[Approval]",
2493
+ `The human approved the action of ${state.questionId} - the work resumes once`,
2494
+ );
2495
+ // The resume continues the work of the request. The action
2496
+ // itself still goes through the checks of the repository:
2497
+ // an approval of the human is not a passed validation.
2498
+ (sharedState.todoContinuationController as any)?.resume?.();
2499
+ },
2500
+ onRejected: (state) => {
2501
+ logToFile(
2502
+ "[Approval]",
2503
+ `The human rejected the action of ${state.questionId} - the action stays blocked`,
2504
+ );
2505
+ (sharedState.todoContinuationController as any)?.explicitPause?.();
2506
+ },
2507
+ log: (message) => logToFile("[auto-continue]", message),
2508
+ });
2509
+
2510
+ // The delegations of the user: the deadline of a question is not an
2511
+ // answer. The work continues at the deadline only when the user
2512
+ // delegated that outcome in advance, and only for the kinds of
2513
+ // operation the delegation names.
2514
+ sharedState.delegatedApproval = new DelegatedApprovalRuntime({
2515
+ now: () => Date.now(),
2516
+ delegations: new DelegationStore(
2517
+ join(homedir(), ".pi-harness-runtime"),
2518
+ ),
2519
+ decisions: new ApprovalDecisionStore(
2520
+ join(homedir(), ".pi-harness-runtime"),
2521
+ ),
2522
+ deliver: async () => ({ delivered: true, failures: [] }),
2523
+ resume: (request, decision) => {
2524
+ logToFile(
2525
+ "[auto-continue]",
2526
+ `The deadline of ${request.requestId} passed under the delegation ${
2527
+ decision.delegationId ?? "unknown"
2528
+ } - one resume is queued`,
2529
+ );
2530
+ // The user is told that the automatic continuation used the
2531
+ // configured default: a silent continuation would look
2532
+ // like a decision of the judge.
2533
+ void _nc
2534
+ ?.notify("Info", {
2535
+ jobId: `delegated-timeout-${request.requestId}`,
2536
+ requirement: `The wait ended. The automatic continuation used your configured default (${
2537
+ decision.delegationId ?? "delegation"
2538
+ }): ${request.operation}.`,
2539
+ })
2540
+ .catch(() => {
2541
+ // The report is best effort: the continuation itself
2542
+ // does not depend on it.
2543
+ });
2544
+ sharedState.delegatedResume?.();
2545
+ },
2546
+ active: (request) => {
2547
+ const current = sharedState.pqController?.getCurrentQuestion?.();
2548
+ if (!current) return false;
2549
+ if (current.requestId !== request.requestId) return false;
2550
+ return current.state === "pending" || current.state === "evaluating";
2551
+ },
2552
+ paused: () =>
2553
+ (sharedState.todoContinuationController as any)?.isExplicitlyPaused?.() ===
2554
+ true,
2555
+ log: (message) => logToFile("[auto-continue]", message),
2556
+ });
2557
+
2339
2558
  // Wire shared state for callback handlers
2340
2559
  sharedState.cancelWait = () => {
2341
2560
  waitLifecycle.cancel();
@@ -2467,6 +2686,10 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2467
2686
  planHandoffAgent.stop();
2468
2687
  planHandoffAgent = null;
2469
2688
  }
2689
+ if (planReceiver) {
2690
+ planReceiver.stop();
2691
+ planReceiver = null;
2692
+ }
2470
2693
  if (_piSessionId) {
2471
2694
  startExplorationGuard(_piSessionId);
2472
2695
  try {
@@ -2474,6 +2697,23 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2474
2697
  sessionId: _piSessionId,
2475
2698
  modelLabel: ctx.model?.id,
2476
2699
  });
2700
+ // The receiver reads the mailbox of this instance: a plan
2701
+ // that was routed to this instance is handed to this
2702
+ // session, and to no other session.
2703
+ planReceiver = startPlanReceiver({
2704
+ registration: planHandoffAgent.registration,
2705
+ deliver: async (message) => {
2706
+ await pi.sendUserMessage(planDeliveryText(message), {
2707
+ deliverAs: "steer",
2708
+ });
2709
+ },
2710
+ // In manual mode the human decides: the plan waits in
2711
+ // the mailbox instead of being handed over.
2712
+ hold: (message) =>
2713
+ process.env.CODEX_MANUAL_MODE === "true" &&
2714
+ message.sender.agentId === "codex",
2715
+ });
2716
+ planReceiver.start();
2477
2717
  } catch (error) {
2478
2718
  logToFile(
2479
2719
  "[plan-handoff]",
@@ -2509,6 +2749,10 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2509
2749
  planHandoffAgent.stop();
2510
2750
  planHandoffAgent = null;
2511
2751
  }
2752
+ if (planReceiver) {
2753
+ planReceiver.stop();
2754
+ planReceiver = null;
2755
+ }
2512
2756
 
2513
2757
  // Cancel the auto-continue interval
2514
2758
  if (autoContinueTimer) {
@@ -2839,10 +3083,28 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2839
3083
  // pending question and every click would be reported stale.
2840
3084
  // A choice question shows its alternatives: the human has to
2841
3085
  // see what the agent is choosing between.
2842
- const requirement = result.alternatives && result.alternatives.length >= 2
3086
+ const options = result.alternatives && result.alternatives.length >= 2
2843
3087
  ? `${result.questionText}\n\nOptions:\n${result.alternatives.map((alternative, index) => `${index + 1}. ${alternative}`).join("\n")}`
2844
3088
  : result.questionText;
2845
- _nc?.notifyWithApproval("WaitingForUserInput", {
3089
+ // A delegation of the user may cover the operation of this
3090
+ // question. The human is then told what happens without an
3091
+ // answer, and the deadline is watched for that decision.
3092
+ const delegatedKind = operationKindFor(
3093
+ questionAction ?? result.questionText,
3094
+ );
3095
+ const delegation = delegatedKind
3096
+ ? sharedState.delegatedApproval?.delegationFor({
3097
+ kind: delegatedKind,
3098
+ workspace: _piSessionCwd || "/",
3099
+ })
3100
+ : undefined;
3101
+ const delegatedNotice = delegation
3102
+ ? `If you do not answer within ${MIN_WAIT_MINUTES} minutes, I will continue under your configured authorization (${delegation.id}).`
3103
+ : undefined;
3104
+ const requirement = delegatedNotice
3105
+ ? `${options}\n\n${delegatedNotice}`
3106
+ : options;
3107
+ const notified = _nc?.notifyWithApproval("WaitingForUserInput", {
2846
3108
  jobId: questionJobId,
2847
3109
  questionId: questionJobId,
2848
3110
  questionKind: question.kind,
@@ -2850,7 +3112,38 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2850
3112
  }, {
2851
3113
  approveLabel: "Continue",
2852
3114
  rejectLabel: "Not yet",
2853
- }).catch((e) => logToFile("[Notification]", "notifyWithApproval failed:", String(e)));
3115
+ });
3116
+ if (delegation && delegatedKind) {
3117
+ // The window of a delegated question starts with the
3118
+ // delivery: a question that nobody was told about must
3119
+ // not consume the opportunity of the human to answer.
3120
+ const delivery = ((await notified?.catch((e) => {
3121
+ logToFile("[Notification]", "notifyWithApproval failed:", String(e));
3122
+ return [] as NotificationResult[];
3123
+ })) ?? []) as NotificationResult[];
3124
+ await sharedState.delegatedApproval?.open(
3125
+ {
3126
+ requestId: questionJobId,
3127
+ workspace: _piSessionCwd || "/",
3128
+ sessionId: _sessionId,
3129
+ generation: requestScopeTracker.generation,
3130
+ kind: delegatedKind,
3131
+ operation: questionAction ?? result.questionText,
3132
+ blocked: [questionAction ?? result.questionText],
3133
+ deadlineAt: Date.now() + MIN_WAIT_MINUTES * 60_000,
3134
+ },
3135
+ {
3136
+ delivered: delivery.some((entry) => entry.success),
3137
+ failures: delivery
3138
+ .filter((entry) => !entry.success)
3139
+ .map((entry) => entry.channel),
3140
+ },
3141
+ );
3142
+ } else {
3143
+ void notified?.catch((e) =>
3144
+ logToFile("[Notification]", "notifyWithApproval failed:", String(e)),
3145
+ );
3146
+ }
2854
3147
  logQuestionTransition(questionJobId, "notified", "waiting-for-user");
2855
3148
 
2856
3149
  // Also send context info as a follow-up message (not in error field)
@@ -3257,6 +3550,63 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3257
3550
  }
3258
3551
  };
3259
3552
 
3553
+ /**
3554
+ * Ask the human about the refusal of the judge.
3555
+ *
3556
+ * The refusal of the judge is a recommendation, and the human
3557
+ * decides with the buttons of the escalation. When no channel
3558
+ * accepts the message, the work stays visibly blocked and the
3559
+ * harness never claims that the human was notified.
3560
+ */
3561
+ const escalateJevRejection = async (input: {
3562
+ originalRequestId: string;
3563
+ action: string;
3564
+ reason: string;
3565
+ }): Promise<void> => {
3566
+ const runtime = sharedState.jevRejectionEscalation;
3567
+ if (!runtime) {
3568
+ logToFile(
3569
+ "[auto-continue]",
3570
+ "The escalation runtime is not ready - the work stays blocked",
3571
+ );
3572
+ return;
3573
+ }
3574
+ try {
3575
+ // The work that remains is named in the message: the human
3576
+ // has to know what stays blocked and what may continue.
3577
+ const read = await requestScopeTracker.read();
3578
+ const open = (read.items ?? [])
3579
+ .filter((item) => item.status !== "completed")
3580
+ .map((item) => item.subject)
3581
+ .filter((subject): subject is string => Boolean(subject));
3582
+ const result = await runtime.escalate({
3583
+ originalRequestId: input.originalRequestId,
3584
+ sessionId: _sessionId,
3585
+ generation: requestScopeTracker.generation,
3586
+ workspace: _piSessionCwd || "/",
3587
+ task: open[0],
3588
+ action: input.action,
3589
+ reason: input.reason,
3590
+ blocked: [input.action],
3591
+ independentWork: open.length
3592
+ ? `the remaining work (${open.slice(0, 3).join(", ")}) may continue`
3593
+ : undefined,
3594
+ });
3595
+ logToFile(
3596
+ "[auto-continue]",
3597
+ `The escalation of ${input.originalRequestId} was ${
3598
+ result.deliveredAtLeastOne ? "delivered" : "NOT delivered"
3599
+ } - the work stays blocked until the human answers`,
3600
+ );
3601
+ } catch (error) {
3602
+ logToFile(
3603
+ "[auto-continue]",
3604
+ "The escalation of the refusal failed:",
3605
+ oneLineError(error),
3606
+ );
3607
+ }
3608
+ };
3609
+
3260
3610
  /**
3261
3611
  * Apply the decision of the judge.
3262
3612
  *
@@ -3402,6 +3752,25 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3402
3752
  clearWait();
3403
3753
  updateAutoContinueStatus("IDLE");
3404
3754
  }
3755
+ // The refusal of the judge is asked of the human. The
3756
+ // question of the judge is closed, so a linked question
3757
+ // with a fresh id carries the buttons: live buttons on a
3758
+ // resolved request would be a lie. The work stays blocked
3759
+ // until the human answers.
3760
+ if (requestId) {
3761
+ const question = sharedState.pqController?.getQuestion?.(requestId);
3762
+ const action =
3763
+ extractQuestionAction(question?.questionText) ??
3764
+ question?.questionText?.slice(0, 200) ??
3765
+ "the proposed action";
3766
+ await escalateJevRejection({
3767
+ originalRequestId: requestId,
3768
+ action,
3769
+ reason:
3770
+ evaluation.reasoning ||
3771
+ "the judge did not approve the action",
3772
+ });
3773
+ }
3405
3774
  return;
3406
3775
  }
3407
3776
 
@@ -3740,9 +4109,26 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3740
4109
  todoContinuationController = new TodoContinuationController(
3741
4110
  ctx as unknown as import("./packages/jev-judge/dist/todo-provider.js").TodoContext,
3742
4111
  {
3743
- dispatch: async (content: string) => {
3744
- await pi.sendUserMessage(content, { deliverAs: "steer" });
3745
- },
4112
+ dispatch: async (content: string) => {
4113
+ await pi.sendUserMessage(content, { deliverAs: "steer" });
4114
+ },
4115
+ // An advisory is a hidden observation, not a steer: it
4116
+ // continues the request that is running, so it carries
4117
+ // the generation of that request.
4118
+ advisoryDispatch: async (content: string, meta) => {
4119
+ pi.sendMessage(
4120
+ {
4121
+ customType: "harness:exploration-guard",
4122
+ content,
4123
+ display: false,
4124
+ details: {
4125
+ reason: meta?.reason ?? "exploration-guard",
4126
+ requestGeneration: meta?.requestGeneration,
4127
+ },
4128
+ },
4129
+ { deliverAs: "followUp", triggerTurn: true },
4130
+ );
4131
+ },
3746
4132
  validationLedger,
3747
4133
  }
3748
4134
  );
@@ -5779,7 +6165,7 @@ function initLangChain(pi: {
5779
6165
  },
5780
6166
  ): void;
5781
6167
  }): void {
5782
- const { readFileSync, writeFileSync, existsSync } = require("node:fs");
6168
+ const { readFileSync, existsSync } = require("node:fs");
5783
6169
  const { spawn } = require("node:child_process");
5784
6170
  const { fileURLToPath } = require("url");
5785
6171
  const { dirname } = require("node:path");
@@ -5892,7 +6278,10 @@ function initLangChain(pi: {
5892
6278
  coder: coderSpec,
5893
6279
  reviewer: reviewerSpec,
5894
6280
  };
5895
- writeFileSync(roleConfigPath, JSON.stringify(config, null, 2), "utf8");
6281
+ // The role config is a durable JSON store: it is published
6282
+ // through the atomic write seam, so a reader never sees a
6283
+ // half-written file.
6284
+ atomicWriteFileSync(roleConfigPath, JSON.stringify(config, null, 2));
5896
6285
 
5897
6286
  logToFile("[pi-harness]", "LangChain role config saved:");
5898
6287
  logToFile("[pi-harness]", ` planner: ${plannerSpec}`);
@@ -7184,6 +7573,22 @@ export default async function (pi: ExtensionAPI) {
7184
7573
  // prompt input field. The guard sends it to the harness log instead.
7185
7574
  initConsoleGuard(pi);
7186
7575
 
7576
+ // --- exploration-checkpoint: let the agent record what it found ---
7577
+ // The guard watches the reads, but only the agent knows what it learned
7578
+ // from them. The tool records that statement beside the coverage of the
7579
+ // request, so a compaction does not make the agent find it again.
7580
+ try {
7581
+ registerExplorationCheckpointTool(pi, {
7582
+ current: () => explorationGuard,
7583
+ });
7584
+ } catch (error) {
7585
+ logToFile(
7586
+ "[exploration-guard]",
7587
+ "the tool of the checkpoint could not be registered:",
7588
+ oneLineError(error),
7589
+ );
7590
+ }
7591
+
7187
7592
  // --- mcp-connector: the fallback for the MCP servers of the extensions ----
7188
7593
  // The built-in MCP extension of Pi connects the servers that extensions
7189
7594
  // register. The connector takes over only the servers that nobody else
@@ -7238,6 +7643,27 @@ export default async function (pi: ExtensionAPI) {
7238
7643
  // Check if manual mode is enabled (human-in-the-loop)
7239
7644
  const isManualMode = process.env.CODEX_MANUAL_MODE === "true";
7240
7645
 
7646
+ /**
7647
+ * Is this instance the recipient of the plan?
7648
+ *
7649
+ * The identity is the runtime identity of the instance: the
7650
+ * agent, the session and the generation. A plan of another
7651
+ * instance, of another session or of another generation is
7652
+ * never executed here.
7653
+ */
7654
+ function isLocalPlanRecipient(recipient?: {
7655
+ agentId: string;
7656
+ sessionId: string;
7657
+ generation: number;
7658
+ }): boolean {
7659
+ if (!recipient || !planReceiver) return false;
7660
+ return (
7661
+ recipient.agentId === planReceiver.agentId &&
7662
+ recipient.sessionId === planReceiver.sessionId &&
7663
+ recipient.generation === planReceiver.generation
7664
+ );
7665
+ }
7666
+
7241
7667
  // Trigger Pi to read the plan
7242
7668
  async function triggerPiForPlan(event: PlanEvent): Promise<void> {
7243
7669
  // The workspace of the plan decides where it goes. The
@@ -7245,6 +7671,9 @@ export default async function (pi: ExtensionAPI) {
7245
7671
  // same directory matches and two worktrees of one repository
7246
7672
  // do not.
7247
7673
  const planWorkspace = codexSessionState.currentProjectRoot || _piSessionCwd || "";
7674
+ let routedRecipient:
7675
+ | { agentId: string; sessionId: string; generation: number }
7676
+ | undefined;
7248
7677
  if (planWorkspace) {
7249
7678
  const delivery = deliverPlanToWorkspace({
7250
7679
  workspace: planWorkspace,
@@ -7277,6 +7706,7 @@ export default async function (pi: ExtensionAPI) {
7277
7706
  });
7278
7707
  return;
7279
7708
  }
7709
+ routedRecipient = delivery.recipient;
7280
7710
  logToFile("[codex-trigger]", "Plan routed to the instance of the workspace:", delivery.recipient?.agentId ?? "unknown");
7281
7711
  }
7282
7712
 
@@ -7288,10 +7718,40 @@ export default async function (pi: ExtensionAPI) {
7288
7718
  return;
7289
7719
  }
7290
7720
 
7291
- const triggerMsg = `Codex finished a plan for this workspace. Read and follow the plan at:\n${event.planPath}\n\nTreat that file as the task requirements. Start by summarizing the plan and then carry it out. Do not edit the plan unless the user asks.`;
7721
+ if (!planWorkspace) {
7722
+ // The workspace of the plan is unknown: there is no
7723
+ // routing and no recipient. The plan was found in the
7724
+ // project of this session, so this session takes it.
7725
+ const triggerMsg = `Codex finished a plan for this workspace. Read and follow the plan at:\n${event.planPath}\n\nTreat that file as the task requirements. Start by summarizing the plan and then carry it out. Do not edit the plan unless the user asks.`;
7726
+
7727
+ try {
7728
+ await pi.sendUserMessage(triggerMsg, { deliverAs: "steer" });
7729
+ event.status = "triggered";
7730
+ logToFile("[codex-trigger]", "Triggered Pi for plan:", event.planPath);
7731
+ } catch (err) {
7732
+ event.status = "failed";
7733
+ logToFile("[codex-trigger]", "Trigger failed:", String(err));
7734
+ }
7735
+ return;
7736
+ }
7737
+
7738
+ // The plan was routed to the instance that was selected. Only
7739
+ // that instance executes it: the instance that watched the
7740
+ // plan never executes the plan of another instance.
7741
+ if (!isLocalPlanRecipient(routedRecipient)) {
7742
+ event.status = "triggered";
7743
+ logToFile(
7744
+ "[codex-trigger]",
7745
+ "The plan waits for the selected instance:",
7746
+ routedRecipient?.agentId ?? "unknown",
7747
+ );
7748
+ return;
7749
+ }
7292
7750
 
7293
7751
  try {
7294
- await pi.sendUserMessage(triggerMsg, { deliverAs: "steer" });
7752
+ // The receiver of this instance hands the plan to this
7753
+ // session: one delivery, one execution.
7754
+ await planReceiver?.poll();
7295
7755
  event.status = "triggered";
7296
7756
  logToFile("[codex-trigger]", "Triggered Pi for plan:", event.planPath);
7297
7757
  } catch (err) {
@@ -10140,6 +10600,17 @@ issue is not authorized work of the current request).
10140
10600
  }
10141
10601
  }
10142
10602
 
10603
+ /**
10604
+ * The resume of the delegated timeout.
10605
+ *
10606
+ * The deadline of a question is not an answer: it continues the work
10607
+ * only under a delegation of the user, and the executor of the
10608
+ * automatic resumes binds the resume to the request that is running.
10609
+ */
10610
+ sharedState.delegatedResume = () => {
10611
+ void queueAutoResume("delegated-timeout", "resume", "followUp");
10612
+ };
10613
+
10143
10614
  /**
10144
10615
  * Deliver the intervention of the exploration guard.
10145
10616
  *
@@ -10154,21 +10625,43 @@ issue is not authorized work of the current request).
10154
10625
  async function deliverExplorationIntervention(): Promise<void> {
10155
10626
  const pending = explorationGuard?.takePending();
10156
10627
  if (!pending) return;
10157
- try {
10158
- pi.sendMessage(
10159
- {
10160
- customType: "harness:exploration-guard",
10161
- content: pending.message,
10162
- display: false,
10163
- details: {
10164
- reason: pending.kind,
10165
- // The message continues the request that is running, so
10166
- // it carries the generation of that request.
10167
- requestGeneration: pending.key.generation,
10168
- },
10628
+ const controller = sharedState.todoContinuationController as {
10629
+ dispatchAdvisory?: (
10630
+ message: string,
10631
+ options?: {
10632
+ itemId?: number;
10633
+ meta?: { reason?: string; requestGeneration?: string };
10169
10634
  },
10170
- { deliverAs: "followUp", triggerTurn: true },
10635
+ ) => Promise<{ dispatched: boolean; reason?: string }>;
10636
+ } | null;
10637
+ if (!controller || typeof controller.dispatchAdvisory !== "function") {
10638
+ // Without the controller there is no guarded path. The reminder
10639
+ // is not sent: an unguarded message would force a turn, and the
10640
+ // guard never forces a turn.
10641
+ logToFile(
10642
+ "[exploration-guard]",
10643
+ "the guarded path is not available, the reminder was not delivered",
10171
10644
  );
10645
+ return;
10646
+ }
10647
+ try {
10648
+ // The reminder goes through the guarded path: a pause, a pending
10649
+ // user message, a busy session and a completed task all stop it.
10650
+ const result = await controller.dispatchAdvisory(pending.message, {
10651
+ itemId: pending.key.todoId,
10652
+ meta: {
10653
+ reason: pending.kind,
10654
+ requestGeneration: pending.key.generation,
10655
+ },
10656
+ });
10657
+ if (!result.dispatched) {
10658
+ logToFile(
10659
+ "[exploration-guard]",
10660
+ "the reminder was not delivered:",
10661
+ result.reason,
10662
+ );
10663
+ return;
10664
+ }
10172
10665
  logToFile(
10173
10666
  "[exploration-guard]",
10174
10667
  `The guard spoke after ${pending.state.readCount} reads: ${pending.kind}`,