pi-harness-runtime 1.1.506 → 1.1.508

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 (88) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/harness/auto-resume-marker.ts +177 -0
  3. package/harness/provider-quota-reset.ts +53 -19
  4. package/harness/provider-recovery-runtime.ts +20 -0
  5. package/harness/quota-capture.ts +150 -0
  6. package/harness/quota-low-remaining.ts +75 -0
  7. package/harness/quota-reset-duration.ts +87 -0
  8. package/harness/quota-threshold.ts +117 -0
  9. package/harness/resume-scope.ts +85 -0
  10. package/harness/scope-expansion-runtime.ts +337 -0
  11. package/harness/scope-expansion.ts +512 -0
  12. package/index.ts +608 -14
  13. package/mirror.ts +4 -0
  14. package/package.json +1 -1
  15. package/packages/agent-policy/package.json +1 -1
  16. package/packages/auth/package.json +1 -1
  17. package/packages/autonomous-runtime/package.json +1 -1
  18. package/packages/checkpoint/package.json +1 -1
  19. package/packages/clipboard/package.json +1 -1
  20. package/packages/codex-watcher/package.json +1 -1
  21. package/packages/config-capture/package.json +1 -1
  22. package/packages/contracts/package.json +1 -1
  23. package/packages/cookie-sanitizer/package.json +1 -1
  24. package/packages/evaluation-engine/package.json +1 -1
  25. package/packages/event-bus/package.json +1 -1
  26. package/packages/event-store/package.json +1 -1
  27. package/packages/experience-replay/package.json +1 -1
  28. package/packages/file-copy-helper/package.json +1 -1
  29. package/packages/intent-analyzer/package.json +1 -1
  30. package/packages/jev-judge/package.json +1 -1
  31. package/packages/knowledge-retrieval/package.json +1 -1
  32. package/packages/learning-engine/package.json +1 -1
  33. package/packages/logging/package.json +1 -1
  34. package/packages/memory-engine/package.json +1 -1
  35. package/packages/notification/dist/adapters/detail-format.d.ts +5 -2
  36. package/packages/notification/dist/adapters/detail-format.d.ts.map +1 -1
  37. package/packages/notification/dist/adapters/detail-format.js +29 -0
  38. package/packages/notification/dist/adapters/detail-format.js.map +1 -1
  39. package/packages/notification/dist/adapters/email-adapter.d.ts.map +1 -1
  40. package/packages/notification/dist/adapters/email-adapter.js +3 -0
  41. package/packages/notification/dist/adapters/email-adapter.js.map +1 -1
  42. package/packages/notification/dist/adapters/line-adapter.d.ts.map +1 -1
  43. package/packages/notification/dist/adapters/line-adapter.js +3 -0
  44. package/packages/notification/dist/adapters/line-adapter.js.map +1 -1
  45. package/packages/notification/dist/adapters/ntfy-adapter.d.ts.map +1 -1
  46. package/packages/notification/dist/adapters/ntfy-adapter.js +3 -0
  47. package/packages/notification/dist/adapters/ntfy-adapter.js.map +1 -1
  48. package/packages/notification/dist/adapters/telegram-adapter.d.ts +0 -1
  49. package/packages/notification/dist/adapters/telegram-adapter.d.ts.map +1 -1
  50. package/packages/notification/dist/adapters/telegram-adapter.js +3 -3
  51. package/packages/notification/dist/adapters/telegram-adapter.js.map +1 -1
  52. package/packages/notification/dist/notification-center.d.ts.map +1 -1
  53. package/packages/notification/dist/notification-center.js +24 -0
  54. package/packages/notification/dist/notification-center.js.map +1 -1
  55. package/packages/notification/dist/notification-policy.d.ts.map +1 -1
  56. package/packages/notification/dist/notification-policy.js +3 -0
  57. package/packages/notification/dist/notification-policy.js.map +1 -1
  58. package/packages/notification/dist/types.d.ts +23 -1
  59. package/packages/notification/dist/types.d.ts.map +1 -1
  60. package/packages/notification/package.json +1 -1
  61. package/packages/notification/src/adapters/detail-format.ts +45 -2
  62. package/packages/notification/src/adapters/email-adapter.ts +3 -0
  63. package/packages/notification/src/adapters/line-adapter.ts +3 -0
  64. package/packages/notification/src/adapters/ntfy-adapter.ts +3 -0
  65. package/packages/notification/src/adapters/telegram-adapter.ts +3 -4
  66. package/packages/notification/src/notification-center.ts +28 -0
  67. package/packages/notification/src/notification-policy.ts +3 -0
  68. package/packages/notification/src/types.ts +25 -0
  69. package/packages/paperclip-integration/package.json +1 -1
  70. package/packages/performance-optimizer/package.json +1 -1
  71. package/packages/privilege-broker/package.json +1 -1
  72. package/packages/prompt-compiler/package.json +1 -1
  73. package/packages/providers/package.json +1 -1
  74. package/packages/qdrant-skills/package.json +1 -1
  75. package/packages/quota-manager/package.json +1 -1
  76. package/packages/relay/package.json +1 -1
  77. package/packages/skill-mcp-client/package.json +1 -1
  78. package/packages/skills/package.json +1 -1
  79. package/packages/todo-bd-sync/package.json +1 -1
  80. package/packages/token-estimation/package.json +1 -1
  81. package/packages/tooling-preference/package.json +1 -1
  82. package/packages/trajectory/package.json +1 -1
  83. package/packages/tui/package.json +1 -1
  84. package/packages/two-phase-review/package.json +1 -1
  85. package/packages/types/package.json +1 -1
  86. package/packages/webmcp-tester/package.json +1 -1
  87. package/packages/wiki/package.json +1 -1
  88. package/packages/write-review/package.json +1 -1
package/index.ts CHANGED
@@ -86,6 +86,34 @@ import {
86
86
  } from "./harness/pi-retry-policy.ts";
87
87
  import { ProviderRecoveryRuntime } from "./harness/provider-recovery-runtime.ts";
88
88
  import { confirmedQuotaReset } from "./harness/provider-quota-reset.ts";
89
+ import { resetEpochFromDuration } from "./harness/quota-reset-duration.ts";
90
+ import { QuotaCaptureController } from "./harness/quota-capture.ts";
91
+ import { QuotaLowRemainingTracker } from "./harness/quota-low-remaining.ts";
92
+ import { remainingPctFromUsedPct } from "./harness/quota-threshold.ts";
93
+ import {
94
+ decideResumeScope,
95
+ RESUME_SCOPE_RULE,
96
+ type ResumeWorkState,
97
+ } from "./harness/resume-scope.ts";
98
+ import {
99
+ buildAutoResumeMessage,
100
+ autoResumeDetails,
101
+ findAutoResumeIndex,
102
+ isAutoResumeMessage,
103
+ neutralizeAutoResume,
104
+ } from "./harness/auto-resume-marker.ts";
105
+ import {
106
+ ScopeExpansionRuntime,
107
+ type HumanScopeOutcome,
108
+ } from "./harness/scope-expansion-runtime.ts";
109
+ import {
110
+ MAX_SCOPE_CANDIDATES,
111
+ SCOPE_EXPANSION_WINDOW_MS,
112
+ scopeProposalMessage,
113
+ type ScopeCandidate,
114
+ type ScopeDecision,
115
+ type ScopeProposal,
116
+ } from "./harness/scope-expansion.ts";
89
117
  import type { ProviderFailure } from "./harness/provider-failure.ts";
90
118
  import {
91
119
  createProviderRecoveryController,
@@ -130,6 +158,7 @@ import {
130
158
  } from "./packages/quota-manager/src/tui-usage-monitor.ts";
131
159
  import { QuotaManager } from "./packages/quota-manager/src/quota-manager.ts";
132
160
  import { buildFooterStatusValue } from "./footer-status.ts";
161
+ import { getProviderLabel } from "./packages/types/src/ai-providers.ts";
133
162
  import { registerGithubLoginCommand } from "./packages/clipboard/dist/src/github-login.js";
134
163
  import {
135
164
  MAX_PROACTIVE_COMPACT_FAILURES,
@@ -183,10 +212,23 @@ import { centralInfo, initCentralLogging, redactText } from "./packages/logging/
183
212
  * Get tasks from bd (beads) for Jev decision context.
184
213
  * Returns { completed, remaining } arrays of task descriptions.
185
214
  */
215
+ /**
216
+ * One issue of the backlog, with the exact id.
217
+ *
218
+ * The exact id is what a proposal names. A title is not an identity: two
219
+ * issues can carry the same title, and only the id tells them apart.
220
+ */
221
+ interface BacklogIssue {
222
+ id: string;
223
+ title: string;
224
+ status?: string;
225
+ }
226
+
186
227
  async function getTaskContext(): Promise<{
187
228
  completed: string[];
188
229
  remaining: string[];
189
230
  total: number;
231
+ issues: BacklogIssue[];
190
232
  }> {
191
233
  try {
192
234
  const { execSync } = await import("node:child_process");
@@ -195,10 +237,15 @@ async function getTaskContext(): Promise<{
195
237
  encoding: "utf8",
196
238
  timeout: 5000,
197
239
  });
198
- const tasks = JSON.parse(output) as Array<{ title?: string; status?: string }>;
240
+ const tasks = JSON.parse(output) as Array<{
241
+ id?: string;
242
+ title?: string;
243
+ status?: string;
244
+ }>;
199
245
 
200
246
  const completed: string[] = [];
201
247
  const remaining: string[] = [];
248
+ const issues: BacklogIssue[] = [];
202
249
 
203
250
  for (const task of tasks ?? []) {
204
251
  if (!task.title) continue;
@@ -206,6 +253,11 @@ async function getTaskContext(): Promise<{
206
253
  completed.push(task.title);
207
254
  } else {
208
255
  remaining.push(task.title);
256
+ // An issue without an id cannot be proposed: a proposal
257
+ // names exact ids.
258
+ if (typeof task.id === "string" && task.id) {
259
+ issues.push({ id: task.id, title: task.title, status: task.status });
260
+ }
209
261
  }
210
262
  }
211
263
 
@@ -213,10 +265,11 @@ async function getTaskContext(): Promise<{
213
265
  completed,
214
266
  remaining,
215
267
  total: completed.length + remaining.length,
268
+ issues,
216
269
  };
217
270
  } catch {
218
271
  // bd not available or error - return empty context
219
- return { completed: [], remaining: [], total: 0 };
272
+ return { completed: [], remaining: [], total: 0, issues: [] };
220
273
  }
221
274
  }
222
275
 
@@ -616,8 +669,72 @@ const sharedState = {
616
669
  delegationHarness: null as any,
617
670
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
618
671
  workspaceEnvMessage: null as string | null,
672
+ // The state of the work of the request that is running. The automatic
673
+ // resume reads it to know whether the work of the request remains.
674
+ workContext: null as unknown,
675
+ // The runtime of the scope expansion: the backlog that could follow a
676
+ // finished request is proposed, and only the approved issues start.
677
+ scopeRuntime: null as ScopeExpansionRuntime | null,
619
678
  };
620
679
 
680
+ /**
681
+ * Was the suppressed resume of this request already reported?
682
+ *
683
+ * The report happens once per request: a suppressed resume is not an event
684
+ * the user has to read again and again.
685
+ */
686
+ let suppressedResumeReported = false;
687
+
688
+ /** The number of the resumes that the harness queued in this session. */
689
+ let resumeNonceCounter = 0;
690
+
691
+ /**
692
+ * A nonce that tells one resume from another.
693
+ *
694
+ * The nonce is part of the marker of the resume, so a log line names the
695
+ * exact resume that was queued.
696
+ */
697
+ function nextResumeNonce(): string {
698
+ resumeNonceCounter += 1;
699
+ return `${Date.now().toString(36)}-${resumeNonceCounter}`;
700
+ }
701
+
702
+ /**
703
+ * Report that an automatic resume was suppressed.
704
+ *
705
+ * The work of the request is complete, so the resume is not sent and the
706
+ * agent is not told to look for other work. The user learns about it once.
707
+ */
708
+ function reportSuppressedResume(report: string | undefined): void {
709
+ if (!report || suppressedResumeReported) return;
710
+ suppressedResumeReported = true;
711
+ logToFile("[resume-scope]", report);
712
+ void nc("Info", {
713
+ jobId: "resume-scope-complete",
714
+ requirement: report,
715
+ });
716
+ }
717
+
718
+ /**
719
+ * The state of the work of the request that is running.
720
+ *
721
+ * An automatic resume continues the request that is running, so it has to
722
+ * know whether that request still has work. An unknown state is not a
723
+ * completion: the uncertainty is preserved and the resume goes on.
724
+ */
725
+ async function currentRequestWorkState(): Promise<ResumeWorkState> {
726
+ const accessor = sharedState.workContext as
727
+ | null
728
+ | (() => Promise<{ work: ResumeWorkState; scope: string[] }>);
729
+ if (typeof accessor !== "function") return "unknown";
730
+ try {
731
+ const context = await accessor();
732
+ return context.work;
733
+ } catch {
734
+ return "unknown";
735
+ }
736
+ }
737
+
621
738
  /**
622
739
  * The scope of the request that is running.
623
740
  *
@@ -677,6 +794,63 @@ const requestScopeTracker = new RequestScopeTracker({
677
794
  */
678
795
  function beginHumanRequest(): void {
679
796
  requestScopeTracker.begin();
797
+ // A new request of the human has its own report: the completion of the
798
+ // previous one was already reported.
799
+ suppressedResumeReported = false;
800
+ }
801
+
802
+ /**
803
+ * Did a notification reach a channel?
804
+ *
805
+ * A skipped channel - a disabled one - is not a delivery: the human was not
806
+ * told, and work that the human was not told about must not start.
807
+ */
808
+ function deliveryOf(results: unknown): { delivered: boolean; failures: string[] } {
809
+ if (!Array.isArray(results)) {
810
+ return { delivered: false, failures: ["the notification returned no result"] };
811
+ }
812
+ const rows = results as Array<{
813
+ success?: boolean;
814
+ channel?: string;
815
+ error?: string;
816
+ skipped?: boolean;
817
+ }>;
818
+ const reached = rows.filter((row) => row.success && !row.skipped);
819
+ const failures = rows
820
+ .filter((row) => !row.success || row.skipped)
821
+ .map((row) => `${row.channel ?? "channel"}: ${row.error ?? "not delivered"}`);
822
+ return { delivered: reached.length > 0, failures };
823
+ }
824
+
825
+ /**
826
+ * Propose the backlog that could follow a finished request.
827
+ *
828
+ * The proposal names exact ids, and the decision of the human - or of Jev,
829
+ * when the five minutes are over without an answer - decides what starts.
830
+ * Nothing of the backlog starts without that decision.
831
+ */
832
+ async function proposeScopeExpansion(): Promise<void> {
833
+ const runtime = sharedState.scopeRuntime;
834
+ if (!runtime) return;
835
+ // One proposal waits for an answer: a second one would ask the same
836
+ // human twice about the same backlog.
837
+ if (runtime.open.length > 0) return;
838
+ const context = await getTaskContext().catch(() => null);
839
+ if (!context || context.issues.length === 0) return;
840
+ const candidates: ScopeCandidate[] = context.issues
841
+ .slice(0, MAX_SCOPE_CANDIDATES)
842
+ .map((issue) => ({ id: issue.id, title: issue.title }));
843
+ const generation = requestScopeTracker.generation;
844
+ await runtime.propose({
845
+ requestId: `request-${generation}`,
846
+ workspace: _piSessionCwd || process.cwd(),
847
+ generation,
848
+ candidates,
849
+ scope: `work on ${candidates.length} issue(s) of the backlog of the session`,
850
+ validation: "the tests of the repository and the closing of every named issue",
851
+ risks: ["the work was not asked for"],
852
+ choices: ["run the named issues", "keep the backlog closed"],
853
+ });
680
854
  }
681
855
 
682
856
  /**
@@ -710,6 +884,26 @@ function applyChannelApproval(
710
884
  logToFile("[Approval]", `${channel} decision '${action}' applied to ${requestId}`);
711
885
  logQuestionTransition(requestId, "answered", `${channel}:${action}`);
712
886
 
887
+ // A question of a scope proposal is not a question of the work of the
888
+ // request: it asks whether the backlog may follow. The answer decides
889
+ // the proposal, and the work of the request stays what it was.
890
+ const scopeProposal = sharedState.scopeRuntime?.proposalForQuestion(requestId);
891
+ if (scopeProposal) {
892
+ const outcome: HumanScopeOutcome = result.resolution === "yes" ? "approve" : "reject";
893
+ void sharedState.scopeRuntime
894
+ ?.answerByQuestion(requestId, outcome, `${channel}:${action}`)
895
+ .then((executed) => {
896
+ logToFile(
897
+ "[scope-expansion]",
898
+ `The proposal ${scopeProposal.id} was answered (${outcome}): started=${executed.started}`,
899
+ );
900
+ })
901
+ .catch((error) => {
902
+ logToFile("[scope-expansion]", "The answer of the proposal failed:", String(error));
903
+ });
904
+ return true;
905
+ }
906
+
713
907
  // The question is answered, so the wait is over. The wait state is only
714
908
  // cleared after a successful resolution.
715
909
  // The controller owns the wait: the answer ends it, and an evaluation
@@ -1438,6 +1632,10 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
1438
1632
  }
1439
1633
  }
1440
1634
 
1635
+ // The automatic resume reads the state of the work from here: the
1636
+ // guard belongs to the code, not to the judge.
1637
+ sharedState.workContext = currentWorkContext;
1638
+
1441
1639
  /**
1442
1640
  * The state of the work of the current request.
1443
1641
  */
@@ -2820,8 +3018,182 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2820
3018
  let validationLedger: import("./packages/jev-judge/dist/validation-ledger.js").ValidationLedger | null = null;
2821
3019
 
2822
3020
  // Create controller on session_start with proper dispatch callback
3021
+ /**
3022
+ * The runtime of the scope expansion.
3023
+ *
3024
+ * The backlog of the session is not work of the request that just
3025
+ * finished. When the request is done, the runtime proposes the exact
3026
+ * issues that could follow, the human decides - or Jev decides when
3027
+ * the five minutes are over - and only the approved ids start. The
3028
+ * decision is delivered before the work starts, and a decision that
3029
+ * reaches nobody leaves the work stopped.
3030
+ */
3031
+ function createScopeExpansionRuntime(): ScopeExpansionRuntime {
3032
+ return new ScopeExpansionRuntime({
3033
+ now: () => Date.now(),
3034
+ deliver: async (text, meta) => {
3035
+ const center = _nc?.center as NcCenter | undefined;
3036
+ if (!center) {
3037
+ return { delivered: false, failures: ["no notification center"] };
3038
+ }
3039
+ const proposal = sharedState.scopeRuntime?.get(meta.id);
3040
+ try {
3041
+ if (meta.kind === "proposal") {
3042
+ const results = await center.notifyWithApproval(
3043
+ "ScopeProposal" as never,
3044
+ {
3045
+ jobId: meta.id,
3046
+ requirement: text,
3047
+ questionId: meta.questionId,
3048
+ questionKind: "approval",
3049
+ scopeIds: proposal?.proposedIds,
3050
+ scopeDeadline: proposal
3051
+ ? new Date(proposal.deadlineAt).toISOString()
3052
+ : undefined,
3053
+ } as never,
3054
+ { approveLabel: "Run these", rejectLabel: "Keep it closed" },
3055
+ );
3056
+ return deliveryOf(results);
3057
+ }
3058
+ const results = await center.notify("ScopeDecision" as never, {
3059
+ jobId: meta.id,
3060
+ requirement: text,
3061
+ scopeIds: proposal?.proposedIds,
3062
+ } as never);
3063
+ return deliveryOf(results);
3064
+ } catch (error) {
3065
+ return { delivered: false, failures: [String(error)] };
3066
+ }
3067
+ },
3068
+ judge: async (proposal) => {
3069
+ const judge = new mod.AutoContinueJudge({
3070
+ providers: jevProviders,
3071
+ proceedThreshold: 0.7,
3072
+ maxWaitMinutes: 30,
3073
+ });
3074
+ const waitedMinutes = Math.max(
3075
+ 0,
3076
+ Math.round((Date.now() - proposal.createdAt) / 60_000),
3077
+ );
3078
+ const question = scopeProposalMessage(proposal);
3079
+ const decision = await judge.decide({
3080
+ completedTasks: [],
3081
+ remainingTasks: proposal.proposedIds,
3082
+ totalTasks: proposal.proposedIds.length,
3083
+ waitTimeMinutes: waitedMinutes,
3084
+ userResponded: false,
3085
+ sessionStartTime: new Date(proposal.createdAt),
3086
+ questionAskedAt: new Date(proposal.createdAt),
3087
+ context: {
3088
+ question: {
3089
+ requestId: `scope-question-${proposal.id}`,
3090
+ text: question,
3091
+ kind: "approval",
3092
+ askType: "approval",
3093
+ alternatives: proposal.choices,
3094
+ contextText: question,
3095
+ proposedAction: proposal.scope,
3096
+ consequence: "the named issues become work of this session",
3097
+ requiresExplicitAuthorization: false,
3098
+ destructive: false,
3099
+ external: false,
3100
+ reversible: true,
3101
+ },
3102
+ currentTask: proposal.scope,
3103
+ totalTasks: proposal.proposedIds.length,
3104
+ nextTasks: proposal.proposedIds,
3105
+ waitedMinutes,
3106
+ deadlineMinutes: Math.round(SCOPE_EXPANSION_WINDOW_MS / 60_000),
3107
+ },
3108
+ });
3109
+ const outcome: ScopeDecision["outcome"] =
3110
+ decision.outcome === "approve" || decision.outcome === "proceed_with_caution"
3111
+ ? "approve"
3112
+ : decision.outcome === "reject"
3113
+ ? "reject"
3114
+ : "wait";
3115
+ return {
3116
+ outcome,
3117
+ selectedIds: outcome === "approve" ? [...proposal.proposedIds] : [],
3118
+ reasoning: decision.reasoning,
3119
+ source: "jev",
3120
+ failed: decision.evaluationError !== undefined,
3121
+ };
3122
+ },
3123
+ dispatch: (proposal, ids) => {
3124
+ // The approval starts new work: it begins a new scope, so
3125
+ // the todos of the finished request stay its history.
3126
+ beginHumanRequest();
3127
+ const lines = ids.map((id) => `- ${id}`).join("\n");
3128
+ const message = [
3129
+ "The human approved the following issues of the backlog.",
3130
+ "Work on exactly these ids and stop when they are done:",
3131
+ lines,
3132
+ ].join("\n");
3133
+ void (async () => {
3134
+ try {
3135
+ await pi.sendUserMessage(message, { deliverAs: "steer" });
3136
+ } catch (error) {
3137
+ logToFile(
3138
+ "[scope-expansion]",
3139
+ `The dispatch of the proposal ${proposal.id} failed:`,
3140
+ String(error),
3141
+ );
3142
+ }
3143
+ })();
3144
+ },
3145
+ registerQuestion: (proposal) => {
3146
+ const question = pqController.createQuestion({
3147
+ text: scopeProposalMessage(proposal),
3148
+ sessionId: _sessionId,
3149
+ workspacePath: _piSessionCwd || "/",
3150
+ jobId: proposal.id,
3151
+ kind: "approval",
3152
+ askType: "approval",
3153
+ alternatives: proposal.choices,
3154
+ contextText: scopeProposalMessage(proposal),
3155
+ risk: {
3156
+ requiresExplicitAuthorization: false,
3157
+ destructive: false,
3158
+ reversible: true,
3159
+ external: false,
3160
+ },
3161
+ relevance:
3162
+ // The question is asked after the work of the request
3163
+ // is done: it is not obsolete, and it does not wait
3164
+ // for an automatic decision of the request.
3165
+ "final-request",
3166
+ });
3167
+ return question.requestId;
3168
+ },
3169
+ cancelQuestion: (questionId) => {
3170
+ pqController.expireByTimeout?.(questionId, "the proposal was not delivered");
3171
+ },
3172
+ latestHumanDecision: (proposal) => {
3173
+ const questionId = sharedState.scopeRuntime?.questionIdFor(proposal.id);
3174
+ if (!questionId) return undefined;
3175
+ const resolution = pqController.getQuestion(questionId)?.resolution;
3176
+ if (resolution === "yes") return "approve";
3177
+ if (resolution === "no") return "reject";
3178
+ return undefined;
3179
+ },
3180
+ groupFinished: async (_proposal: ScopeProposal, ids) => {
3181
+ const context = await getTaskContext().catch(() => null);
3182
+ if (!context) return false;
3183
+ const open = new Set(context.issues.map((issue) => issue.id));
3184
+ return ids.every((id) => !open.has(id));
3185
+ },
3186
+ log: (message) => logToFile("[scope-expansion]", message),
3187
+ });
3188
+ }
3189
+
2823
3190
  pi.on("session_start", async (_event, ctx) => {
2824
3191
  try {
3192
+ // The runtime of the scope expansion belongs to the session:
3193
+ // a session that starts has no open proposal, and a session
3194
+ // that ends leaves none behind.
3195
+ sharedState.scopeRuntime?.dispose();
3196
+ sharedState.scopeRuntime = createScopeExpansionRuntime();
2825
3197
  const { TodoContinuationController } = await import("./packages/jev-judge/dist/continuation-controller.js");
2826
3198
  const { ValidationLedger } = await import("./packages/jev-judge/dist/validation-ledger.js");
2827
3199
  // The ledger records which validation tier ran. The controller
@@ -2885,6 +3257,10 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2885
3257
  todoContinuationHandle = null;
2886
3258
  sharedState.todoContinuationController = null;
2887
3259
  sharedState.validationLedger = null;
3260
+ // The proposal of a scope belongs to the session that is ending:
3261
+ // its countdown does not survive it.
3262
+ sharedState.scopeRuntime?.dispose();
3263
+ sharedState.scopeRuntime = null;
2888
3264
  // The scope belongs to the session that is ending.
2889
3265
  requestScopeTracker.reset();
2890
3266
  });
@@ -3091,6 +3467,12 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3091
3467
  // is stale must run before the open question stops the handler.
3092
3468
  await reconcileObsoleteQuestion();
3093
3469
 
3470
+ // The work of an authorized group may have finished: the group
3471
+ // is done when every issue of it is closed. The session stops
3472
+ // again with it: the approval of that group does not authorize
3473
+ // the next one.
3474
+ await sharedState.scopeRuntime?.checkGroupFinished();
3475
+
3094
3476
  // Don't continue if user is waiting for response, and do not
3095
3477
  // continue behind a question that is still open: the work waits
3096
3478
  // for the answer, also when the wait itself is over.
@@ -3200,6 +3582,12 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3200
3582
  jobId: `done-${reason.replace(/\s+/g, "-")}`,
3201
3583
  requirement: message,
3202
3584
  }).catch((e) => logToFile("[Notification]", "ReadyForClient failed:", String(e)));
3585
+
3586
+ // The request of the human is done. The backlog of the
3587
+ // session is not work of it: the exact issues that
3588
+ // could follow are proposed, and only the approved
3589
+ // ids start.
3590
+ await proposeScopeExpansion();
3203
3591
  }
3204
3592
  }
3205
3593
  }
@@ -5845,17 +6233,29 @@ function isOutputLimitResumePromptMessage(message: {
5845
6233
  role?: string;
5846
6234
  content?: unknown;
5847
6235
  }): boolean {
6236
+ // A resume of the harness carries the marker, and the prompt is its
6237
+ // content: it is the same message as before.
6238
+ if (isAutoResumeMessage(message)) {
6239
+ return isOutputLimitResumePromptText(message.content);
6240
+ }
5848
6241
  if (message.role !== "user") {
5849
6242
  return false;
5850
6243
  }
5851
- if (typeof message.content === "string") {
5852
- return message.content === OUTPUT_LIMIT_RESUME_PROMPT;
6244
+ return isOutputLimitResumePromptText(message.content);
6245
+ }
6246
+
6247
+ /**
6248
+ * Does this content carry the prompt of the output limit?
6249
+ */
6250
+ function isOutputLimitResumePromptText(content: unknown): boolean {
6251
+ if (typeof content === "string") {
6252
+ return content === OUTPUT_LIMIT_RESUME_PROMPT;
5853
6253
  }
5854
- if (!Array.isArray(message.content)) {
6254
+ if (!Array.isArray(content)) {
5855
6255
  return false;
5856
6256
  }
5857
6257
  return (
5858
- message.content
6258
+ content
5859
6259
  .filter(
5860
6260
  (part): part is { type: "text"; text: string } =>
5861
6261
  part &&
@@ -6684,6 +7084,9 @@ After completing ANY task or unit of work:
6684
7084
  3. Only stop and report progress when ALL tasks are completed (or genuinely blocked)
6685
7085
  4. If blocked (waiting on user input, CI, external dependency), THEN ask
6686
7086
 
7087
+ **The scope of the work:** the next task is the next task **of this request**.
7088
+ Pending issues in bd or another backlog are not pending work of this request.
7089
+
6687
7090
  **Anti-pattern (WRONG):**
6688
7091
  > [Task 1 done] → stops → "Done! What would you like me to do next?"
6689
7092
 
@@ -6691,12 +7094,15 @@ After completing ANY task or unit of work:
6691
7094
  > [Task 1 done] → picks Task 2 → works → Task 3 → ... → all done → report
6692
7095
 
6693
7096
  This applies to EVERY turn. Every time you finish something, check todos first.
7097
+
7098
+ ${RESUME_SCOPE_RULE}
6694
7099
  `;
6695
7100
 
6696
7101
  const COMMIT_BUILD_CHECKLIST = `
6697
7102
 
6698
7103
  BEFORE committing code or triggering builds, ALWAYS check:
6699
- 1. Run \`bd ready\` to see pending **bd issues**
7104
+ 1. Run \`bd ready\` to see pending **bd issues** (bookkeeping only — a pending
7105
+ bd issue is not authorized work of the current request)
6700
7106
  2. Mark completed issues with \`bd close <id> --reason "Done"\`
6701
7107
  3. Acknowledge pending issues before proceeding
6702
7108
  4. Never commit/build without acknowledging pending bd issues
@@ -6795,7 +7201,8 @@ Before running a build, ensure you update the current task status:
6795
7201
  2. If tracking in **bd issues**: use \`bd update <id> --status in_progress\`
6796
7202
  3. After build succeeds: mark completed in the appropriate tracker
6797
7203
 
6798
- Run \`bd ready\` to see current bd issues.
7204
+ Run \`bd ready\` to see current bd issues (bookkeeping only — a pending bd
7205
+ issue is not authorized work of the current request).
6799
7206
  `;
6800
7207
 
6801
7208
  // Detect build commands and log reminder (don't modify result.content)
@@ -6862,9 +7269,17 @@ Run \`bd ready\` to see current bd issues.
6862
7269
  sessionBusy: activeExtensionContext?.isIdle?.() === false,
6863
7270
  }),
6864
7271
  resetEvidence: (failure) => applicableResetEvidence(failure),
6865
- quotaResetEvidence: (failure, provider) => confirmedQuotaReset(
6866
- failure, provider, mirrorStore.readProvider(provider.toLowerCase()), Date.now(),
6867
- ),
7272
+ quotaResetEvidence: (failure, provider) => {
7273
+ // A capture that failed means that the row of the mirror is the
7274
+ // old one, and an old row cannot prove a deadline.
7275
+ if (quotaCaptureController.failed(provider)) return undefined;
7276
+ return confirmedQuotaReset(
7277
+ failure,
7278
+ provider,
7279
+ mirrorStore.readProvider(provider.toLowerCase()),
7280
+ Date.now(),
7281
+ );
7282
+ },
6868
7283
  overloadDelayMs: () => getProviderOverloadResumeDelayMs(),
6869
7284
  overloadMaxAttempts: PROVIDER_OVERLOAD_AUTO_RESUME_LIMIT,
6870
7285
  dispatch: async (reason) => {
@@ -6906,7 +7321,7 @@ Run \`bd ready\` to see current bd issues.
6906
7321
 
6907
7322
  // The run settled: the internal retries of Pi are over, so a failure
6908
7323
  // that waited for the boundary is final and the recovery starts now.
6909
- pi.on("agent_settled", (event) => {
7324
+ pi.on("agent_settled", async (event) => {
6910
7325
  // An aborted run is a decision of the user, not a failure of the
6911
7326
  // provider: an automatic resume would fight the user.
6912
7327
  //
@@ -6924,12 +7339,56 @@ Run \`bd ready\` to see current bd issues.
6924
7339
  providerFailureAttemptsInRun = 0;
6925
7340
  return;
6926
7341
  }
7342
+ // A quota failure needs a fresh capture before the recovery picks a
7343
+ // deadline. The capture that the harness has can be hours old, and
7344
+ // a stale capture proves nothing about the reset that is coming.
7345
+ // The capture is not a scheduler: it only refreshes what the
7346
+ // recovery reads.
7347
+ await quotaCaptureController.wait();
6927
7348
  providerRecoveryRuntime?.noteSettled();
6928
7349
  // The run is over: the streak of its failures ends with it, so the
6929
7350
  // next run starts its own count.
6930
7351
  providerFailureAttemptsInRun = 0;
6931
7352
  });
6932
7353
 
7354
+ /**
7355
+ * The guard of a resume that is consumed too late.
7356
+ *
7357
+ * A resume is queued while the request runs. Pi drains the queue one
7358
+ * message at a time, so a resume can be consumed after the request
7359
+ * finished - and a resume of a request that is complete would send the
7360
+ * agent to the backlog, which is not work of that request.
7361
+ *
7362
+ * The public boundary of Pi is the "context" event: it runs before the
7363
+ * provider is called, and the handler may replace the messages. The
7364
+ * marker of the resume is still there at that point - Pi removes it
7365
+ * later, when it converts the messages for the provider.
7366
+ *
7367
+ * The run is not aborted: other work of the session must go on. Only
7368
+ * the resume itself is neutralized.
7369
+ */
7370
+ pi.on("context", async (event) => {
7371
+ const index = findAutoResumeIndex(event.messages);
7372
+ const details =
7373
+ index === -1 ? undefined : autoResumeDetails(event.messages[index]);
7374
+ // A resume of a cut turn continues a turn that was cut off: it is
7375
+ // unfinished by definition and the guard does not apply.
7376
+ if (index === -1 || details?.scope === "turn") {
7377
+ return { messages: event.messages };
7378
+ }
7379
+ const decision = decideResumeScope({
7380
+ work: await currentRequestWorkState(),
7381
+ reason: details?.reason ?? "auto-resume",
7382
+ });
7383
+ if (decision.action !== "suppress") {
7384
+ return { messages: event.messages };
7385
+ }
7386
+ logToFile("[resume-scope]", `Resume neutralized: ${decision.reason}`);
7387
+ return {
7388
+ messages: neutralizeAutoResume(event.messages, index) as typeof event.messages,
7389
+ };
7390
+ });
7391
+
6933
7392
  pi.on("message_end", async (event, ctx) => {
6934
7393
  // The context of the running extension: the resume checks it before
6935
7394
  // it dispatches, so it does not compete with the user.
@@ -7049,6 +7508,14 @@ Run \`bd ready\` to see current bd issues.
7049
7508
  typeof m.errorMessage === "string" ? m.errorMessage : undefined,
7050
7509
  ),
7051
7510
  });
7511
+ // A quota failure needs a fresh capture before the recovery
7512
+ // picks a deadline. The capture runs while Pi retries the
7513
+ // failed turn internally.
7514
+ const quotaCandidate =
7515
+ providerRecoveryRuntime?.pendingQuotaFailure();
7516
+ if (quotaCandidate) {
7517
+ quotaCaptureController.begin(quotaCandidate.provider);
7518
+ }
7052
7519
  } else {
7053
7520
  // No automatic retry can fix this failure: the row says that
7054
7521
  // nothing is scheduled.
@@ -7089,7 +7556,9 @@ Run \`bd ready\` to see current bd issues.
7089
7556
  OUTPUT_LIMIT_CONTINUATION_ID,
7090
7557
  "the output limit continues the turn",
7091
7558
  );
7092
- await queueAutoResume("output-limit", OUTPUT_LIMIT_RESUME_PROMPT, "steer");
7559
+ await queueAutoResume("output-limit", OUTPUT_LIMIT_RESUME_PROMPT, "steer", {
7560
+ scope: "turn",
7561
+ });
7093
7562
  // Emit OutputLimitContinued to Telegram
7094
7563
  await nc("OutputLimitContinued", {
7095
7564
  requirement: "Session output",
@@ -7380,6 +7849,7 @@ Run \`bd ready\` to see current bd issues.
7380
7849
  // JSON.stringify(record),
7381
7850
  // );
7382
7851
  mirrorStore.writeProvider(provider, { ...record, provider });
7852
+ notifyQuotaLowRemaining(provider, record);
7383
7853
  if (footerSetStatus) {
7384
7854
  refreshFooterStatus(
7385
7855
  footerSetStatus,
@@ -7391,6 +7861,43 @@ Run \`bd ready\` to see current bd issues.
7391
7861
  }
7392
7862
  }
7393
7863
 
7864
+ /**
7865
+ * The alert of a low allowance.
7866
+ *
7867
+ * The alert is sent once per crossing: a capture of the same state
7868
+ * again does not send it again, and an allowance that recovers arms it
7869
+ * again. It needs no approval and it costs no attempt of the recovery.
7870
+ */
7871
+ const quotaLowRemainingTracker = new QuotaLowRemainingTracker();
7872
+
7873
+ function notifyQuotaLowRemaining(
7874
+ provider: ProviderId,
7875
+ record: Omit<import("./mirror.js").ProviderMirrorRecord, "provider">,
7876
+ ): void {
7877
+ // No channel, no message: an alert that cannot be sent is not an
7878
+ // alert that was sent.
7879
+ if (!_nc) return;
7880
+ const decision = quotaLowRemainingTracker.observe(
7881
+ provider,
7882
+ record.h5_used_pct,
7883
+ );
7884
+ if (decision !== "notify") return;
7885
+ const remainingPct = remainingPctFromUsedPct(record.h5_used_pct as number);
7886
+ const label = getProviderLabel(provider);
7887
+ const resetAt = record.h5_resets_at_epoch
7888
+ ? new Date(record.h5_resets_at_epoch).toISOString()
7889
+ : record.h5_resets_at;
7890
+ void nc("QuotaLowRemaining", {
7891
+ jobId: `quota-low-${provider}`,
7892
+ requirement: `The 5h quota of ${label} is low`,
7893
+ provider: label,
7894
+ quotaWindow: "5h",
7895
+ remainingPct: Math.round(remainingPct * 10) / 10,
7896
+ ...(resetAt ? { resetAt } : {}),
7897
+ reason: `The 5h window has ${Math.round(remainingPct * 10) / 10}% left`,
7898
+ });
7899
+ }
7900
+
7394
7901
  async function hasBrowserProfileAutoFetchSource(): Promise<boolean> {
7395
7902
  try {
7396
7903
  const { getLiveSessionPath, getStatusPath } = await import(
@@ -7478,13 +7985,26 @@ Run \`bd ready\` to see current bd issues.
7478
7985
  return null;
7479
7986
  }
7480
7987
 
7988
+ // The console writes the remaining time of a window as text. The
7989
+ // mirror needs an absolute moment, and the capture is the anchor
7990
+ // of the text.
7991
+ const observedAt = Date.parse(status.checked_at);
7992
+
7481
7993
  return {
7482
7994
  synced_at: status.checked_at,
7483
7995
  provider: "minimax",
7484
7996
  h5_used_pct: parsed.h5UsedPct,
7485
7997
  h5_resets_at: parsed.h5ResetsAt,
7998
+ h5_resets_at_epoch: resetEpochFromDuration(
7999
+ parsed.h5ResetsAt,
8000
+ observedAt,
8001
+ ),
7486
8002
  weekly_used_pct: parsed.weeklyUsedPct,
7487
8003
  weekly_resets_at: parsed.weeklyResetsAt,
8004
+ weekly_resets_at_epoch: resetEpochFromDuration(
8005
+ parsed.weeklyResetsAt,
8006
+ observedAt,
8007
+ ),
7488
8008
  };
7489
8009
  } catch (error) {
7490
8010
  if (!suppressErrors) {
@@ -7510,8 +8030,10 @@ Run \`bd ready\` to see current bd issues.
7510
8030
  model: profileRecord.model,
7511
8031
  h5_used_pct: profileRecord.h5_used_pct,
7512
8032
  h5_resets_at: profileRecord.h5_resets_at,
8033
+ h5_resets_at_epoch: profileRecord.h5_resets_at_epoch,
7513
8034
  weekly_used_pct: profileRecord.weekly_used_pct,
7514
8035
  weekly_resets_at: profileRecord.weekly_resets_at,
8036
+ weekly_resets_at_epoch: profileRecord.weekly_resets_at_epoch,
7515
8037
  });
7516
8038
  return true;
7517
8039
  }
@@ -7676,6 +8198,35 @@ Run \`bd ready\` to see current bd issues.
7676
8198
  }
7677
8199
  }
7678
8200
 
8201
+ /**
8202
+ * The quota capture of a provider failure.
8203
+ *
8204
+ * The recovery decides when to continue from a capture of the quota,
8205
+ * and the row of the mirror can be hours old. The capture is the one of
8206
+ * the harness: it refreshes the mirror and nothing else, it never
8207
+ * charges an attempt of the recovery and it never schedules anything.
8208
+ */
8209
+ const quotaCaptureController = new QuotaCaptureController({
8210
+ capture: (provider) => captureQuotaOf(provider),
8211
+ log: (message) => logToFile("[pi-harness]", message),
8212
+ });
8213
+
8214
+ /**
8215
+ * Capture the quota of a provider.
8216
+ */
8217
+ async function captureQuotaOf(provider: string): Promise<boolean> {
8218
+ if (provider === "minimax") {
8219
+ return autoFetchQuota({ suppressErrors: true });
8220
+ }
8221
+ if (provider === "openai" || provider === "openai-codex") {
8222
+ return autoFetchOpenAIQuota({ suppressErrors: true });
8223
+ }
8224
+ if (provider === "glm") {
8225
+ return autoFetchGLMQuota({ suppressErrors: true });
8226
+ }
8227
+ return false;
8228
+ }
8229
+
7679
8230
  async function maybeAutoFetchQuota(
7680
8231
  modelId: string | null | undefined,
7681
8232
  ): Promise<void> {
@@ -8468,6 +9019,7 @@ Run \`bd ready\` to see current bd issues.
8468
9019
  "output-limit-settled",
8469
9020
  OUTPUT_LIMIT_RESUME_PROMPT,
8470
9021
  "followUp",
9022
+ { scope: "turn" },
8471
9023
  );
8472
9024
  }, 0);
8473
9025
  });
@@ -8508,6 +9060,10 @@ Run \`bd ready\` to see current bd issues.
8508
9060
  "post-compact-output-limit",
8509
9061
  OUTPUT_LIMIT_RESUME_PROMPT,
8510
9062
  event.willRetry ? "steer" : "followUp",
9063
+ // The output limit cut the turn off, so the turn is
9064
+ // unfinished: the guard of a completed request does not
9065
+ // apply to it.
9066
+ { scope: "turn" },
8511
9067
  );
8512
9068
  return;
8513
9069
  }
@@ -8580,9 +9136,47 @@ Run \`bd ready\` to see current bd issues.
8580
9136
  reason: string,
8581
9137
  content: string,
8582
9138
  deliverAs: "steer" | "followUp",
9139
+ options: {
9140
+ /**
9141
+ * What the resume continues: the request that is running, or a
9142
+ * turn that was cut off.
9143
+ *
9144
+ * A cut turn is unfinished by definition, so it is resumed
9145
+ * without the guard. A resume of the request is gated: it goes
9146
+ * on only while that request has work.
9147
+ */
9148
+ scope?: "request" | "turn";
9149
+ } = {},
8583
9150
  ): Promise<void> {
8584
9151
  try {
8585
- pi.sendUserMessage(content, { deliverAs });
9152
+ if (options.scope !== "turn") {
9153
+ // An automatic resume continues the request that is running.
9154
+ // It is not an instruction to find more work: a resume that
9155
+ // was queued while the request ran and that is consumed
9156
+ // after it finished would send the agent to the backlog,
9157
+ // and the backlog is not work of this request.
9158
+ const decision = decideResumeScope({
9159
+ work: await currentRequestWorkState(),
9160
+ reason,
9161
+ });
9162
+ if (decision.action === "suppress") {
9163
+ logToFile("[resume-scope]", `Resume suppressed: ${decision.reason}`);
9164
+ reportSuppressedResume(decision.report);
9165
+ return;
9166
+ }
9167
+ }
9168
+ // The resume is a message of the harness, not a message of the
9169
+ // human: it carries a marker, so the guard can recognize it when
9170
+ // it is consumed after the request finished.
9171
+ pi.sendMessage(
9172
+ buildAutoResumeMessage({
9173
+ content,
9174
+ reason,
9175
+ scope: options.scope ?? "request",
9176
+ nonce: nextResumeNonce(),
9177
+ }),
9178
+ { deliverAs },
9179
+ );
8586
9180
  await nc("ResumeScheduled", {
8587
9181
  requirement: "Session auto-resume",
8588
9182
  // A resume trigger is not a failure. It renders as