pi-harness-runtime 1.1.512 → 1.1.514

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 (225) hide show
  1. package/AGENTS.md +23 -0
  2. package/CHANGELOG.md +183 -0
  3. package/footer-status.ts +112 -43
  4. package/harness/cookie-import-refresh.ts +60 -0
  5. package/harness/exploration-guard-runtime.ts +316 -0
  6. package/harness/plan-handoff-bridge.ts +247 -0
  7. package/harness/plan-handoff-delivery.ts +193 -0
  8. package/harness/plan-handoff-recipient-selection.ts +205 -0
  9. package/harness/plan-handoff-registration.ts +169 -0
  10. package/harness/quota-credential-choice.ts +67 -0
  11. package/harness/quota-refresh-coordinator.ts +129 -0
  12. package/index.ts +633 -115
  13. package/package.json +7 -1
  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/detect-format.d.ts +26 -12
  23. package/packages/cookie-sanitizer/dist/detect-format.d.ts.map +1 -1
  24. package/packages/cookie-sanitizer/dist/detect-format.js +54 -39
  25. package/packages/cookie-sanitizer/dist/detect-format.js.map +1 -1
  26. package/packages/cookie-sanitizer/dist/index.d.ts +9 -3
  27. package/packages/cookie-sanitizer/dist/index.d.ts.map +1 -1
  28. package/packages/cookie-sanitizer/dist/index.js +5 -3
  29. package/packages/cookie-sanitizer/dist/index.js.map +1 -1
  30. package/packages/cookie-sanitizer/dist/parse-netscape-space.d.ts +73 -0
  31. package/packages/cookie-sanitizer/dist/parse-netscape-space.d.ts.map +1 -0
  32. package/packages/cookie-sanitizer/dist/parse-netscape-space.js +154 -0
  33. package/packages/cookie-sanitizer/dist/parse-netscape-space.js.map +1 -0
  34. package/packages/cookie-sanitizer/dist/parse-netscape.d.ts +28 -1
  35. package/packages/cookie-sanitizer/dist/parse-netscape.d.ts.map +1 -1
  36. package/packages/cookie-sanitizer/dist/parse-netscape.js +50 -13
  37. package/packages/cookie-sanitizer/dist/parse-netscape.js.map +1 -1
  38. package/packages/cookie-sanitizer/dist/source-state.d.ts +56 -0
  39. package/packages/cookie-sanitizer/dist/source-state.d.ts.map +1 -0
  40. package/packages/cookie-sanitizer/dist/source-state.js +61 -0
  41. package/packages/cookie-sanitizer/dist/source-state.js.map +1 -0
  42. package/packages/cookie-sanitizer/dist/sync.d.ts +9 -0
  43. package/packages/cookie-sanitizer/dist/sync.d.ts.map +1 -1
  44. package/packages/cookie-sanitizer/dist/sync.js +47 -16
  45. package/packages/cookie-sanitizer/dist/sync.js.map +1 -1
  46. package/packages/cookie-sanitizer/dist/types.d.ts +1 -1
  47. package/packages/cookie-sanitizer/dist/types.d.ts.map +1 -1
  48. package/packages/cookie-sanitizer/package.json +1 -1
  49. package/packages/cookie-sanitizer/src/detect-format.ts +78 -41
  50. package/packages/cookie-sanitizer/src/index.ts +34 -1
  51. package/packages/cookie-sanitizer/src/parse-netscape-space.ts +188 -0
  52. package/packages/cookie-sanitizer/src/parse-netscape.ts +81 -13
  53. package/packages/cookie-sanitizer/src/source-state.ts +95 -0
  54. package/packages/cookie-sanitizer/src/sync.ts +59 -16
  55. package/packages/cookie-sanitizer/src/types.ts +4 -1
  56. package/packages/evaluation-engine/package.json +1 -1
  57. package/packages/event-bus/package.json +1 -1
  58. package/packages/event-store/package.json +1 -1
  59. package/packages/experience-replay/package.json +1 -1
  60. package/packages/exploration-guard/dist/budget.d.ts +105 -0
  61. package/packages/exploration-guard/dist/budget.d.ts.map +1 -0
  62. package/packages/exploration-guard/dist/budget.js +199 -0
  63. package/packages/exploration-guard/dist/budget.js.map +1 -0
  64. package/packages/exploration-guard/dist/checkpoint.d.ts +140 -0
  65. package/packages/exploration-guard/dist/checkpoint.d.ts.map +1 -0
  66. package/packages/exploration-guard/dist/checkpoint.js +201 -0
  67. package/packages/exploration-guard/dist/checkpoint.js.map +1 -0
  68. package/packages/exploration-guard/dist/index.d.ts +19 -0
  69. package/packages/exploration-guard/dist/index.d.ts.map +1 -0
  70. package/packages/exploration-guard/dist/index.js +18 -0
  71. package/packages/exploration-guard/dist/index.js.map +1 -0
  72. package/packages/exploration-guard/dist/observation.d.ts +82 -0
  73. package/packages/exploration-guard/dist/observation.d.ts.map +1 -0
  74. package/packages/exploration-guard/dist/observation.js +239 -0
  75. package/packages/exploration-guard/dist/observation.js.map +1 -0
  76. package/packages/exploration-guard/dist/state.d.ts +107 -0
  77. package/packages/exploration-guard/dist/state.d.ts.map +1 -0
  78. package/packages/exploration-guard/dist/state.js +300 -0
  79. package/packages/exploration-guard/dist/state.js.map +1 -0
  80. package/packages/exploration-guard/dist/status.d.ts +56 -0
  81. package/packages/exploration-guard/dist/status.d.ts.map +1 -0
  82. package/packages/exploration-guard/dist/status.js +79 -0
  83. package/packages/exploration-guard/dist/status.js.map +1 -0
  84. package/packages/exploration-guard/dist/tracker.d.ts +115 -0
  85. package/packages/exploration-guard/dist/tracker.d.ts.map +1 -0
  86. package/packages/exploration-guard/dist/tracker.js +207 -0
  87. package/packages/exploration-guard/dist/tracker.js.map +1 -0
  88. package/packages/exploration-guard/dist/types.d.ts +254 -0
  89. package/packages/exploration-guard/dist/types.d.ts.map +1 -0
  90. package/packages/exploration-guard/dist/types.js +14 -0
  91. package/packages/exploration-guard/dist/types.js.map +1 -0
  92. package/packages/exploration-guard/package.json +16 -0
  93. package/packages/exploration-guard/src/budget.ts +275 -0
  94. package/packages/exploration-guard/src/checkpoint.ts +297 -0
  95. package/packages/exploration-guard/src/index.ts +97 -0
  96. package/packages/exploration-guard/src/observation.ts +342 -0
  97. package/packages/exploration-guard/src/state.ts +357 -0
  98. package/packages/exploration-guard/src/status.ts +120 -0
  99. package/packages/exploration-guard/src/tracker.ts +291 -0
  100. package/packages/exploration-guard/src/types.ts +276 -0
  101. package/packages/file-copy-helper/package.json +1 -1
  102. package/packages/intent-analyzer/package.json +1 -1
  103. package/packages/jev-judge/dist/continuation-controller.d.ts +27 -2
  104. package/packages/jev-judge/dist/continuation-controller.d.ts.map +1 -1
  105. package/packages/jev-judge/dist/continuation-controller.js +87 -11
  106. package/packages/jev-judge/dist/continuation-controller.js.map +1 -1
  107. package/packages/jev-judge/dist/index.d.ts +2 -0
  108. package/packages/jev-judge/dist/index.d.ts.map +1 -1
  109. package/packages/jev-judge/dist/index.js +2 -0
  110. package/packages/jev-judge/dist/index.js.map +1 -1
  111. package/packages/jev-judge/dist/todo-provider.d.ts.map +1 -1
  112. package/packages/jev-judge/dist/todo-provider.js +93 -18
  113. package/packages/jev-judge/dist/todo-provider.js.map +1 -1
  114. package/packages/jev-judge/dist/todo-reconciliation.d.ts +50 -0
  115. package/packages/jev-judge/dist/todo-reconciliation.d.ts.map +1 -0
  116. package/packages/jev-judge/dist/todo-reconciliation.js +96 -0
  117. package/packages/jev-judge/dist/todo-reconciliation.js.map +1 -0
  118. package/packages/jev-judge/package.json +1 -1
  119. package/packages/jev-judge/src/continuation-controller.ts +90 -12
  120. package/packages/jev-judge/src/index.ts +8 -0
  121. package/packages/jev-judge/src/todo-provider.ts +117 -25
  122. package/packages/jev-judge/src/todo-reconciliation.ts +121 -0
  123. package/packages/knowledge-retrieval/package.json +1 -1
  124. package/packages/learning-engine/package.json +1 -1
  125. package/packages/logging/package.json +1 -1
  126. package/packages/memory-engine/package.json +1 -1
  127. package/packages/notification/dist/adapters/email-adapter.d.ts.map +1 -1
  128. package/packages/notification/dist/adapters/email-adapter.js +1 -0
  129. package/packages/notification/dist/adapters/email-adapter.js.map +1 -1
  130. package/packages/notification/dist/adapters/line-adapter.d.ts.map +1 -1
  131. package/packages/notification/dist/adapters/line-adapter.js +1 -0
  132. package/packages/notification/dist/adapters/line-adapter.js.map +1 -1
  133. package/packages/notification/dist/adapters/ntfy-adapter.d.ts.map +1 -1
  134. package/packages/notification/dist/adapters/ntfy-adapter.js +1 -0
  135. package/packages/notification/dist/adapters/ntfy-adapter.js.map +1 -1
  136. package/packages/notification/dist/adapters/telegram-adapter.d.ts.map +1 -1
  137. package/packages/notification/dist/adapters/telegram-adapter.js +1 -0
  138. package/packages/notification/dist/adapters/telegram-adapter.js.map +1 -1
  139. package/packages/notification/dist/notification-center.d.ts.map +1 -1
  140. package/packages/notification/dist/notification-center.js +7 -0
  141. package/packages/notification/dist/notification-center.js.map +1 -1
  142. package/packages/notification/dist/notification-policy.d.ts.map +1 -1
  143. package/packages/notification/dist/notification-policy.js +3 -0
  144. package/packages/notification/dist/notification-policy.js.map +1 -1
  145. package/packages/notification/dist/telegram-webhook-handler.d.ts +8 -0
  146. package/packages/notification/dist/telegram-webhook-handler.d.ts.map +1 -1
  147. package/packages/notification/dist/telegram-webhook-handler.js +8 -0
  148. package/packages/notification/dist/telegram-webhook-handler.js.map +1 -1
  149. package/packages/notification/dist/types.d.ts +8 -1
  150. package/packages/notification/dist/types.d.ts.map +1 -1
  151. package/packages/notification/package.json +1 -1
  152. package/packages/notification/src/adapters/email-adapter.ts +1 -0
  153. package/packages/notification/src/adapters/line-adapter.ts +1 -0
  154. package/packages/notification/src/adapters/ntfy-adapter.ts +1 -0
  155. package/packages/notification/src/adapters/telegram-adapter.ts +1 -0
  156. package/packages/notification/src/notification-center.ts +7 -0
  157. package/packages/notification/src/notification-policy.ts +3 -0
  158. package/packages/notification/src/telegram-webhook-handler.ts +8 -0
  159. package/packages/notification/src/types.ts +7 -0
  160. package/packages/paperclip-integration/package.json +1 -1
  161. package/packages/performance-optimizer/package.json +1 -1
  162. package/packages/plan-handoff/dist/index.d.ts +31 -0
  163. package/packages/plan-handoff/dist/index.d.ts.map +1 -0
  164. package/packages/plan-handoff/dist/index.js +23 -0
  165. package/packages/plan-handoff/dist/index.js.map +1 -0
  166. package/packages/plan-handoff/dist/mailbox.d.ts +134 -0
  167. package/packages/plan-handoff/dist/mailbox.d.ts.map +1 -0
  168. package/packages/plan-handoff/dist/mailbox.js +243 -0
  169. package/packages/plan-handoff/dist/mailbox.js.map +1 -0
  170. package/packages/plan-handoff/dist/message.d.ts +152 -0
  171. package/packages/plan-handoff/dist/message.d.ts.map +1 -0
  172. package/packages/plan-handoff/dist/message.js +157 -0
  173. package/packages/plan-handoff/dist/message.js.map +1 -0
  174. package/packages/plan-handoff/dist/pairing.d.ts +51 -0
  175. package/packages/plan-handoff/dist/pairing.d.ts.map +1 -0
  176. package/packages/plan-handoff/dist/pairing.js +88 -0
  177. package/packages/plan-handoff/dist/pairing.js.map +1 -0
  178. package/packages/plan-handoff/dist/publish.d.ts +96 -0
  179. package/packages/plan-handoff/dist/publish.d.ts.map +1 -0
  180. package/packages/plan-handoff/dist/publish.js +97 -0
  181. package/packages/plan-handoff/dist/publish.js.map +1 -0
  182. package/packages/plan-handoff/dist/registry.d.ts +95 -0
  183. package/packages/plan-handoff/dist/registry.d.ts.map +1 -0
  184. package/packages/plan-handoff/dist/registry.js +122 -0
  185. package/packages/plan-handoff/dist/registry.js.map +1 -0
  186. package/packages/plan-handoff/dist/retention.d.ts +101 -0
  187. package/packages/plan-handoff/dist/retention.d.ts.map +1 -0
  188. package/packages/plan-handoff/dist/retention.js +178 -0
  189. package/packages/plan-handoff/dist/retention.js.map +1 -0
  190. package/packages/plan-handoff/dist/routing.d.ts +69 -0
  191. package/packages/plan-handoff/dist/routing.d.ts.map +1 -0
  192. package/packages/plan-handoff/dist/routing.js +75 -0
  193. package/packages/plan-handoff/dist/routing.js.map +1 -0
  194. package/packages/plan-handoff/dist/workspace.d.ts +59 -0
  195. package/packages/plan-handoff/dist/workspace.d.ts.map +1 -0
  196. package/packages/plan-handoff/dist/workspace.js +78 -0
  197. package/packages/plan-handoff/dist/workspace.js.map +1 -0
  198. package/packages/plan-handoff/package.json +16 -0
  199. package/packages/plan-handoff/src/index.ts +75 -0
  200. package/packages/plan-handoff/src/mailbox.ts +306 -0
  201. package/packages/plan-handoff/src/message.ts +286 -0
  202. package/packages/plan-handoff/src/pairing.ts +120 -0
  203. package/packages/plan-handoff/src/publish.ts +186 -0
  204. package/packages/plan-handoff/src/registry.ts +174 -0
  205. package/packages/plan-handoff/src/retention.ts +237 -0
  206. package/packages/plan-handoff/src/routing.ts +134 -0
  207. package/packages/plan-handoff/src/workspace.ts +89 -0
  208. package/packages/privilege-broker/package.json +1 -1
  209. package/packages/prompt-compiler/package.json +1 -1
  210. package/packages/providers/package.json +1 -1
  211. package/packages/qdrant-skills/package.json +1 -1
  212. package/packages/quota-manager/package.json +1 -1
  213. package/packages/relay/package.json +1 -1
  214. package/packages/skill-mcp-client/package.json +1 -1
  215. package/packages/skills/package.json +1 -1
  216. package/packages/todo-bd-sync/package.json +1 -1
  217. package/packages/token-estimation/package.json +1 -1
  218. package/packages/tooling-preference/package.json +1 -1
  219. package/packages/trajectory/package.json +1 -1
  220. package/packages/tui/package.json +1 -1
  221. package/packages/two-phase-review/package.json +1 -1
  222. package/packages/types/package.json +1 -1
  223. package/packages/webmcp-tester/package.json +1 -1
  224. package/packages/wiki/package.json +1 -1
  225. package/packages/write-review/package.json +1 -1
package/index.ts CHANGED
@@ -33,6 +33,20 @@ import {
33
33
  type KeyFileAuditResult,
34
34
  } from "./harness/key-file-audit.ts";
35
35
  import { renderDetailLines } from "./harness/startup-lines.ts";
36
+ import {
37
+ startPlanHandoffRegistration,
38
+ type PlanHandoffAgent,
39
+ } from "./harness/plan-handoff-registration.ts";
40
+ import { deliverPlanToWorkspace } from "./harness/plan-handoff-delivery.ts";
41
+ import {
42
+ offerRecipientSelection,
43
+ resolveRecipientSelection,
44
+ } from "./harness/plan-handoff-recipient-selection.ts";
45
+ import { ExplorationGuardRuntime } from "./harness/exploration-guard-runtime.ts";
46
+ import {
47
+ describeCandidates,
48
+ type AgentRegistration,
49
+ } from "./packages/plan-handoff/dist/index.js";
36
50
  import {
37
51
  isQuestionOpen,
38
52
  isRejection,
@@ -164,8 +178,14 @@ import { parseMiniMaxQuotaText } from "./harness/e2e/minimax-quota-parser.js";
164
178
  import {
165
179
  CookieWatcher,
166
180
  DEFAULT_DROP_DIR as COOKIE_DROP_DIR,
167
- hasAnyCookieSource as sanitizerHasAnyCookieSource,
181
+ inspectCookieSource,
168
182
  } from "./packages/cookie-sanitizer/src/index.ts";
183
+ import {
184
+ QuotaRefreshCoordinator,
185
+ type QuotaRefreshOutcome,
186
+ } from "./harness/quota-refresh-coordinator.ts";
187
+ import { handleCookieWatcherEvent } from "./harness/cookie-import-refresh.ts";
188
+ import { chooseQuotaCredential } from "./harness/quota-credential-choice.ts";
169
189
  import {
170
190
  providerFromModelId,
171
191
  type ProviderId,
@@ -176,6 +196,7 @@ import {
176
196
  } from "./packages/quota-manager/src/tui-usage-monitor.ts";
177
197
  import { QuotaManager } from "./packages/quota-manager/src/quota-manager.ts";
178
198
  import { buildFooterStatusValue } from "./footer-status.ts";
199
+ import type { FooterQuotaSource } from "./footer-status.ts";
179
200
  import { getProviderLabel } from "./packages/types/src/ai-providers.ts";
180
201
  import { registerGithubLoginCommand } from "./packages/clipboard/dist/src/github-login.js";
181
202
  import {
@@ -598,6 +619,188 @@ let todoContinuationHandle: { isExplicitlyPaused(): boolean } | null = null;
598
619
  */
599
620
  let activeExtensionContext: ExtensionContext | null = null;
600
621
 
622
+ /**
623
+ * The registration of this instance in the plan handoff store.
624
+ *
625
+ * The instance registers itself, so a sender can find the recipient of a
626
+ * plan in this workspace. The registration proves that the instance is
627
+ * alive, never that it may start a task.
628
+ */
629
+ let planHandoffAgent: PlanHandoffAgent | null = null;
630
+
631
+ /**
632
+ * The guard of the exploration of the running request.
633
+ *
634
+ * The guard watches the reads of the agent, keeps the record of what was
635
+ * already read, and asks for a checkpoint when the exploration passes the
636
+ * budget that the deployment chose.
637
+ *
638
+ * The guard never authorises anything: it never commits, never pushes,
639
+ * never builds, never answers a question of the human and never touches a
640
+ * countdown of the provider. It says what it saw, and the agent decides.
641
+ */
642
+ let explorationGuard: ExplorationGuardRuntime | null = null;
643
+
644
+ /**
645
+ * The phase of the request that is running, as the guard names it.
646
+ *
647
+ * The phase is the phase of the two-phase review when it is known, and
648
+ * "other" when it is not: an unknown phase is never guessed.
649
+ */
650
+ function explorationPhase(): "implementation" | "review" | "review_fixes" | "test" | "other" {
651
+ try {
652
+ const runtime = sharedState.twoPhaseRuntime as
653
+ | { getPhase?: () => string }
654
+ | null
655
+ | undefined;
656
+ const phase = runtime?.getPhase?.();
657
+ if (phase === "review" || phase === "review_fixes") return phase;
658
+ if (phase === "implementation") return "implementation";
659
+ if (phase === "test_pending" || phase === "test") return "test";
660
+ } catch {
661
+ // The phase is not known: the guard falls back to "other".
662
+ }
663
+ return "other";
664
+ }
665
+
666
+ /**
667
+ * The guard of the exploration, created when the session begins.
668
+ */
669
+ function startExplorationGuard(sessionId: string): void {
670
+ try {
671
+ explorationGuard = new ExplorationGuardRuntime({
672
+ identity: {
673
+ workspace: () => _piSessionCwd || process.cwd(),
674
+ sessionId: () => sessionId,
675
+ generation: () => String(requestScopeTracker.generation),
676
+ phase: () => explorationPhase(),
677
+ },
678
+ });
679
+ } catch (error) {
680
+ explorationGuard = null;
681
+ logToFile(
682
+ "[exploration-guard]",
683
+ "the guard could not be started:",
684
+ oneLineError(error),
685
+ );
686
+ }
687
+ }
688
+
689
+ /**
690
+ * Offer the user the choice of the recipient of a plan.
691
+ *
692
+ * Several Pi instances can run in the workspace of a plan. The plan is not
693
+ * broadcast: the user chooses the instance that receives it. The offer names
694
+ * the identity of every candidate, because the model label is not an
695
+ * identity.
696
+ */
697
+ async function offerPlanRecipient(options: {
698
+ workspace: string;
699
+ candidates: AgentRegistration[];
700
+ planPath?: string;
701
+ summary?: string;
702
+ senderSessionId?: string;
703
+ }): Promise<void> {
704
+ const selection = offerRecipientSelection({
705
+ workspace: options.workspace,
706
+ candidates: options.candidates,
707
+ ...(options.planPath ? { planPath: options.planPath } : {}),
708
+ ...(options.summary ? { summary: options.summary } : {}),
709
+ ...(options.senderSessionId
710
+ ? { senderSessionId: options.senderSessionId }
711
+ : {}),
712
+ });
713
+
714
+ const candidates = describeCandidates(options.candidates);
715
+ const lines = candidates.map(
716
+ (candidate, index) => `${index + 1}. ${candidate}`,
717
+ );
718
+ const message = [
719
+ `Several Pi instances run in ${options.workspace}.`,
720
+ "The plan is not broadcast: choose the instance that receives it.",
721
+ "",
722
+ ...lines,
723
+ ].join("\n");
724
+
725
+ const buttons = selection.offers.map((offer, index) => ({
726
+ text: `${index + 1}. ${offer.agentId.slice(0, 8)}`,
727
+ action: "planpick",
728
+ targetId: offer.token,
729
+ }));
730
+
731
+ logToFile(
732
+ "[plan-handoff]",
733
+ `Offering ${options.candidates.length} recipients for the workspace of the plan`,
734
+ );
735
+
736
+ try {
737
+ await _nc?.notifyWithButtons?.(
738
+ "PlanRecipientSelection",
739
+ { requirement: message, jobId: "plan-handoff" },
740
+ buttons,
741
+ );
742
+ } catch (error) {
743
+ logToFile("[plan-handoff]", "The offer of the recipients failed:", String(error));
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Apply the choice of the user about the recipient of a plan.
749
+ *
750
+ * The choice names one candidate of an offer. The first answer wins, and the
751
+ * choice becomes the pairing of the workspace, so the next plan of the same
752
+ * workspace goes to the same instance without asking again.
753
+ */
754
+ async function resolvePlanRecipient(
755
+ offerToken: string,
756
+ channel: "telegram" | "line",
757
+ ): Promise<{ ok: boolean; message: string }> {
758
+ const result = resolveRecipientSelection(offerToken, Date.now());
759
+ if (!result.ok || !result.selection || !result.recipient) {
760
+ logToFile(
761
+ "[plan-handoff]",
762
+ `The choice of the recipient (${channel}) was refused: ${result.reason}`,
763
+ );
764
+ return { ok: false, message: `Stale button - ${result.reason}` };
765
+ }
766
+
767
+ const selection = result.selection;
768
+ const recipient = result.recipient;
769
+
770
+ // The plan goes to the instance the user chose. The routing runs again
771
+ // with the pairing that the choice has just written, so the plan is
772
+ // delivered to the chosen instance and to no other.
773
+ const delivery = deliverPlanToWorkspace({
774
+ workspace: selection.workspace,
775
+ sender: {
776
+ agentId: "codex",
777
+ sessionId: selection.senderSessionId ?? "unknown",
778
+ },
779
+ summary: selection.summary ?? `Codex finished a plan: ${selection.planPath ?? ""}`,
780
+ ...(selection.planPath ? { reference: selection.planPath } : {}),
781
+ });
782
+
783
+ if (delivery.decision !== "queued") {
784
+ logToFile(
785
+ "[plan-handoff]",
786
+ `The chosen recipient could not be reached: ${delivery.reason}`,
787
+ );
788
+ return {
789
+ ok: false,
790
+ message: "The chosen instance cannot be reached right now.",
791
+ };
792
+ }
793
+
794
+ logToFile(
795
+ "[plan-handoff]",
796
+ `The plan goes to the chosen instance: ${recipient.agentId}`,
797
+ );
798
+ return {
799
+ ok: true,
800
+ message: `The plan goes to the chosen instance (${recipient.agentId.slice(0, 8)}).`,
801
+ };
802
+ }
803
+
601
804
  /**
602
805
  * The controller of the bounded recovery cycles.
603
806
  *
@@ -758,6 +961,10 @@ const sharedState = {
758
961
  delegationHarness: null as any,
759
962
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
760
963
  workspaceEnvMessage: null as string | null,
964
+ // The runtime of the two-phase workflow. The guard of the exploration
965
+ // reads its phase, so the exploration budget follows the phase of the
966
+ // work: a review reads differently than an implementation.
967
+ twoPhaseRuntime: null as unknown,
761
968
  // The state of the work of the request that is running. The automatic
762
969
  // resume reads it to know whether the work of the request remains.
763
970
  workContext: null as unknown,
@@ -894,6 +1101,9 @@ function beginHumanRequest(): void {
894
1101
  // A new request of the human has its own report: the completion of the
895
1102
  // previous one was already reported.
896
1103
  suppressedResumeReported = false;
1104
+ // The guard of the exploration is active again. The state of the new
1105
+ // request is its own: the counters of the old request do not carry over.
1106
+ explorationGuard?.activate();
897
1107
  }
898
1108
 
899
1109
  /**
@@ -1342,6 +1552,9 @@ async function initTwoPhaseReview(pi: ExtensionAPI): Promise<void> {
1342
1552
  }
1343
1553
  },
1344
1554
  log: (message: string) => logToFile("[TwoPhase]", message),
1555
+ }).then((runtime) => {
1556
+ // The guard of the exploration reads the phase of the workflow.
1557
+ sharedState.twoPhaseRuntime = runtime;
1345
1558
  });
1346
1559
  } catch (error) {
1347
1560
  logToFile("[TwoPhase]", `runtime not registered: ${oneLineError(error)}`);
@@ -1923,6 +2136,29 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1923
2136
  }
1924
2137
  });
1925
2138
 
2139
+ // The guard of the exploration remembers the call, so the result can be
2140
+ // paired with it. Nothing is observed here: a call that fails read
2141
+ // nothing, and only the result says what was read.
2142
+ pi.on("tool_call", (event) => {
2143
+ try {
2144
+ const toolEvent = event as {
2145
+ toolCallId?: string;
2146
+ toolName?: string;
2147
+ input?: unknown;
2148
+ };
2149
+ explorationGuard?.toolCall(String(toolEvent.toolCallId ?? ""), {
2150
+ toolName: String(toolEvent.toolName ?? ""),
2151
+ input: toolEvent.input,
2152
+ });
2153
+ } catch (error) {
2154
+ logToFile(
2155
+ "[exploration-guard]",
2156
+ "the call could not be remembered:",
2157
+ oneLineError(error),
2158
+ );
2159
+ }
2160
+ });
2161
+
1926
2162
  pi.on("tool_execution_end", (event) => {
1927
2163
  try {
1928
2164
  const toolEvent = event as {
@@ -1930,7 +2166,24 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1930
2166
  toolName?: string;
1931
2167
  result?: unknown;
1932
2168
  isError?: boolean;
2169
+ durationMs?: number;
1933
2170
  };
2171
+ // The guard of the exploration observes the read and the search.
2172
+ // It speaks at a safe boundary and it never authorises anything.
2173
+ try {
2174
+ explorationGuard?.toolCallEnd(String(toolEvent.toolCallId ?? ""), {
2175
+ toolName: String(toolEvent.toolName ?? ""),
2176
+ isError: toolEvent.isError === true,
2177
+ result: toolEvent.result,
2178
+ durationMs: toolEvent.durationMs,
2179
+ });
2180
+ } catch (error) {
2181
+ logToFile(
2182
+ "[exploration-guard]",
2183
+ "the observation failed:",
2184
+ oneLineError(error),
2185
+ );
2186
+ }
1934
2187
  const child = sharedState.delegationHarness?.observeToolEnd?.({
1935
2188
  toolCallId: String(toolEvent.toolCallId ?? ""),
1936
2189
  toolName: String(toolEvent.toolName ?? ""),
@@ -2190,8 +2443,6 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2190
2443
 
2191
2444
  // Capture UI context from session_start
2192
2445
  pi.on("session_start", (_event, ctx) => {
2193
- // The context of the running extension: a resume checks it
2194
- // before it dispatches, so it does not compete with the user.
2195
2446
  activeExtensionContext = ctx;
2196
2447
  // The session of the runtime: the countdown of a question belongs
2197
2448
  // to the session that asked it.
@@ -2209,6 +2460,28 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2209
2460
  _piSessionId = sessionId;
2210
2461
  activeSessionId = sessionId;
2211
2462
  }
2463
+ // The instance registers itself in its workspace, so a sender can
2464
+ // find the recipient of a plan here. The registration proves that
2465
+ // the instance is alive, never that it may start a task.
2466
+ if (planHandoffAgent) {
2467
+ planHandoffAgent.stop();
2468
+ planHandoffAgent = null;
2469
+ }
2470
+ if (_piSessionId) {
2471
+ startExplorationGuard(_piSessionId);
2472
+ try {
2473
+ planHandoffAgent = startPlanHandoffRegistration({
2474
+ sessionId: _piSessionId,
2475
+ modelLabel: ctx.model?.id,
2476
+ });
2477
+ } catch (error) {
2478
+ logToFile(
2479
+ "[plan-handoff]",
2480
+ "the registration of the instance failed:",
2481
+ error instanceof Error ? error.message : String(error),
2482
+ );
2483
+ }
2484
+ }
2212
2485
  if (ctx.hasUI && ctx.ui) {
2213
2486
  _setAutoContinueStatus = ctx.ui.setStatus.bind(ctx.ui, "harness-auto-continue");
2214
2487
  // The pending actions of the session get their own row of the
@@ -2228,9 +2501,16 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2228
2501
 
2229
2502
  });
2230
2503
 
2231
- // Clear status and cancel background work on session shutdown
2232
- pi.on("session_shutdown", () => {
2233
- // Cancel the auto-continue interval
2504
+ // Clear status and cancel background work on session shutdown
2505
+ pi.on("session_shutdown", () => {
2506
+ // The instance leaves the plan handoff store: a sender must
2507
+ // not find an instance that is no longer running.
2508
+ if (planHandoffAgent) {
2509
+ planHandoffAgent.stop();
2510
+ planHandoffAgent = null;
2511
+ }
2512
+
2513
+ // Cancel the auto-continue interval
2234
2514
  if (autoContinueTimer) {
2235
2515
  clearInterval(autoContinueTimer);
2236
2516
  autoContinueTimer = null;
@@ -3499,6 +3779,9 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3499
3779
  sharedState.scopeRuntime = null;
3500
3780
  // The scope belongs to the session that is ending.
3501
3781
  requestScopeTracker.reset();
3782
+ // The pending actions of the guard belong to the session that
3783
+ // is ending: a completed request is not continued by the guard.
3784
+ explorationGuard?.deactivate();
3502
3785
  });
3503
3786
 
3504
3787
  // --- task-intake: Automatic todo capture from user requests -----------
@@ -3994,7 +4277,7 @@ interface PlanEvent {
3994
4277
  codexSessionId: string;
3995
4278
  planPath: string;
3996
4279
  planHash: string;
3997
- status: "observed" | "settling" | "ready" | "triggered" | "failed" | "manual_wait" | "done";
4280
+ status: "observed" | "settling" | "ready" | "triggered" | "failed" | "manual_wait" | "done" | "retained" | "needs_recipient";
3998
4281
  ordinal: number;
3999
4282
  lastActivity: number;
4000
4283
  settleTimer: ReturnType<typeof setTimeout> | null;
@@ -4363,6 +4646,17 @@ async function initTelegram(pi: ExtensionAPI): Promise<void> {
4363
4646
  await acknowledge(result.message);
4364
4647
  break;
4365
4648
  }
4649
+ case CallbackActions.PLAN_RECIPIENT: {
4650
+ // The user chose the Pi instance that receives the plan.
4651
+ // The choice is the human alone, the first answer wins,
4652
+ // and the plan is never broadcast.
4653
+ const result = await resolvePlanRecipient(
4654
+ parsed.targetId,
4655
+ "telegram",
4656
+ );
4657
+ await acknowledge(result.message);
4658
+ break;
4659
+ }
4366
4660
  default:
4367
4661
  // Check for channel toggle actions
4368
4662
  if (parsed.action === "toggle_telegram") {
@@ -4484,6 +4778,11 @@ async function initTelegram(pi: ExtensionAPI): Promise<void> {
4484
4778
  ctx: Record<string, unknown>,
4485
4779
  options?: { approveLabel?: string; rejectLabel?: string },
4486
4780
  ) => center.notifyWithApproval(event as never, ctx as never, options as never),
4781
+ notifyWithButtons: (
4782
+ event: string,
4783
+ ctx: Record<string, unknown>,
4784
+ buttons: Array<{ text: string; action: string; targetId: string; url?: string }>,
4785
+ ) => center.notifyWithButtons(event as never, ctx as never, buttons as never),
4487
4786
  };
4488
4787
 
4489
4788
  // Wire to GLMQuotaCountdown so it sends Telegram alerts
@@ -4908,6 +5207,21 @@ async function initRelayStream(): Promise<void> {
4908
5207
  ? "countdown"
4909
5208
  : "manual";
4910
5209
  await resolveWeeklyDecision(raw, decision, "line");
5210
+ } else if (
5211
+ callback.action === "planpick" ||
5212
+ callback.action.startsWith("planpick_")
5213
+ ) {
5214
+ // The choice of the recipient of a plan is the same
5215
+ // choice as in Telegram: one resolver, the first
5216
+ // answer wins. The postback data arrives split into the
5217
+ // action and the token of the candidate, and it may
5218
+ // arrive as one string.
5219
+ const separator = callback.action.indexOf("_");
5220
+ const raw =
5221
+ separator === -1
5222
+ ? callback.targetId
5223
+ : callback.action.slice(separator + 1);
5224
+ await resolvePlanRecipient(raw, "line");
4911
5225
  } else {
4912
5226
  applyChannelApproval(callback.action, callback.targetId, "line");
4913
5227
  }
@@ -6156,6 +6470,15 @@ interface LoopCompletion {
6156
6470
  finishedAt: string;
6157
6471
  }
6158
6472
 
6473
+ /**
6474
+ * The tag of a completed loop, for the log line.
6475
+ */
6476
+ function loopCompletionTag(verdict: string): string {
6477
+ if (verdict === "approved") return "[ok]";
6478
+ if (verdict === "blocked") return "[blocked]";
6479
+ return "[done]";
6480
+ }
6481
+
6159
6482
  function processCompletionFile(filePath: string, pi: ExtensionAPI): void {
6160
6483
  const { existsSync, readFileSync, unlinkSync } = require("node:fs");
6161
6484
  try {
@@ -6163,12 +6486,7 @@ function processCompletionFile(filePath: string, pi: ExtensionAPI): void {
6163
6486
  const raw = readFileSync(filePath, "utf8");
6164
6487
  const completion = JSON.parse(raw) as LoopCompletion;
6165
6488
 
6166
- const tag =
6167
- completion.verdict === "approved"
6168
- ? "[ok]"
6169
- : completion.verdict === "blocked"
6170
- ? "[blocked]"
6171
- : "[done]";
6489
+ const tag = loopCompletionTag(completion.verdict);
6172
6490
 
6173
6491
  const message =
6174
6492
  `Loop completed ${tag}: ${completion.taskId}\n` +
@@ -6884,7 +7202,7 @@ export default async function (pi: ExtensionAPI) {
6884
7202
  codexSessionId: string;
6885
7203
  planPath: string;
6886
7204
  planHash: string;
6887
- status: "observed" | "settling" | "ready" | "triggered" | "failed" | "manual_wait" | "done";
7205
+ status: "observed" | "settling" | "ready" | "triggered" | "failed" | "manual_wait" | "done" | "retained" | "needs_recipient";
6888
7206
  ordinal: number;
6889
7207
  lastActivity: number;
6890
7208
  settleTimer: ReturnType<typeof setTimeout> | null;
@@ -6922,10 +7240,44 @@ export default async function (pi: ExtensionAPI) {
6922
7240
 
6923
7241
  // Trigger Pi to read the plan
6924
7242
  async function triggerPiForPlan(event: PlanEvent): Promise<void> {
6925
- // Check cwd match
6926
- if (_piSessionCwd && codexSessionState.currentProjectRoot && _piSessionCwd !== codexSessionState.currentProjectRoot) {
6927
- logToFile("[codex-trigger]", "Cwd mismatch, skipping:", _piSessionCwd, "!=", codexSessionState.currentProjectRoot);
6928
- return;
7243
+ // The workspace of the plan decides where it goes. The
7244
+ // comparison is on the canonical paths, so a symlink of the
7245
+ // same directory matches and two worktrees of one repository
7246
+ // do not.
7247
+ const planWorkspace = codexSessionState.currentProjectRoot || _piSessionCwd || "";
7248
+ if (planWorkspace) {
7249
+ const delivery = deliverPlanToWorkspace({
7250
+ workspace: planWorkspace,
7251
+ sender: {
7252
+ agentId: "codex",
7253
+ sessionId: codexSessionState.currentCodexSessionId || "unknown",
7254
+ },
7255
+ summary: `Codex finished a plan: ${event.planPath}`,
7256
+ reference: event.planPath,
7257
+ });
7258
+ if (delivery.decision === "retained") {
7259
+ // No Pi instance runs in the workspace of the plan: the
7260
+ // plan waits for one. It is never delivered to an
7261
+ // instance of another project.
7262
+ logToFile("[codex-trigger]", "No instance in the workspace of the plan, retained:", planWorkspace);
7263
+ event.status = "retained";
7264
+ return;
7265
+ }
7266
+ if (delivery.decision === "needs-recipient") {
7267
+ // Several instances run in the workspace: the recipient
7268
+ // has to be selected, and the plan is not broadcast.
7269
+ logToFile("[codex-trigger]", "Several instances in the workspace of the plan, a recipient has to be selected:", planWorkspace);
7270
+ event.status = "needs_recipient";
7271
+ await offerPlanRecipient({
7272
+ workspace: planWorkspace,
7273
+ candidates: delivery.candidates,
7274
+ planPath: event.planPath,
7275
+ summary: `Codex finished a plan: ${event.planPath}`,
7276
+ senderSessionId: codexSessionState.currentCodexSessionId || undefined,
7277
+ });
7278
+ return;
7279
+ }
7280
+ logToFile("[codex-trigger]", "Plan routed to the instance of the workspace:", delivery.recipient?.agentId ?? "unknown");
6929
7281
  }
6930
7282
 
6931
7283
  // In manual mode, do NOT auto-trigger Pi - wait for human command
@@ -8097,19 +8449,48 @@ issue is not authorized work of the current request).
8097
8449
  const cookieDropDir = COOKIE_DROP_DIR;
8098
8450
  const cookieCachePath = join(homedir(), ".config", "minimax-cookies.txt");
8099
8451
 
8100
- const hasCookieSource = (): boolean => {
8101
- try {
8102
- if (existsSync(cookieCachePath)) return true;
8103
- } catch {
8104
- // ignore
8105
- }
8452
+ /**
8453
+ * The shared quota refresh.
8454
+ *
8455
+ * One refresh at a time. A watcher event, a periodic tick and a command
8456
+ * that arrive together share one fetch, so a burst never opens two
8457
+ * browsers and never asks the provider twice.
8458
+ */
8459
+ const quotaRefresh = new QuotaRefreshCoordinator({
8460
+ refresh: () => autoFetchQuota({ suppressErrors: true }),
8461
+ logger: (message) => logToFile("[pi-harness] quota refresh:", message),
8462
+ });
8463
+
8464
+ /**
8465
+ * The state of the credential source.
8466
+ *
8467
+ * Three facts are different and were conflated: a file was found
8468
+ * (discovery), the file was imported into the canonical cache (import),
8469
+ * and the provider accepted the credential (authentication). The first
8470
+ * two are read from the disk; the third comes from the last fetch.
8471
+ */
8472
+ const cookieSourceState = (): FooterQuotaSource => {
8473
+ let stage: FooterQuotaSource["stage"] = "none";
8106
8474
  try {
8107
- return sanitizerHasAnyCookieSource(cookieDropDir);
8475
+ stage = inspectCookieSource({
8476
+ dropDir: cookieDropDir,
8477
+ cachePath: cookieCachePath,
8478
+ }).stage;
8108
8479
  } catch {
8109
- return false;
8480
+ stage = "none";
8110
8481
  }
8482
+ const last = quotaRefresh.lastOutcome;
8483
+ return {
8484
+ stage,
8485
+ lastFetch: last
8486
+ ? { ok: last.ok, source: last.source, reason: last.reason }
8487
+ : null,
8488
+ };
8111
8489
  };
8112
8490
 
8491
+ /** Whether any credential source exists, imported or not. */
8492
+ const hasCookieSource = (): boolean => cookieSourceState().stage !== "none";
8493
+
8113
8494
  // --- TUI quota signal plumbing (OpenAI / GLM / Anthropic / OpenRouter) --
8114
8495
  // The TUIUsageMonitor parses provider quota-exhaustion messages from pi's
8115
8496
  // TUI / message stream and emits signals we write to per-provider mirror
@@ -8145,49 +8526,22 @@ issue is not authorized work of the current request).
8145
8526
  dropDir: cookieDropDir,
8146
8527
  syncOptions: { cachePath: cookieCachePath, providerHint: "minimax" },
8147
8528
  onEvent: (event) => {
8148
- if (event.kind === "sync-error" || event.kind === "watcher-error") {
8149
- const msg = "message" in event ? event.message : "";
8150
- if (msg.includes("ENOSPC")) {
8151
- logToFile(
8152
- "[pi-harness] cookie-sanitizer: ENOSPC — inotify watchers exhausted.\n" +
8153
- " Fix (run once as sudo):\n" +
8154
- " echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/99-watch.conf\n" +
8155
- " sudo sysctl --system",
8156
- );
8157
- } else {
8158
- logToFile("[pi-harness] cookie-sanitizer:", msg);
8159
- }
8160
- }
8161
- // A successful sync means the canonical cache is fresh; the
8162
- // next autoFetchQuota() should pick it up immediately. Reset
8163
- // the rate-limit so we don't wait 15 min for the first scrape.
8529
+ // A successful sync means the canonical cache is fresh. One
8530
+ // shared refresh, outside the model, picks the new credential
8531
+ // up. The rate limit is reset so the periodic tick does not
8532
+ // ask again before the shared refresh finished.
8164
8533
  if (event.kind === "sync-ok") {
8165
8534
  lastQuotaAutoFetchAt = 0;
8166
8535
  }
8536
+ handleCookieWatcherEvent(event, {
8537
+ requestRefresh: (trigger) => {
8538
+ void quotaRefresh.request(trigger);
8539
+ },
8540
+ log: (message) => logToFile("[pi-harness]", message),
8541
+ });
8167
8542
  },
8168
8543
  });
8169
8544
 
8170
- try {
8171
- cookieWatcher.start();
8172
- // Sync existing drop-folder cookies now (ignoreInitial: true means
8173
- // the watcher won't do this automatically on startup).
8174
- cookieWatcher.triggerNow();
8175
- } catch (e) {
8176
- const msg = e instanceof Error ? e.message : String(e);
8177
- if (msg.includes("ENOSPC")) {
8178
- logToFile(
8179
- "[pi-harness] cookie-sanitizer watcher: ENOSPC — " +
8180
- "inotify watcher limit reached.\n" +
8181
- "Fix (once, as root):\n" +
8182
- " echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/99-watch.conf\n" +
8183
- " sudo sysctl --system\n" +
8184
- "Drop folder sync still works — polling will resume automatically.",
8185
- );
8186
- } else {
8187
- logToFile("[pi-harness] cookie-sanitizer watcher failed to start:", msg);
8188
- }
8189
- }
8190
-
8191
8545
  // Store only the setStatus function, NOT the ctx itself.
8192
8546
  // Storing ctx causes stale-context errors after pi reload/restart.
8193
8547
  let footerSetStatus: ((key: string, value: string) => void) | null = null;
@@ -8310,7 +8664,7 @@ issue is not authorized work of the current request).
8310
8664
  footerSetStatus,
8311
8665
  tracker,
8312
8666
  mirrorStore,
8313
- hasCookieSource,
8667
+ cookieSourceState,
8314
8668
  () => lastActiveProvider,
8315
8669
  );
8316
8670
  }
@@ -8386,7 +8740,7 @@ issue is not authorized work of the current request).
8386
8740
  footerSetStatus,
8387
8741
  tracker,
8388
8742
  mirrorStore,
8389
- hasCookieSource,
8743
+ cookieSourceState,
8390
8744
  () => lastActiveProvider,
8391
8745
  );
8392
8746
  }
@@ -8411,9 +8765,9 @@ issue is not authorized work of the current request).
8411
8765
 
8412
8766
  async function autoFetchQuotaFromBrowserProfile(
8413
8767
  suppressErrors = false,
8414
- ): Promise<MirrorRecord | null> {
8768
+ ): Promise<{ record: MirrorRecord | null; reason?: string }> {
8415
8769
  if (!(await hasBrowserProfileAutoFetchSource())) {
8416
- return null;
8770
+ return { record: null };
8417
8771
  }
8418
8772
 
8419
8773
  try {
@@ -8425,19 +8779,28 @@ issue is not authorized work of the current request).
8425
8779
  status.page_url.includes("unified-login") ||
8426
8780
  status.page_url.includes("login")
8427
8781
  ) {
8428
- return null;
8782
+ return {
8783
+ record: null,
8784
+ reason: "the browser profile is not signed in",
8785
+ };
8429
8786
  }
8430
8787
  const rawText =
8431
8788
  status.usage_lines?.join("\n")?.trim() ||
8432
8789
  status.detected_text_sample?.trim() ||
8433
8790
  "";
8434
8791
  if (!rawText) {
8435
- return null;
8792
+ return {
8793
+ record: null,
8794
+ reason: "the browser profile holds no quota reading",
8795
+ };
8436
8796
  }
8437
8797
 
8438
8798
  const parsed = parseMiniMaxQuotaText(rawText);
8439
8799
  if (parsed.h5UsedPct === undefined && parsed.weeklyUsedPct === undefined) {
8440
- return null;
8800
+ return {
8801
+ record: null,
8802
+ reason: "the browser profile reading holds no quota window",
8803
+ };
8441
8804
  }
8442
8805
 
8443
8806
  // The console writes the remaining time of a window as text. The
@@ -8446,39 +8809,43 @@ issue is not authorized work of the current request).
8446
8809
  const observedAt = Date.parse(status.checked_at);
8447
8810
 
8448
8811
  return {
8449
- synced_at: status.checked_at,
8450
- provider: "minimax",
8451
- h5_used_pct: parsed.h5UsedPct,
8452
- h5_resets_at: parsed.h5ResetsAt,
8453
- h5_resets_at_epoch: resetEpochFromDuration(
8454
- parsed.h5ResetsAt,
8455
- observedAt,
8456
- ),
8457
- weekly_used_pct: parsed.weeklyUsedPct,
8458
- weekly_resets_at: parsed.weeklyResetsAt,
8459
- weekly_resets_at_epoch: resetEpochFromDuration(
8460
- parsed.weeklyResetsAt,
8461
- observedAt,
8462
- ),
8812
+ record: {
8813
+ synced_at: status.checked_at,
8814
+ provider: "minimax",
8815
+ h5_used_pct: parsed.h5UsedPct,
8816
+ h5_resets_at: parsed.h5ResetsAt,
8817
+ h5_resets_at_epoch: resetEpochFromDuration(
8818
+ parsed.h5ResetsAt,
8819
+ observedAt,
8820
+ ),
8821
+ weekly_used_pct: parsed.weeklyUsedPct,
8822
+ weekly_resets_at: parsed.weeklyResetsAt,
8823
+ weekly_resets_at_epoch: resetEpochFromDuration(
8824
+ parsed.weeklyResetsAt,
8825
+ observedAt,
8826
+ ),
8827
+ },
8463
8828
  };
8464
8829
  } catch (error) {
8830
+ const reason = error instanceof Error ? error.message : String(error);
8465
8831
  if (!suppressErrors) {
8466
8832
  logToFile(
8467
8833
  "[pi-harness]",
8468
8834
  "Browser-profile quota fetch skipped:",
8469
- error instanceof Error ? error.message : String(error),
8835
+ reason,
8470
8836
  );
8471
8837
  }
8472
- return null;
8838
+ return { record: null, reason };
8473
8839
  }
8474
8840
  }
8475
8841
 
8476
8842
  async function autoFetchQuota(options?: {
8477
8843
  suppressErrors?: boolean;
8478
- }): Promise<boolean> {
8844
+ }): Promise<QuotaRefreshOutcome> {
8479
8845
  const suppressErrors = options?.suppressErrors === true;
8480
- const profileRecord = await autoFetchQuotaFromBrowserProfile(suppressErrors);
8481
- if (profileRecord) {
8846
+ const profile = await autoFetchQuotaFromBrowserProfile(suppressErrors);
8847
+ if (profile.record) {
8848
+ const profileRecord = profile.record;
8482
8849
  writeMirrorRecord("minimax", {
8483
8850
  synced_at: profileRecord.synced_at,
8484
8851
  source: "scrape",
@@ -8490,11 +8857,19 @@ issue is not authorized work of the current request).
8490
8857
  weekly_resets_at: profileRecord.weekly_resets_at,
8491
8858
  weekly_resets_at_epoch: profileRecord.weekly_resets_at_epoch,
8492
8859
  });
8493
- return true;
8860
+ return { ok: true, source: "browser-profile" };
8494
8861
  }
8495
8862
 
8496
- if (!hasCookieSource()) {
8497
- return false;
8863
+ // The browser profile already ran and did not answer. The cookie
8864
+ // cache is the second credential, and it only exists when an import
8865
+ // published it: a file that was found but not imported gives a
8866
+ // scraper nothing to read.
8867
+ const choice = chooseQuotaCredential({
8868
+ browserProfile: { ok: false, reason: profile.reason },
8869
+ cookieStage: cookieSourceState().stage,
8870
+ });
8871
+ if (choice.choice !== "cookie-cache") {
8872
+ return { ok: false, source: "none", reason: choice.reason };
8498
8873
  }
8499
8874
 
8500
8875
  try {
@@ -8509,16 +8884,41 @@ issue is not authorized work of the current request).
8509
8884
  weekly_resets_at: data.weeklyResetsAt,
8510
8885
  weekly_resets_at_epoch: data.weeklyResetsAtEpoch,
8511
8886
  });
8512
- return true;
8887
+ return { ok: true, source: "cookie-cache" };
8513
8888
  } catch (error) {
8889
+ const reason = error instanceof Error ? error.message : String(error);
8514
8890
  if (!suppressErrors) {
8515
8891
  logToFile(
8516
8892
  "[pi-harness]",
8517
8893
  "Quota auto-fetch skipped:",
8518
- error instanceof Error ? error.message : String(error),
8894
+ reason,
8519
8895
  );
8520
8896
  }
8521
- return false;
8897
+ return { ok: false, source: "cookie-cache", reason };
8898
+ }
8899
+ }
8900
+
8901
+ // The watcher starts here, not at the top of the initialization: a sync
8902
+ // that runs during the initialization would ask for a refresh that reads
8903
+ // capture state that does not exist yet.
8904
+ try {
8905
+ cookieWatcher.start();
8906
+ // Sync existing drop-folder cookies now (ignoreInitial: true means
8907
+ // the watcher won't do this automatically on startup).
8908
+ cookieWatcher.triggerNow();
8909
+ } catch (e) {
8910
+ const msg = e instanceof Error ? e.message : String(e);
8911
+ if (msg.includes("ENOSPC")) {
8912
+ logToFile(
8913
+ "[pi-harness] cookie-sanitizer watcher: ENOSPC — " +
8914
+ "inotify watcher limit reached.\n" +
8915
+ "Fix (once, as root):\n" +
8916
+ " echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/99-watch.conf\n" +
8917
+ " sudo sysctl --system\n" +
8918
+ "Drop folder sync still works — polling will resume automatically.",
8919
+ );
8920
+ } else {
8921
+ logToFile("[pi-harness] cookie-sanitizer watcher failed to start:", msg);
8522
8922
  }
8523
8923
  }
8524
8924
 
@@ -8671,7 +9071,8 @@ issue is not authorized work of the current request).
8671
9071
  */
8672
9072
  async function captureQuotaOf(provider: string): Promise<boolean> {
8673
9073
  if (provider === "minimax") {
8674
- return autoFetchQuota({ suppressErrors: true });
9074
+ const outcome = await autoFetchQuota({ suppressErrors: true });
9075
+ return outcome.ok;
8675
9076
  }
8676
9077
  if (provider === "openai" || provider === "openai-codex") {
8677
9078
  return autoFetchOpenAIQuota({ suppressErrors: true });
@@ -8820,23 +9221,46 @@ issue is not authorized work of the current request).
8820
9221
  pi.registerCommand("usage-refresh", {
8821
9222
  description: "Force refresh quota from provider console",
8822
9223
  handler: async (_args: string, ctx: ExtensionCommandContext) => {
8823
- const autoFetchAvailable =
8824
- hasCookieSource() || (await hasBrowserProfileAutoFetchSource());
8825
- if (!autoFetchAvailable) {
9224
+ const source = cookieSourceState();
9225
+ const browserProfile = await hasBrowserProfileAutoFetchSource();
9226
+ if (!hasCookieSource() && !browserProfile) {
8826
9227
  ctx.ui.notify(
8827
- "MiniMax cookies not found. Drop any cookie file (Netscape or EditThisCookie JSON) into ~/.pi-harness-runtime/cookies/ — the runtime normalizes it for you. Or run `bun packages/auth/src/run-minimax-auth.ts auth`.",
9228
+ "MiniMax cookies not found. Drop any cookie file (Netscape, the space-separated Netscape export, or EditThisCookie JSON) into ~/.pi-harness-runtime/cookies/ — the runtime normalizes it for you. Or run `bun packages/auth/src/run-minimax-auth.ts auth`.",
8828
9229
  "warning",
8829
9230
  );
8830
9231
  return;
8831
9232
  }
8832
9233
  ctx.ui.notify("Fetching quota from MiniMax console...", "info");
8833
- const refreshed = await autoFetchQuota();
8834
- ctx.ui.notify(
8835
- refreshed
8836
- ? "Quota refreshed. Run `/usage` to see updated status."
8837
- : "Quota refresh skipped. Check cookie validity or MiniMax auth profile, then run `/usage` again.",
8838
- "info",
8839
- );
9234
+ const outcome = await quotaRefresh.request("usage-refresh");
9235
+ if (outcome.ok) {
9236
+ const via =
9237
+ outcome.source === "browser-profile"
9238
+ ? "the browser profile"
9239
+ : "the imported cookie cache";
9240
+ ctx.ui.notify(
9241
+ `Quota refreshed via ${via}. Run \`/usage\` to see updated status.`,
9242
+ "info",
9243
+ );
9244
+ return;
9245
+ }
9246
+ // The failure names what failed: the import, the authentication
9247
+ // or the provider. It never carries a credential.
9248
+ const reason =
9249
+ outcome.reason ??
9250
+ "the provider did not answer with a quota reading";
9251
+ const via =
9252
+ outcome.source === "cookie-cache"
9253
+ ? "the imported cookie cache"
9254
+ : outcome.source === "browser-profile"
9255
+ ? "the browser profile"
9256
+ : "no credential";
9257
+ ctx.ui.notify(`Quota refresh failed via ${via}: ${reason}`, "warning");
9258
+ if (source.stage === "discovered" && !browserProfile) {
9259
+ ctx.ui.notify(
9260
+ "The cookie file was found but not imported. Check the harness log for the reason, then run `/usage-refresh` again.",
9261
+ "warning",
9262
+ );
9263
+ }
8840
9264
  },
8841
9265
  });
8842
9266
 
@@ -8908,7 +9332,7 @@ issue is not authorized work of the current request).
8908
9332
  footerSetStatus,
8909
9333
  tracker,
8910
9334
  mirrorStore,
8911
- hasCookieSource,
9335
+ cookieSourceState,
8912
9336
  () => lastActiveProvider,
8913
9337
  );
8914
9338
  } catch (e) {
@@ -9369,7 +9793,7 @@ issue is not authorized work of the current request).
9369
9793
  footerSetStatus,
9370
9794
  tracker,
9371
9795
  mirrorStore,
9372
- hasCookieSource,
9796
+ cookieSourceState,
9373
9797
  () => lastActiveProvider,
9374
9798
  );
9375
9799
 
@@ -9453,12 +9877,15 @@ issue is not authorized work of the current request).
9453
9877
  footerSetStatus,
9454
9878
  tracker,
9455
9879
  mirrorStore,
9456
- hasCookieSource,
9880
+ cookieSourceState,
9457
9881
  () => lastActiveProvider,
9458
9882
  );
9459
9883
  void maybeAutoFetchQuota(ctx.model?.id ?? null);
9460
9884
  maybeTriggerProactiveCompact(ctx);
9461
9885
  maybeNotifyContextUsage(ctx);
9886
+ // The guard of the exploration speaks at the boundary of the turn:
9887
+ // it asks for a checkpoint and it authorises nothing.
9888
+ void deliverExplorationIntervention();
9462
9889
  // The quality check of the workspace runs after the turn: it never
9463
9890
  // writes and it never steers the session.
9464
9891
  void maybeRunToolingCheck(ctx);
@@ -9491,10 +9918,16 @@ issue is not authorized work of the current request).
9491
9918
  footerSetStatus,
9492
9919
  tracker,
9493
9920
  mirrorStore,
9494
- hasCookieSource,
9921
+ cookieSourceState,
9495
9922
  () => lastActiveProvider,
9496
9923
  );
9497
9924
 
9925
+ // The checkpoint of the exploration is saved before the compaction,
9926
+ // so the summary of the context and the record of what was read are
9927
+ // two separate things. The compaction does not reset the budget of
9928
+ // the request.
9929
+ explorationGuard?.saveCheckpoint();
9930
+
9498
9931
  const forceOutputLimitResume = pendingOutputLimitResumeAfterCompact;
9499
9932
  pendingOutputLimitResumeAfterCompact = false;
9500
9933
 
@@ -9529,7 +9962,17 @@ issue is not authorized work of the current request).
9529
9962
  "the compaction continues the turn",
9530
9963
  );
9531
9964
  // pi.dev expects the literal "resume" command to continue after compaction.
9532
- await queueAutoResume("post-compact", "resume", "followUp");
9965
+ // The checkpoint of the exploration rides along, so the agent reuses
9966
+ // the findings instead of reading the same files again. The text
9967
+ // authorises nothing: it asks, it does not instruct.
9968
+ const explorationContinuation = explorationGuard?.continuationAfterCompaction();
9969
+ await queueAutoResume(
9970
+ "post-compact",
9971
+ explorationContinuation
9972
+ ? `resume\n\n${explorationContinuation}`
9973
+ : "resume",
9974
+ "followUp",
9975
+ );
9533
9976
  });
9534
9977
 
9535
9978
  // The compaction failed. A compaction that fails with the overload of
@@ -9588,7 +10031,7 @@ issue is not authorized work of the current request).
9588
10031
  footerSetStatus,
9589
10032
  tracker,
9590
10033
  mirrorStore,
9591
- hasCookieSource,
10034
+ cookieSourceState,
9592
10035
  () => lastActiveProvider,
9593
10036
  );
9594
10037
  }
@@ -9697,6 +10140,48 @@ issue is not authorized work of the current request).
9697
10140
  }
9698
10141
  }
9699
10142
 
10143
+ /**
10144
+ * Deliver the intervention of the exploration guard.
10145
+ *
10146
+ * The turn end is the safe boundary: the agent is between turns, so a
10147
+ * message here does not interrupt a tool call and does not race another
10148
+ * tool. The guard speaks at most three times in a request, so a request
10149
+ * that ignored the warnings is not nagged.
10150
+ *
10151
+ * The message asks for a checkpoint and it authorises nothing: it never
10152
+ * commits, never pushes, never builds and never starts another request.
10153
+ */
10154
+ async function deliverExplorationIntervention(): Promise<void> {
10155
+ const pending = explorationGuard?.takePending();
10156
+ 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
+ },
10169
+ },
10170
+ { deliverAs: "followUp", triggerTurn: true },
10171
+ );
10172
+ logToFile(
10173
+ "[exploration-guard]",
10174
+ `The guard spoke after ${pending.state.readCount} reads: ${pending.kind}`,
10175
+ );
10176
+ } catch (error) {
10177
+ logToFile(
10178
+ "[exploration-guard]",
10179
+ "the intervention could not be delivered:",
10180
+ oneLineError(error),
10181
+ );
10182
+ }
10183
+ }
10184
+
9700
10185
  function maybeTriggerProactiveCompact(ctx: ExtensionContext): void {
9701
10186
  if (proactiveCompactInFlight) {
9702
10187
  return;
@@ -9753,7 +10238,7 @@ function refreshFooterStatus(
9753
10238
  setStatus: (key: string, value: string) => void,
9754
10239
  tracker: UsageTracker,
9755
10240
  mirrorStore: MirrorStore,
9756
- hasCookieSource: () => boolean,
10241
+ cookieSourceState: () => FooterQuotaSource,
9757
10242
  getActiveProvider: () => ProviderId | null = () => null,
9758
10243
  ) {
9759
10244
  const nowMs = Date.now();
@@ -9764,7 +10249,13 @@ function refreshFooterStatus(
9764
10249
  // mirror ? JSON.stringify(mirror) : null,
9765
10250
  // );
9766
10251
  const freshness = mirrorStore.freshness(mirror, nowMs);
9767
- const statusValue = buildFooterStatusValue(local, mirror, freshness, hasCookieSource(), provider);
10252
+ const statusValue = buildFooterStatusValue(
10253
+ local,
10254
+ mirror,
10255
+ freshness,
10256
+ cookieSourceState(),
10257
+ provider,
10258
+ );
9768
10259
  // Prepend harness version so it shows in the footer during startup
9769
10260
  setStatus(
9770
10261
  "harness-runtime",
@@ -9775,6 +10266,33 @@ function refreshFooterStatus(
9775
10266
  // Pi renders every status value on ONE shared line, so the harness footer
9776
10267
  // (see installHarnessFooter) renders it on a dedicated row instead.
9777
10268
  setWorkspaceEnvStatus(setStatus);
10269
+
10270
+ // The exploration of the request is published under its own status key.
10271
+ // The numbers describe the reads, never what the agent understood.
10272
+ setExplorationStatus(setStatus);
10273
+ }
10274
+
10275
+ /**
10276
+ * Publish the status of the exploration of the request.
10277
+ *
10278
+ * The status is passive: it shows what was observed and it never steers the
10279
+ * session. A guard that cannot read its own state says so instead of
10280
+ * showing a number it does not know.
10281
+ */
10282
+ function setExplorationStatus(
10283
+ setStatus: (key: string, value: string) => void,
10284
+ ): void {
10285
+ try {
10286
+ const status = explorationGuard?.status();
10287
+ if (!status) return;
10288
+ setStatus("harness-exploration", status);
10289
+ } catch (error) {
10290
+ logToFile(
10291
+ "[exploration-guard]",
10292
+ "the status could not be published:",
10293
+ oneLineError(error),
10294
+ );
10295
+ }
9778
10296
  }
9779
10297
 
9780
10298
  /**