pi-harness-runtime 1.1.510 → 1.1.511

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 (78) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/harness/mirror-record-merge.ts +64 -0
  3. package/harness/optional-event.ts +27 -0
  4. package/harness/provider-recovery-runtime.ts +143 -4
  5. package/harness/weekly-exhaustion-registry.ts +178 -0
  6. package/harness/weekly-quota-exhaustion.ts +172 -0
  7. package/index.ts +321 -2
  8. package/package.json +1 -1
  9. package/packages/agent-policy/package.json +1 -1
  10. package/packages/auth/package.json +1 -1
  11. package/packages/autonomous-runtime/package.json +1 -1
  12. package/packages/checkpoint/package.json +1 -1
  13. package/packages/clipboard/package.json +1 -1
  14. package/packages/codex-watcher/package.json +1 -1
  15. package/packages/config-capture/package.json +1 -1
  16. package/packages/contracts/package.json +1 -1
  17. package/packages/cookie-sanitizer/package.json +1 -1
  18. package/packages/evaluation-engine/package.json +1 -1
  19. package/packages/event-bus/package.json +1 -1
  20. package/packages/event-store/package.json +1 -1
  21. package/packages/experience-replay/package.json +1 -1
  22. package/packages/file-copy-helper/package.json +1 -1
  23. package/packages/intent-analyzer/package.json +1 -1
  24. package/packages/jev-judge/package.json +1 -1
  25. package/packages/knowledge-retrieval/package.json +1 -1
  26. package/packages/learning-engine/package.json +1 -1
  27. package/packages/logging/package.json +1 -1
  28. package/packages/memory-engine/package.json +1 -1
  29. package/packages/notification/dist/adapters/email-adapter.d.ts.map +1 -1
  30. package/packages/notification/dist/adapters/email-adapter.js +1 -0
  31. package/packages/notification/dist/adapters/email-adapter.js.map +1 -1
  32. package/packages/notification/dist/adapters/line-adapter.d.ts.map +1 -1
  33. package/packages/notification/dist/adapters/line-adapter.js +1 -0
  34. package/packages/notification/dist/adapters/line-adapter.js.map +1 -1
  35. package/packages/notification/dist/adapters/ntfy-adapter.d.ts.map +1 -1
  36. package/packages/notification/dist/adapters/ntfy-adapter.js +1 -0
  37. package/packages/notification/dist/adapters/ntfy-adapter.js.map +1 -1
  38. package/packages/notification/dist/adapters/telegram-adapter.d.ts.map +1 -1
  39. package/packages/notification/dist/adapters/telegram-adapter.js +1 -0
  40. package/packages/notification/dist/adapters/telegram-adapter.js.map +1 -1
  41. package/packages/notification/dist/notification-center.d.ts.map +1 -1
  42. package/packages/notification/dist/notification-center.js +6 -0
  43. package/packages/notification/dist/notification-center.js.map +1 -1
  44. package/packages/notification/dist/telegram-webhook-handler.d.ts +14 -0
  45. package/packages/notification/dist/telegram-webhook-handler.d.ts.map +1 -1
  46. package/packages/notification/dist/telegram-webhook-handler.js +14 -0
  47. package/packages/notification/dist/telegram-webhook-handler.js.map +1 -1
  48. package/packages/notification/dist/types.d.ts +9 -1
  49. package/packages/notification/dist/types.d.ts.map +1 -1
  50. package/packages/notification/package.json +1 -1
  51. package/packages/notification/src/adapters/email-adapter.ts +1 -0
  52. package/packages/notification/src/adapters/line-adapter.ts +1 -0
  53. package/packages/notification/src/adapters/ntfy-adapter.ts +1 -0
  54. package/packages/notification/src/adapters/telegram-adapter.ts +1 -0
  55. package/packages/notification/src/notification-center.ts +6 -0
  56. package/packages/notification/src/telegram-webhook-handler.ts +14 -0
  57. package/packages/notification/src/types.ts +8 -0
  58. package/packages/paperclip-integration/package.json +1 -1
  59. package/packages/performance-optimizer/package.json +1 -1
  60. package/packages/privilege-broker/package.json +1 -1
  61. package/packages/prompt-compiler/package.json +1 -1
  62. package/packages/providers/package.json +1 -1
  63. package/packages/qdrant-skills/package.json +1 -1
  64. package/packages/quota-manager/package.json +1 -1
  65. package/packages/relay/package.json +1 -1
  66. package/packages/skill-mcp-client/package.json +1 -1
  67. package/packages/skills/package.json +1 -1
  68. package/packages/todo-bd-sync/package.json +1 -1
  69. package/packages/token-estimation/package.json +1 -1
  70. package/packages/tooling-preference/package.json +1 -1
  71. package/packages/trajectory/package.json +1 -1
  72. package/packages/tui/package.json +1 -1
  73. package/packages/two-phase-review/package.json +1 -1
  74. package/packages/types/package.json +1 -1
  75. package/packages/webmcp-tester/package.json +1 -1
  76. package/packages/wiki/package.json +1 -1
  77. package/packages/write-review/package.json +1 -1
  78. package/proactive-compact.ts +21 -0
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The exhaustion of the weekly allowance of a provider.
3
+ *
4
+ * The weekly window is not the five-hour window: it lasts days, and no
5
+ * bounded cycle of retries reaches its end. A weekly allowance that is
6
+ * empty therefore blocks the account until the week resets, and that is a
7
+ * decision of the human: the harness may count down to the reset, or the
8
+ * human may deal with the account itself. Until the human chooses, the
9
+ * work stays paused.
10
+ *
11
+ * The evidence is the mirror of the harness, and it has to be fresh: a row
12
+ * of the mirror that is hours old describes a week that may already have
13
+ * been paid for. The selector therefore reads the row that the harness
14
+ * already has - it never scrapes again - and it refuses a row that is not
15
+ * fresh, not for this provider, or not complete.
16
+ *
17
+ * The module is pure: it decides, it does not observe, notify or
18
+ * schedule.
19
+ */
20
+
21
+ import type { ProviderMirrorRecord } from "../mirror.ts";
22
+ import type { ProviderFailure } from "./provider-failure.ts";
23
+ import {
24
+ MAX_RESET_EVIDENCE_AGE_MS,
25
+ normalizeProviderIdentity,
26
+ } from "./provider-recovery.ts";
27
+ import {
28
+ quotaWindowState,
29
+ remainingPctFromUsedPct,
30
+ } from "./quota-threshold.ts";
31
+
32
+ /**
33
+ * The evidence of an empty weekly allowance.
34
+ */
35
+ export interface WeeklyQuotaExhaustion {
36
+ /** The provider whose weekly allowance is empty. */
37
+ provider: string;
38
+ /** The absolute epoch of the weekly reset. */
39
+ resetAt: number;
40
+ /** When the evidence was observed. */
41
+ observedAt: number;
42
+ /** The remaining percentage of the weekly window (zero when it is empty). */
43
+ remainingPct: number;
44
+ /** Where the evidence came from. */
45
+ source: string;
46
+ }
47
+
48
+ /**
49
+ * The names the providers are known by in a message of the harness.
50
+ *
51
+ * The provider writes its own name ("MiniMax"), and the id of the mirror
52
+ * is lower case. A message about the account of the user should carry the
53
+ * name the user knows.
54
+ */
55
+ const DISPLAY_NAMES: Record<string, string> = {
56
+ minimax: "MiniMax",
57
+ glm: "GLM",
58
+ openai: "OpenAI",
59
+ anthropic: "Anthropic",
60
+ openrouter: "OpenRouter",
61
+ };
62
+
63
+ /**
64
+ * The name of a provider for a message of the harness.
65
+ */
66
+ export function providerDisplayName(provider: string): string {
67
+ const key = normalizeProviderIdentity(provider);
68
+ return DISPLAY_NAMES[key] ?? provider;
69
+ }
70
+
71
+ /**
72
+ * Is the weekly allowance of the provider empty?
73
+ *
74
+ * The decision needs three facts, and every one of them has to be there:
75
+ *
76
+ * - the failure is a failure of the quota (an exhausted plan or a rate
77
+ * limit). A rejected credential or an overload says nothing about the
78
+ * weekly allowance,
79
+ * - the row of the mirror is for this provider and is fresh, and
80
+ * - the weekly window of that row is empty and has a reset in the future.
81
+ *
82
+ * A weekly window that is empty but has no usable reset yields nothing:
83
+ * without a moment to wait for, the harness cannot offer a countdown, and
84
+ * the ordinary recovery of the quota keeps its own rules.
85
+ */
86
+ export function weeklyQuotaExhausted(input: {
87
+ /** The classified failure of the provider. */
88
+ failure: ProviderFailure;
89
+ /** The provider that rejected the request. */
90
+ provider: string;
91
+ /** The row of the mirror, when there is one. */
92
+ mirror: ProviderMirrorRecord | null | undefined;
93
+ /** The clock of the decision. */
94
+ now: number;
95
+ }): WeeklyQuotaExhaustion | undefined {
96
+ const { failure, provider, mirror, now } = input;
97
+ if (failure.kind !== "usage-exhausted" && failure.kind !== "rate-limit") {
98
+ return undefined;
99
+ }
100
+ if (!mirror) return undefined;
101
+ if (
102
+ normalizeProviderIdentity(mirror.provider) !==
103
+ normalizeProviderIdentity(provider)
104
+ ) {
105
+ return undefined;
106
+ }
107
+ const observedAt = Date.parse(mirror.synced_at);
108
+ if (
109
+ !Number.isFinite(observedAt) ||
110
+ observedAt > now ||
111
+ now - observedAt > MAX_RESET_EVIDENCE_AGE_MS
112
+ ) {
113
+ return undefined;
114
+ }
115
+ if (quotaWindowState(mirror.weekly_used_pct) !== "exhausted") {
116
+ return undefined;
117
+ }
118
+ const resetAt = mirror.weekly_resets_at_epoch;
119
+ if (typeof resetAt !== "number" || !Number.isFinite(resetAt) || resetAt <= now) {
120
+ return undefined;
121
+ }
122
+ return {
123
+ provider: normalizeProviderIdentity(provider),
124
+ resetAt,
125
+ observedAt,
126
+ remainingPct: remainingPctFromUsedPct(mirror.weekly_used_pct as number),
127
+ source: mirror.source,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * The duration until a reset, in the words of the console.
133
+ *
134
+ * The console of a provider writes the remaining time of a window as
135
+ * "2 days 7 hours 58 minutes", and the harness writes it the same way.
136
+ * The unit that is missing is left out, and a duration below a minute is
137
+ * written in seconds.
138
+ */
139
+ export function formatResetDuration(ms: number): string {
140
+ const total = Math.max(0, Math.round(ms));
141
+ const days = Math.floor(total / 86_400_000);
142
+ const hours = Math.floor((total % 86_400_000) / 3_600_000);
143
+ const minutes = Math.floor((total % 3_600_000) / 60_000);
144
+ const seconds = Math.floor((total % 60_000) / 1000);
145
+ const parts: string[] = [];
146
+ if (days > 0) parts.push(`${days} ${days === 1 ? "day" : "days"}`);
147
+ if (hours > 0) parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`);
148
+ if (minutes > 0) {
149
+ parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`);
150
+ }
151
+ if (parts.length === 0) parts.push(`${seconds} ${seconds === 1 ? "second" : "seconds"}`);
152
+ return parts.join(" ");
153
+ }
154
+
155
+ /**
156
+ * The message of the exhaustion of the weekly allowance.
157
+ *
158
+ * The message names the provider, the remaining time of the week and the
159
+ * state of the work. It travels in full: a truncated message is not a
160
+ * message the user can decide about.
161
+ */
162
+ export function weeklyExhaustionMessage(input: {
163
+ /** The provider whose weekly allowance is empty. */
164
+ provider: string;
165
+ /** The absolute epoch of the weekly reset. */
166
+ resetAt: number;
167
+ /** The clock of the message. */
168
+ now: number;
169
+ }): string {
170
+ const { provider, resetAt, now } = input;
171
+ return `${providerDisplayName(provider)} weekly quota exhausted. Resets in ${formatResetDuration(resetAt - now)}. Work is paused.`;
172
+ }
package/index.ts CHANGED
@@ -86,6 +86,19 @@ 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 { mergeMirrorRecord } from "./harness/mirror-record-merge.ts";
90
+ import { onOptionalEvent } from "./harness/optional-event.ts";
91
+ import {
92
+ providerDisplayName,
93
+ weeklyExhaustionMessage,
94
+ weeklyQuotaExhausted,
95
+ type WeeklyQuotaExhaustion,
96
+ } from "./harness/weekly-quota-exhaustion.ts";
97
+ import {
98
+ buildWeeklyRequestId,
99
+ WeeklyExhaustionRegistry,
100
+ type WeeklyDecision,
101
+ } from "./harness/weekly-exhaustion-registry.ts";
89
102
  import { resetEpochFromDuration } from "./harness/quota-reset-duration.ts";
90
103
  import { QuotaCaptureController } from "./harness/quota-capture.ts";
91
104
  import { QuotaLowRemainingTracker } from "./harness/quota-low-remaining.ts";
@@ -177,6 +190,7 @@ import {
177
190
  isProviderRetryFailedReport,
178
191
  shouldQueuePostCompactionResume,
179
192
  shouldTriggerProactiveCompact,
193
+ isProviderOverloadText,
180
194
  } from "./proactive-compact.ts";
181
195
  import { aggregateWindows } from "./windows.ts";
182
196
 
@@ -497,6 +511,76 @@ const PROVIDER_BLOCKED_ACTION_ID = "provider-blocked";
497
511
  */
498
512
  let providerRecoveryRuntime: ProviderRecoveryRuntime | null = null;
499
513
 
514
+ /**
515
+ * The decisions of the human about an empty weekly allowance.
516
+ *
517
+ * The weekly window of a provider lasts days, and the work stays paused
518
+ * until the human decides: the harness counts down to the reset of the
519
+ * week, or the human deals with the account itself. The registry holds the
520
+ * decisions - the first answer wins - and it never asks the judge.
521
+ */
522
+ const weeklyExhaustions = new WeeklyExhaustionRegistry();
523
+
524
+ /**
525
+ * The decision of the human about the weekly allowance.
526
+ *
527
+ * One resolver for every channel: the first answer wins, and the button
528
+ * of an old message is stale. Only the count down schedules anything -
529
+ * the human handling the account leaves the work paused.
530
+ *
531
+ * The resolver lives at the top level of the extension: the click of
532
+ * Telegram and the postback of LINE arrive in different places of the
533
+ * harness, and both of them have to reach the same decision.
534
+ */
535
+ async function resolveWeeklyDecision(
536
+ requestId: string,
537
+ decision: WeeklyDecision,
538
+ channel: "telegram" | "line",
539
+ ): Promise<{ ok: boolean; message: string }> {
540
+ const claim = weeklyExhaustions.claim(
541
+ requestId,
542
+ decision,
543
+ channel,
544
+ Date.now(),
545
+ );
546
+ if (!claim.ok) {
547
+ const reason = claim.reason ?? "the decision was refused";
548
+ logToFile("[pi-harness]", `Weekly decision (${channel}): stale - ${reason}`);
549
+ return { ok: false, message: `Stale button - ${reason}` };
550
+ }
551
+ const record = claim.record;
552
+ if (!record) {
553
+ return { ok: false, message: "Stale button - the decision is unknown" };
554
+ }
555
+ if (decision === "countdown") {
556
+ const scheduled =
557
+ providerRecoveryRuntime?.scheduleWeeklyReset(
558
+ record.resetAt,
559
+ record.provider,
560
+ ) ?? false;
561
+ logToFile(
562
+ "[pi-harness]",
563
+ `Weekly decision (${channel}): count down to ${new Date(record.resetAt).toISOString()} (scheduled=${scheduled})`,
564
+ );
565
+ return {
566
+ ok: true,
567
+ message: scheduled
568
+ ? "Counting down to the reset of the week."
569
+ : "The reset of the week cannot be scheduled.",
570
+ };
571
+ }
572
+ // The human deals with the account: the work stays paused until the
573
+ // human says otherwise.
574
+ logToFile(
575
+ "[pi-harness]",
576
+ `Weekly decision (${channel}): the user handles the account, the work stays paused`,
577
+ );
578
+ return {
579
+ ok: true,
580
+ message: "Understood - the work stays paused until you say otherwise.",
581
+ };
582
+ }
583
+
500
584
  /**
501
585
  * The continuation controller of the todos.
502
586
  *
@@ -4262,6 +4346,23 @@ async function initTelegram(pi: ExtensionAPI): Promise<void> {
4262
4346
  }
4263
4347
  break;
4264
4348
  }
4349
+ case CallbackActions.WEEK_COUNTDOWN:
4350
+ case CallbackActions.WEEK_MANUAL: {
4351
+ // The decision about the weekly allowance of the provider.
4352
+ // It is the human alone: the judge is never asked, and the
4353
+ // first answer wins.
4354
+ const decision: WeeklyDecision =
4355
+ parsed.action === CallbackActions.WEEK_COUNTDOWN
4356
+ ? "countdown"
4357
+ : "manual";
4358
+ const result = await resolveWeeklyDecision(
4359
+ parsed.targetId,
4360
+ decision,
4361
+ "telegram",
4362
+ );
4363
+ await acknowledge(result.message);
4364
+ break;
4365
+ }
4265
4366
  default:
4266
4367
  // Check for channel toggle actions
4267
4368
  if (parsed.action === "toggle_telegram") {
@@ -4786,6 +4887,27 @@ async function initRelayStream(): Promise<void> {
4786
4887
  ? callback.action.slice("biome_".length)
4787
4888
  : callback.targetId;
4788
4889
  await resolveToolingPreference(raw, "line", _extensionApi);
4890
+ } else if (
4891
+ callback.action === "weekcountdown" ||
4892
+ callback.action === "weekmanual" ||
4893
+ callback.action.startsWith("weekcountdown_") ||
4894
+ callback.action.startsWith("weekmanual_")
4895
+ ) {
4896
+ // The decision about the weekly allowance is the same
4897
+ // decision as in Telegram: one resolver, the first
4898
+ // answer wins. The postback data arrives split into
4899
+ // the action and the request ID, and it may arrive as
4900
+ // one string.
4901
+ const separator = callback.action.indexOf("_");
4902
+ const raw =
4903
+ separator === -1
4904
+ ? callback.targetId
4905
+ : callback.action.slice(separator + 1);
4906
+ const decision: WeeklyDecision =
4907
+ callback.action.startsWith("weekcountdown")
4908
+ ? "countdown"
4909
+ : "manual";
4910
+ await resolveWeeklyDecision(raw, decision, "line");
4789
4911
  } else {
4790
4912
  applyChannelApproval(callback.action, callback.targetId, "line");
4791
4913
  }
@@ -6200,6 +6322,27 @@ type NcCenter = {
6200
6322
  notifyWithButtons?: Function;
6201
6323
  };
6202
6324
 
6325
+ /**
6326
+ * The failure of a compaction.
6327
+ *
6328
+ * The installed core of Pi fires this event. The declaration of the
6329
+ * extension API that the harness compiles against does not name it yet,
6330
+ * so the shape is described here: the fields the harness reads are the
6331
+ * fields of the core.
6332
+ */
6333
+ interface SessionCompactFailedEvent {
6334
+ /** What triggered the compaction. */
6335
+ reason: "manual" | "threshold" | "overflow";
6336
+ /** The text of the failure, when it failed for a reason other than an abort. */
6337
+ errorMessage?: string;
6338
+ /** Was the compaction cancelled or aborted? */
6339
+ aborted: boolean;
6340
+ /** Would the aborted turn be retried after the compaction? */
6341
+ willRetry: boolean;
6342
+ /** Did the failing content come from an extension? */
6343
+ fromExtension: boolean;
6344
+ }
6345
+
6203
6346
  /**
6204
6347
  * Fire a Telegram notification event. Logs delivery outcomes.
6205
6348
  * Silently skips if Telegram is not configured.
@@ -7408,6 +7551,114 @@ issue is not authorized work of the current request).
7408
7551
  // and a scheduled resume checks that it still owns the session before it
7409
7552
  // dispatches. The resume itself goes through the executor below, so
7410
7553
  // there is no second resume loop.
7554
+ // --- The weekly exhaustion of the quota ------------------------------
7555
+ //
7556
+ // The weekly allowance of a provider lasts days. When it is empty, no
7557
+ // bounded cycle of retries reaches its end, and the work stays paused
7558
+ // until the human decides: the harness counts down to the reset of the
7559
+ // week, or the human deals with the account itself. The judge is never
7560
+ // asked, and the silence of the human keeps the work paused.
7561
+ //
7562
+ // The message carries the whole text: the remaining time of the week
7563
+ // and the state of the work are what the human decides about.
7564
+ async function notifyWeeklyExhaustion(
7565
+ exhaustion: WeeklyQuotaExhaustion,
7566
+ ): Promise<void> {
7567
+ const center = _nc?.center as NcCenter | undefined;
7568
+ if (!center || typeof center.notifyWithButtons !== "function") {
7569
+ logToFile(
7570
+ "[pi-harness]",
7571
+ "Weekly quota exhausted: no notification center, the work stays paused",
7572
+ );
7573
+ return;
7574
+ }
7575
+ const now = Date.now();
7576
+ const requestId = buildWeeklyRequestId(
7577
+ exhaustion.provider,
7578
+ exhaustion.resetAt,
7579
+ );
7580
+ const message = weeklyExhaustionMessage({
7581
+ provider: exhaustion.provider,
7582
+ resetAt: exhaustion.resetAt,
7583
+ now,
7584
+ });
7585
+ // A repeated failure of the provider must not send the same
7586
+ // question again: the decision is the same one, and the user
7587
+ // answers it once.
7588
+ const existing = weeklyExhaustions.get(requestId);
7589
+ if (existing?.delivered) {
7590
+ logToFile(
7591
+ "[pi-harness]",
7592
+ "Weekly quota exhausted: the message is already delivered, the work stays paused",
7593
+ );
7594
+ return;
7595
+ }
7596
+ // The decision is registered before the message goes out: a click
7597
+ // that arrives before the delivery is acknowledged still finds it.
7598
+ weeklyExhaustions.register({
7599
+ requestId,
7600
+ provider: exhaustion.provider,
7601
+ resetAt: exhaustion.resetAt,
7602
+ now,
7603
+ });
7604
+ let delivered = false;
7605
+ try {
7606
+ const results = (await center.notifyWithButtons(
7607
+ "QuotaWeeklyExhausted",
7608
+ {
7609
+ jobId: requestId,
7610
+ requirement: message,
7611
+ provider: providerDisplayName(exhaustion.provider),
7612
+ quotaWindow: "weekly",
7613
+ resetAt: new Date(exhaustion.resetAt).toISOString(),
7614
+ remainingPct: exhaustion.remainingPct,
7615
+ },
7616
+ [
7617
+ {
7618
+ text: "Count down week resets",
7619
+ action: "weekcountdown",
7620
+ targetId: requestId,
7621
+ },
7622
+ {
7623
+ text: "I will handle it",
7624
+ action: "weekmanual",
7625
+ targetId: requestId,
7626
+ },
7627
+ ],
7628
+ )) as
7629
+ | Array<{ success: boolean; channel: string; error?: string }>
7630
+ | undefined;
7631
+ delivered =
7632
+ Array.isArray(results) &&
7633
+ results.some((result) => result?.success === true);
7634
+ for (const result of results ?? []) {
7635
+ logToFile(
7636
+ "[pi-harness]",
7637
+ `Weekly quota exhausted: ${result?.success ? "sent to" : "failed on"} ${result?.channel}${result?.error ? ` (${result.error})` : ""}`,
7638
+ );
7639
+ }
7640
+ } catch (error) {
7641
+ logToFile(
7642
+ "[pi-harness]",
7643
+ `Weekly quota exhausted: the message failed: ${
7644
+ error instanceof Error ? error.message : String(error)
7645
+ }`,
7646
+ );
7647
+ }
7648
+ if (!delivered) {
7649
+ // A decision nobody can reach would wait for an answer that
7650
+ // never comes.
7651
+ weeklyExhaustions.remove(requestId);
7652
+ logToFile(
7653
+ "[pi-harness]",
7654
+ "Weekly quota exhausted: no channel carried the message, the work stays paused",
7655
+ );
7656
+ return;
7657
+ }
7658
+ // The window of the answer starts when the delivery is acknowledged.
7659
+ weeklyExhaustions.markDelivered(requestId);
7660
+ }
7661
+
7411
7662
  providerRecoveryRuntime = new ProviderRecoveryRuntime({
7412
7663
  controller: providerRecovery,
7413
7664
  actions: pendingActions,
@@ -7436,6 +7687,21 @@ issue is not authorized work of the current request).
7436
7687
  Date.now(),
7437
7688
  );
7438
7689
  },
7690
+ weeklyExhaustionEvidence: (failure, provider) => {
7691
+ // The same rule as for the deadline: a capture that failed
7692
+ // leaves the old row of the mirror, and an old row cannot prove
7693
+ // an empty week.
7694
+ if (quotaCaptureController.failed(provider)) return undefined;
7695
+ return weeklyQuotaExhausted({
7696
+ failure,
7697
+ provider,
7698
+ mirror: mirrorStore.readProvider(provider.toLowerCase()),
7699
+ now: Date.now(),
7700
+ });
7701
+ },
7702
+ onWeeklyExhaustion: (exhaustion) => {
7703
+ void notifyWeeklyExhaustion(exhaustion);
7704
+ },
7439
7705
  overloadDelayMs: () => getProviderOverloadResumeDelayMs(),
7440
7706
  overloadMaxAttempts: PROVIDER_OVERLOAD_AUTO_RESUME_LIMIT,
7441
7707
  dispatch: async (reason) => {
@@ -8029,8 +8295,16 @@ issue is not authorized work of the current request).
8029
8295
  // "record:",
8030
8296
  // JSON.stringify(record),
8031
8297
  // );
8032
- mirrorStore.writeProvider(provider, { ...record, provider });
8033
- notifyQuotaLowRemaining(provider, record);
8298
+ // A write that knows no quota window must not throw the evidence of
8299
+ // the windows away: the signal of the TUI arrives with the failure
8300
+ // of the provider, and that is the moment the recovery needs the
8301
+ // evidence of the week.
8302
+ const merged = mergeMirrorRecord(mirrorStore.readProvider(provider), {
8303
+ ...record,
8304
+ provider,
8305
+ });
8306
+ mirrorStore.writeProvider(provider, merged);
8307
+ notifyQuotaLowRemaining(provider, merged);
8034
8308
  if (footerSetStatus) {
8035
8309
  refreshFooterStatus(
8036
8310
  footerSetStatus,
@@ -9258,6 +9532,51 @@ issue is not authorized work of the current request).
9258
9532
  await queueAutoResume("post-compact", "resume", "followUp");
9259
9533
  });
9260
9534
 
9535
+ // The compaction failed. A compaction that fails with the overload of
9536
+ // the provider is the same overload as a failed turn, and it shares the
9537
+ // executor of the overload: one countdown, one resume, and the same
9538
+ // limit of attempts. A second countdown would continue the work twice.
9539
+ onOptionalEvent<SessionCompactFailedEvent>(
9540
+ pi,
9541
+ "session_compact_failed",
9542
+ (event) => {
9543
+ const errorMessage =
9544
+ typeof event.errorMessage === "string" ? event.errorMessage : "";
9545
+ if (event.aborted) {
9546
+ // The user aborted the compaction: a decision of the user and
9547
+ // not an overload. An automatic resume would fight it.
9548
+ logToFile("[pi-harness]", "Compaction aborted by the user");
9549
+ return;
9550
+ }
9551
+ if (!isProviderOverloadText(errorMessage)) {
9552
+ logToFile(
9553
+ "[pi-harness]",
9554
+ `Compaction failed: ${errorMessage || event.reason}`,
9555
+ );
9556
+ return;
9557
+ }
9558
+ if (event.willRetry) {
9559
+ // Pi retries the turn itself after the compaction: a resume
9560
+ // of the harness would continue the work a second time.
9561
+ logToFile(
9562
+ "[pi-harness]",
9563
+ "Compaction failed with an overload of the provider: Pi retries the turn itself",
9564
+ );
9565
+ return;
9566
+ }
9567
+ const scheduled =
9568
+ providerRecoveryRuntime?.scheduleOverloadResume() ?? false;
9569
+ logToFile(
9570
+ "[pi-harness]",
9571
+ `Compaction failed with an overload of the provider: ${
9572
+ scheduled
9573
+ ? "the countdown of the overload is armed"
9574
+ : "no countdown - the budget of the overload is spent"
9575
+ }`,
9576
+ );
9577
+ },
9578
+ );
9579
+
9261
9580
  // --- Periodic quota refresh every 15 minutes ---
9262
9581
  // `maybeAutoFetchQuota` checks its own rate-limit (MINIMAX_REFRESH_MIN_INTERVAL_MS)
9263
9582
  // so this is safe to call frequently.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-harness-runtime",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "[BETA] Codex-style /usage status + autonomous coding harness for pi. Not production ready — expect breaking changes.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/agent-policy",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "Agent policy runtime for pi-harness - enforces mandatory rule delivery and mutation gating",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/auth",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "pi-harness-runtime — auth",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/autonomous-runtime",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "Autonomous Operations Runtime — task inbox, lease management, and worker lifecycle (RFC-0101)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/checkpoint",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "Enhanced checkpoint system with incremental snapshots, diff-based storage, and recovery strategies",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/clipboard",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/codex-watcher",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "Watches Codex CLI sessions and emits visible messages for PING-PONG monitoring",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moocoding/config-capture",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "Auto-capture API-fetched configuration values to AGENTS.md",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/contracts",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "type": "module",
5
5
  "description": "RPC schema definitions for pi-harness runtime",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/cookie-sanitizer",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "pi-harness-runtime — cookie sanitizer (provider-quota cookie file normaliser)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/evaluation-engine",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "Evaluation engine for pi-harness runtime (RFC-0057)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/event-bus",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/event-store",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/experience-replay",
3
- "version": "1.1.510",
3
+ "version": "1.1.511",
4
4
  "description": "Experience replay for debugging and reproducibility (RFC-0059)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",