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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,95 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [1.1.511](https://github.com/ManotLuijiu/pi-harness-runtime/compare/v1.1.448...v1.1.511) (2026-11-16)
6
+
7
+
8
+ ### Features
9
+
10
+ * **actions:** register the job resume, the GLM countdown and the queued continuations ([177c964](https://github.com/ManotLuijiu/pi-harness-runtime/commit/177c964555b0057e6bc7d293dafab10c95eabbf9))
11
+ * **delegation:** a child is only a child when it really ran ([ac4e678](https://github.com/ManotLuijiu/pi-harness-runtime/commit/ac4e6782d7d4bc4941e458425c8a9f38a51fc9d4))
12
+ * **delegation:** the scope of a request is measured before it is judged ([684b6a5](https://github.com/ManotLuijiu/pi-harness-runtime/commit/684b6a55184f63d3be24c48dcecfb0b13410dc15))
13
+ * **harness:** the startup tells the user that the session keeps its issues with bd ([81d63c5](https://github.com/ManotLuijiu/pi-harness-runtime/commit/81d63c5dc2452b9f08001756866db80046a2532a))
14
+ * **honcho:** the memory service speaks the native MCP of Pi ([f9f740c](https://github.com/ManotLuijiu/pi-harness-runtime/commit/f9f740c12869bae4c4380afbe8c76e12388bb744))
15
+ * **jev:** one decision per question, bound to the question it was evaluated for ([03448aa](https://github.com/ManotLuijiu/pi-harness-runtime/commit/03448aaa17f2d0c3bcf644b0b1d5949727dfff8c))
16
+ * **jev:** the evaluation of a choice sees what the options mean ([f0c207e](https://github.com/ManotLuijiu/pi-harness-runtime/commit/f0c207e074701e6b7dab0965170ec39453d9d502))
17
+ * **jev:** the pending question carries the ask and the answer ([a792133](https://github.com/ManotLuijiu/pi-harness-runtime/commit/a792133e517fb8c12d3363e98942f3af30270f27))
18
+ * **jev:** the pending question counts down to the decision ([d0cc171](https://github.com/ManotLuijiu/pi-harness-runtime/commit/d0cc171223986b2d32c670b6c1c74712fe0a4ad8))
19
+ * **keys:** tell the user what to do about an exposed key file ([7031003](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7031003574307351b7a8f28ee14159b58e17b793))
20
+ * **keys:** the key files are repaired when their permissions are unsafe ([e9c2c26](https://github.com/ManotLuijiu/pi-harness-runtime/commit/e9c2c26b287665b56ed749de269737e8403bb8af))
21
+ * **mcp:** the harness connects the registered servers when nobody else does ([7fef951](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7fef95137ad4664df57f045cd91b7d233315b0bc))
22
+ * **merge:** a manual run can leave the merge to the pull request event ([b3d1950](https://github.com/ManotLuijiu/pi-harness-runtime/commit/b3d1950b5941c78ccd56951acdafd1d4afbe1bff))
23
+ * **phase:** the agent owns the todo list and the harness says so ([c489370](https://github.com/ManotLuijiu/pi-harness-runtime/commit/c489370bd7926aece8cb1a77aa20ca2d2672f1fb))
24
+ * **providers:** a shared registry of the pending automatic actions and a bounded recovery ([c5f955b](https://github.com/ManotLuijiu/pi-harness-runtime/commit/c5f955bc82adcb6999a89d5bc278fa87fccee022))
25
+ * **providers:** one failure has one executor, and the retry bridge is checked ([e73c4c7](https://github.com/ManotLuijiu/pi-harness-runtime/commit/e73c4c76ff20a9708083659bdcefe74870a84837))
26
+ * **questions:** refuse the deletion of a temporary path without the judge ([ab29694](https://github.com/ManotLuijiu/pi-harness-runtime/commit/ab29694f36c1ff020b3b19ca542a27b37847055c))
27
+ * **quota:** a fresh capture and a low allowance decide the MiniMax recovery ([06d7b8e](https://github.com/ManotLuijiu/pi-harness-runtime/commit/06d7b8e971e0da58a344f75778c98edb442562bd))
28
+ * **quota:** the empty week waits for the human, the overload of a compaction shares the executor ([bbb0c39](https://github.com/ManotLuijiu/pi-harness-runtime/commit/bbb0c3909b11735343e84be690c4c47e67a563bb))
29
+ * **recovery:** a MiniMax quota exhaustion waits for the captured reset plus ten minutes ([5af08a0](https://github.com/ManotLuijiu/pi-harness-runtime/commit/5af08a0e86c8c93fa5b7ff64a7b08e4514bc68f3))
30
+ * **review:** the review starts on its own when the implementation is done ([04f51f5](https://github.com/ManotLuijiu/pi-harness-runtime/commit/04f51f599cd3222b6c74dd8fadb1373bd72d9bd7))
31
+ * **scope:** a marked resume and a backlog that only an approval starts ([19d3320](https://github.com/ManotLuijiu/pi-harness-runtime/commit/19d33204819cf05e678996fddf4c4621f0dd7d2f))
32
+ * **status:** the status line names the phase, the progress and the children ([0167bf3](https://github.com/ManotLuijiu/pi-harness-runtime/commit/0167bf396a0b987c1d44f3b869351976a951dd65))
33
+ * **test:** the task waits for the final tier of the validation plan ([fa147db](https://github.com/ManotLuijiu/pi-harness-runtime/commit/fa147dbf7d50d56e6ea48c6d8fbb4fcb190caf8a))
34
+ * **validation:** a large job starts with a measured pilot ([425964b](https://github.com/ManotLuijiu/pi-harness-runtime/commit/425964b04a3d4fa02adfabed47ff62c5ec2b9c28))
35
+ * **validation:** the size of a job is a fact, not a phrase ([8aa6c11](https://github.com/ManotLuijiu/pi-harness-runtime/commit/8aa6c119565d0f8412dc8aeafa6b295d47d3f093))
36
+ * **workspace:** a Frappe bench names the mode of the workspace ([9d58517](https://github.com/ManotLuijiu/pi-harness-runtime/commit/9d585172063a330992fee933316e268ae9985e3c))
37
+
38
+
39
+ ### Bug Fixes
40
+
41
+ * **ci:** every run of a required check counts, and the worst one decides ([da9e0da](https://github.com/ManotLuijiu/pi-harness-runtime/commit/da9e0da6b0ca29cb320764fd5fc1b8a8dee8b1e0))
42
+ * **ci:** the newest attempt of a run decides, not the attempt that failed ([9d7adcc](https://github.com/ManotLuijiu/pi-harness-runtime/commit/9d7adcc31cbacc517c3c1a9bcd3956be94c908ef))
43
+ * **harness:** a raw control byte hid the request scope from the review ([852b1ff](https://github.com/ManotLuijiu/pi-harness-runtime/commit/852b1ff3afc21adb71e92b85d21ff1c88e14816a))
44
+ * **honcho:** a handshake that never finishes is named instead of hanging the startup ([d66005f](https://github.com/ManotLuijiu/pi-harness-runtime/commit/d66005f928a4f8df5de5b8a0579cbd4f8df37ff9))
45
+ * **honcho:** a probe that the end of the session cuts off is not a failure ([493fd93](https://github.com/ManotLuijiu/pi-harness-runtime/commit/493fd938ba09fdcf57bed4aaf259d81c4040909e))
46
+ * **honcho:** a slow connector is not a failed one, the row is corrected when the tools appear ([b62ac5b](https://github.com/ManotLuijiu/pi-harness-runtime/commit/b62ac5b16ad93e2bfb10cbec589b80a09b7e20b3))
47
+ * **honcho:** a tools listing that the end of the session cuts off is not a failure ([62cc8c3](https://github.com/ManotLuijiu/pi-harness-runtime/commit/62cc8c376aade01c953ce2a1c6501ed07b74a1e9))
48
+ * **honcho:** the report names the state of the MCP server, not the registration ([762f4d5](https://github.com/ManotLuijiu/pi-harness-runtime/commit/762f4d59e4eabcab9a1c21a61aa522c3267621b3))
49
+ * **hooks:** a tag is checked through the commit behind it ([c823e8e](https://github.com/ManotLuijiu/pi-harness-runtime/commit/c823e8e1f6973c62b5449a97c101759a4d5cbba5))
50
+ * **jev:** a completion question, a stale check and a pending validation ([827120b](https://github.com/ManotLuijiu/pi-harness-runtime/commit/827120b4138b6f5ae253e69154de190085703de8))
51
+ * **jev:** a new request does not inherit the completion of the old one ([0f863c7](https://github.com/ManotLuijiu/pi-harness-runtime/commit/0f863c7fcaf35e261beabebef15b8ab634132fdc))
52
+ * **jev:** a prohibition must not hide a destructive action ([78a6cc1](https://github.com/ManotLuijiu/pi-harness-runtime/commit/78a6cc199e647f812e145483f7e94991358d8f34))
53
+ * **jev:** a refusal without punctuation, and only a decline of an action ([ef3dbf8](https://github.com/ManotLuijiu/pi-harness-runtime/commit/ef3dbf87a2a1725373281613a0d48881ed5d2239))
54
+ * **jev:** a rejection during the countdown pauses the work ([9b018ce](https://github.com/ManotLuijiu/pi-harness-runtime/commit/9b018ce1152b6724dee73cdc901b8a360ecc91ab))
55
+ * **jev:** a session switch ends the wait of the old session ([ca03d39](https://github.com/ManotLuijiu/pi-harness-runtime/commit/ca03d399c0d4a1b2dd428ac39836ab53c0e51ab6))
56
+ * **jev:** an open question is not a permission to answer it ([e20eca2](https://github.com/ManotLuijiu/pi-harness-runtime/commit/e20eca24bb88d385198bb12ee3ebf573af9aea86))
57
+ * **jev:** keep a comparative caveat with the option it constrains ([7be306b](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7be306b0d0872713ebca9386d613ae5a8da9d5b6))
58
+ * **jev:** the action of the question on its own text, and a reply is not an authorization ([7c3fdd6](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7c3fdd6822b58bd6ccfa3bcdf1c5282cb3db52dd))
59
+ * **jev:** the action of the question, and an open question blocks the work ([1f9ff39](https://github.com/ManotLuijiu/pi-harness-runtime/commit/1f9ff39efc4ee17464c54c2ca9b583245093dbac))
60
+ * **jev:** the alternatives of a question are parsed without a quadratic pattern ([63016a3](https://github.com/ManotLuijiu/pi-harness-runtime/commit/63016a3f0488acb801990dd46770c00d382b5858))
61
+ * **jev:** the countdown of an obsolete question does not outlive the work ([fe78b29](https://github.com/ManotLuijiu/pi-harness-runtime/commit/fe78b29e6fc513b11a6993bc68fd9418dc77f79b))
62
+ * **jev:** the facts of an option survive the wording of the agent ([5a6250c](https://github.com/ManotLuijiu/pi-harness-runtime/commit/5a6250c07aa8d965bc6ae242cccbf519477598f8))
63
+ * **jev:** the scope decides the question, the identity guards the awaits ([ed348b2](https://github.com/ManotLuijiu/pi-harness-runtime/commit/ed348b2f94460a3b3ac11c01afd4420ee4ec1020))
64
+ * **jev:** the scope of a request on every human path, and the todos it touched ([cec8f36](https://github.com/ManotLuijiu/pi-harness-runtime/commit/cec8f3644333b1d13a203340df80a30fef5c1ac0))
65
+ * **jev:** the subject of the scope decides, a clarification is preserved ([faf6a0f](https://github.com/ManotLuijiu/pi-harness-runtime/commit/faf6a0fe7d0dce94d4fa48d0d7a57d126556ba6d))
66
+ * **keys:** the key directory is audited as a tree ([081cc75](https://github.com/ManotLuijiu/pi-harness-runtime/commit/081cc75ac8ceff36b0d619c3f76371dc08459d3c))
67
+ * **logging:** the sanitizer of a message writes its control characters as escapes ([f4bbdb9](https://github.com/ManotLuijiu/pi-harness-runtime/commit/f4bbdb94bc1801d4228142bc1a1b31505c42a575))
68
+ * **mcp:** the connector and the watcher stop with the session ([4d1b87d](https://github.com/ManotLuijiu/pi-harness-runtime/commit/4d1b87d14d015749025b62bf54d6d0b6137295f7))
69
+ * **mcp:** the connector survives a runtime that cannot list the servers ([d0f555f](https://github.com/ManotLuijiu/pi-harness-runtime/commit/d0f555fa14f51de33591e572a41ded5b59a3e4dd))
70
+ * **merge:** the boolean input is read as a boolean ([971b716](https://github.com/ManotLuijiu/pi-harness-runtime/commit/971b7169a43db382dbdeb6bb9bab02ab56e0351c))
71
+ * **merge:** the manual job needs the right of the merge ([7ba685e](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7ba685ec43d815f90aa35b742579e87e76c69209))
72
+ * **merge:** the merge of the pull request is the GraphQL mutation ([972bab4](https://github.com/ManotLuijiu/pi-harness-runtime/commit/972bab4b0f7faf1b0047f3bb767ef6db3de4b2fa))
73
+ * **merge:** the workflow merges the pull request the gates cleared ([d7639ec](https://github.com/ManotLuijiu/pi-harness-runtime/commit/d7639ec9b83723510acb4a5c4e23d5d6167c3af6))
74
+ * **providers:** the escape of the user stops the recovery, and a permanent failure clears it ([cfe5797](https://github.com/ManotLuijiu/pi-harness-runtime/commit/cfe57976bf463c327e45b874fd297c3e942246b8))
75
+ * **providers:** the pause wins over a retry, and the retry starts when the run settles ([e016dd2](https://github.com/ManotLuijiu/pi-harness-runtime/commit/e016dd2a5add5b0f3c848a225a28a59e0f5fc7f3))
76
+ * **recovery:** a cancelled countdown does not own the next attempt ([7b79f30](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7b79f301389fae48201e696d3086d257ed722fb9))
77
+ * **recovery:** a cancelled retry of Pi is a cancelled decision, a spent budget is not ([7e13f15](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7e13f156a279cded2b2d4b0c99358100b3d5e038))
78
+ * **recovery:** a manual request takes the work back from the countdown ([fa81d8f](https://github.com/ManotLuijiu/pi-harness-runtime/commit/fa81d8fd9d6160166a095e07bdf17049bbafa32d))
79
+ * **recovery:** the predicate of Pi decides the retry, the provider identity is normalized ([6c8c17b](https://github.com/ManotLuijiu/pi-harness-runtime/commit/6c8c17b53302cea1602d192251eacd0ebbd3e8c9))
80
+ * **release:** a manual release keeps the version of its manifest ([122e661](https://github.com/ManotLuijiu/pi-harness-runtime/commit/122e661ea48cb8aff14c71dbd0221a4cf0ba4c8e))
81
+ * **release:** the alignment names the reason of a failure ([5814dd0](https://github.com/ManotLuijiu/pi-harness-runtime/commit/5814dd0b780f5839cf8011ed0cbbbb31e7eb0418))
82
+ * **release:** the channels of the package name the release ([a7a273f](https://github.com/ManotLuijiu/pi-harness-runtime/commit/a7a273ffe8398e2b5b07ef1c321777de41792c6e))
83
+ * **release:** the release publishes and leaves the channels alone ([5871746](https://github.com/ManotLuijiu/pi-harness-runtime/commit/5871746589c1281d855dbeb591b02419fa43f22e))
84
+ * **release:** the release pull request names the version of its branch ([a846e83](https://github.com/ManotLuijiu/pi-harness-runtime/commit/a846e83e6de6e529f4bca05e869db0b5eebb37c5))
85
+ * **release:** the release scans the tree of the commit it publishes ([7d47a0b](https://github.com/ManotLuijiu/pi-harness-runtime/commit/7d47a0b5406480a1e1d3a52623a76aabd1e2d0ba))
86
+ * **scope:** a session that ends leaves no proposal behind ([9aad01e](https://github.com/ManotLuijiu/pi-harness-runtime/commit/9aad01e1f13446da1d01032e9967cadf66772792))
87
+ * **scope:** the findings of the review of the scope expansion ([92372e5](https://github.com/ManotLuijiu/pi-harness-runtime/commit/92372e51ca31198593025ce8671b226d2ca7182e))
88
+ * **scope:** the question of a proposal is not obsolete and a rejection is named ([d4c58c3](https://github.com/ManotLuijiu/pi-harness-runtime/commit/d4c58c3e63e27449ef1de0f8e4e55ebbf342ff7d))
89
+ * **test:** the quota capture integration needs the runtime of bun ([86fae7d](https://github.com/ManotLuijiu/pi-harness-runtime/commit/86fae7de31e76414aa31bb75eb136155f62d7a40))
90
+ * **workspace:** a strong bench signal decides, and the question is not a fact of an option ([303a828](https://github.com/ManotLuijiu/pi-harness-runtime/commit/303a828f55aa7c4e0a611231f482489b530ff5a3))
91
+ * **workspace:** keep a client name out of the comment about the search depth ([b572e0a](https://github.com/ManotLuijiu/pi-harness-runtime/commit/b572e0af16ff562203bda2b5c47b41807cff5a95))
92
+ * **workspace:** the repository names the mode before the mode stays unknown ([188a32c](https://github.com/ManotLuijiu/pi-harness-runtime/commit/188a32c7a6af1465dd24714278fccc73d06f6477))
93
+
5
94
  ### [1.1.510](https://github.com/ManotLuijiu/pi-harness-runtime/compare/v1.1.448...v1.1.510) (2026-11-16)
6
95
 
7
96
 
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The merge of a mirror record with the row it replaces.
3
+ *
4
+ * The mirror holds one row per provider, and a row holds everything the
5
+ * harness knows about the quota of that provider: the used percentage of
6
+ * the five-hour window, the used percentage of the weekly window, the
7
+ * moments of their resets and the source of the data.
8
+ *
9
+ * Not every write knows all of it. A capture of the quota of the console
10
+ * knows every window. A signal of the TUI knows only that the provider
11
+ * reported a limit, and it carries the remaining percentage of a window it
12
+ * does not name. Such a write replaces the row as it stands, and the
13
+ * evidence of the windows is gone - at the very moment the recovery needs
14
+ * it, because the signal arrives with the failure of the provider.
15
+ *
16
+ * The merge keeps the evidence of the windows and the moment it was
17
+ * observed. A row that carries evidence from an earlier capture is as old
18
+ * as that capture: nothing in the row claims to be fresher than the
19
+ * numbers it holds.
20
+ */
21
+
22
+ import type { ProviderMirrorRecord } from "../mirror.ts";
23
+
24
+ /**
25
+ * Does the record know about a quota window?
26
+ */
27
+ function hasWindowEvidence(
28
+ record: ProviderMirrorRecord | null | undefined,
29
+ ): boolean {
30
+ if (!record) return false;
31
+ return (
32
+ typeof record.h5_used_pct === "number" ||
33
+ typeof record.weekly_used_pct === "number"
34
+ );
35
+ }
36
+
37
+ /**
38
+ * Merge a new record with the row it replaces.
39
+ *
40
+ * A record that knows a window is a full observation: it replaces the row
41
+ * as it stands, because it is newer than the row and it knows more. A
42
+ * record that knows no window is a reduced observation: it adds what it
43
+ * knows and keeps the evidence of the windows.
44
+ */
45
+ export function mergeMirrorRecord(
46
+ previous: ProviderMirrorRecord | null | undefined,
47
+ next: ProviderMirrorRecord,
48
+ ): ProviderMirrorRecord {
49
+ if (!previous) return next;
50
+ if (hasWindowEvidence(next) || !hasWindowEvidence(previous)) {
51
+ // A full observation replaces the row. The model of the provider is
52
+ // kept when the new observation does not name one.
53
+ return { ...next, model: next.model ?? previous.model };
54
+ }
55
+ // A reduced observation: the windows of the row stay, and the row is as
56
+ // old as the evidence it carries.
57
+ return {
58
+ ...previous,
59
+ ...next,
60
+ synced_at: previous.synced_at,
61
+ source: previous.source,
62
+ model: next.model ?? previous.model,
63
+ };
64
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The registration of an event that the compiled API does not declare.
3
+ *
4
+ * The harness compiles against the declarations of one version of the
5
+ * extension API of Pi, and it runs in the core that the user installed.
6
+ * A core that is newer knows events that the declarations do not name
7
+ * yet.
8
+ *
9
+ * The core dispatches the events by name: the handler of an event that
10
+ * the core does not know is never called, and nothing breaks. The helper
11
+ * therefore registers the handler under its name, and the shape of the
12
+ * event is described by the caller instead of being borrowed from a
13
+ * declaration that does not exist yet.
14
+ *
15
+ * The cast lives in this helper and nowhere else: the caller stays typed
16
+ * by the shape of the event it reads.
17
+ */
18
+ export function onOptionalEvent<TEvent>(
19
+ api: unknown,
20
+ eventName: string,
21
+ handler: (event: TEvent) => void,
22
+ ): void {
23
+ const register = api as {
24
+ on(event: string, handler: (event: TEvent) => void): void;
25
+ };
26
+ register.on(eventName, handler);
27
+ }
@@ -36,6 +36,7 @@ import type {
36
36
  } from "./provider-recovery.ts";
37
37
  import { MAX_RESET_EVIDENCE_AGE_MS, normalizeProviderIdentity } from "./provider-recovery.ts";
38
38
  import { QUOTA_RESET_BUFFER_MS } from "./provider-quota-reset.ts";
39
+ import type { WeeklyQuotaExhaustion } from "./weekly-quota-exhaustion.ts";
39
40
 
40
41
  /**
41
42
  * The state of the session, read when a resume would run.
@@ -162,6 +163,24 @@ export interface ProviderRecoveryRuntimeOptions {
162
163
  resetEvidence?: (failure: ProviderFailure) => RecoveryResetEvidence | undefined;
163
164
  /** Fresh evidence that quota is fully consumed, including for generic 2067 errors. */
164
165
  quotaResetEvidence?: (failure: ProviderFailure, provider: string) => RecoveryResetEvidence | undefined;
166
+ /**
167
+ * The evidence of an empty weekly allowance.
168
+ *
169
+ * The weekly window lasts days: no bounded cycle of retries reaches its
170
+ * end, and the work stays paused until the human decides what happens.
171
+ * The runtime asks for the evidence before it schedules anything.
172
+ */
173
+ weeklyExhaustionEvidence?: (
174
+ failure: ProviderFailure,
175
+ provider: string,
176
+ ) => WeeklyQuotaExhaustion | undefined;
177
+ /**
178
+ * The notification of an empty weekly allowance.
179
+ *
180
+ * The runtime owns no channel: it hands the evidence to the caller,
181
+ * which owns the messages to the user.
182
+ */
183
+ onWeeklyExhaustion?: (exhaustion: WeeklyQuotaExhaustion) => void;
165
184
  /** The number of attempts the cycle allows. */
166
185
  maxAttempts: number;
167
186
  /** The wait of the overload executor, in milliseconds. */
@@ -269,7 +288,7 @@ export class ProviderRecoveryRuntime {
269
288
  }
270
289
 
271
290
  if (candidate.overloadEligible) {
272
- this.startOverloadResume();
291
+ this.scheduleOverloadResume();
273
292
  return;
274
293
  }
275
294
  if (!candidate.boundedEligible) {
@@ -378,6 +397,11 @@ export class ProviderRecoveryRuntime {
378
397
  private startRecovery(candidate: ProviderFailureCandidate): void {
379
398
  const { failure, failureKey, provider } = candidate;
380
399
  const sessionId = this.options.context().sessionId;
400
+ // An empty weekly allowance is not a wait of the cycle: it lasts
401
+ // days, and the human decides what happens. The check comes before
402
+ // the ordinary reset, because the ordinary reset would schedule the
403
+ // work to continue on its own.
404
+ if (this.blockOnWeeklyExhaustion(candidate, sessionId)) return;
381
405
  // A real quota reset is a different wait from a transient retry.
382
406
  // It remains available even after the four short retries were used.
383
407
  if (this.scheduleQuotaReset(candidate, sessionId)) return;
@@ -416,6 +440,110 @@ export class ProviderRecoveryRuntime {
416
440
  );
417
441
  }
418
442
 
443
+ /**
444
+ * Block the work because the weekly allowance of the provider is empty.
445
+ *
446
+ * The weekly window lasts days, so no attempt of the cycle reaches its
447
+ * end. The runtime therefore registers the blocked row and hands the
448
+ * evidence to the caller, which asks the user what happens. Nothing is
449
+ * scheduled: the work continues when the user says so, not before.
450
+ *
451
+ * The evidence decides, and the evidence has to be fresh. A row of the
452
+ * mirror that is hours old describes a week that may already have been
453
+ * paid for.
454
+ */
455
+ private blockOnWeeklyExhaustion(
456
+ candidate: ProviderFailureCandidate,
457
+ sessionId: string,
458
+ ): boolean {
459
+ const { failure, provider } = candidate;
460
+ if (failure.kind !== "usage-exhausted" && failure.kind !== "rate-limit") {
461
+ return false;
462
+ }
463
+ const exhaustion = this.options.weeklyExhaustionEvidence?.(
464
+ failure,
465
+ provider,
466
+ );
467
+ if (!exhaustion) return false;
468
+ // Every pending resume of the provider dies: a resume that runs
469
+ // while the weekly allowance is empty continues work that the
470
+ // account cannot pay for.
471
+ this.cancelRecoveryAttempt();
472
+ this.cancelOverloadResume();
473
+ this.options.actions.remove(this.options.blockedActionId);
474
+ this.options.actions.register({
475
+ id: this.options.blockedActionId,
476
+ sessionId,
477
+ owner: "provider",
478
+ kind: "retry",
479
+ state: "blocked",
480
+ provider,
481
+ ...(failure.code ? { code: failure.code } : {}),
482
+ reason: "weekly quota exhausted; waiting for the user",
483
+ });
484
+ this.log(
485
+ `Provider weekly quota exhausted (${provider}): the work waits for the user`,
486
+ );
487
+ this.options.onWeeklyExhaustion?.(exhaustion);
488
+ return true;
489
+ }
490
+
491
+ /**
492
+ * Count down to the reset of an empty weekly allowance.
493
+ *
494
+ * The human asked for it: the harness waits for the reset of the week
495
+ * plus the buffer of the quota service, and continues then. This is the
496
+ * only way the work continues after a weekly exhaustion, and the
497
+ * silence of the human keeps the work paused.
498
+ */
499
+ scheduleWeeklyReset(resetAt: number, provider?: string): boolean {
500
+ const sessionId = this.options.context().sessionId;
501
+ const now = this.now();
502
+ if (!Number.isFinite(resetAt) || resetAt <= now) return false;
503
+ const dueAt = resetAt + QUOTA_RESET_BUFFER_MS;
504
+ this.cancelRecoveryAttempt();
505
+ this.options.actions.remove(this.options.blockedActionId);
506
+ this.options.actions.register({
507
+ id: this.options.recoveryActionId,
508
+ sessionId,
509
+ owner: "provider-recovery",
510
+ kind: "retry",
511
+ state: "scheduled",
512
+ dueAt,
513
+ ...(provider ? { provider } : {}),
514
+ reason: "weekly quota exhausted; waiting for the reset + 10m",
515
+ });
516
+ this.log(
517
+ `Provider weekly quota reset wait until ${new Date(dueAt).toISOString()}`,
518
+ );
519
+ const arm = () => {
520
+ // Node timers longer than roughly 24 days otherwise fire
521
+ // immediately.
522
+ this.recoveryTimer = this.setTimer(() => {
523
+ if (this.now() < dueAt) {
524
+ arm();
525
+ return;
526
+ }
527
+ this.recoveryTimer = null;
528
+ this.options.actions.remove(this.options.recoveryActionId);
529
+ if (
530
+ !mayDispatchResume({
531
+ scheduledSessionId: sessionId,
532
+ current: this.options.context(),
533
+ }).allowed
534
+ ) {
535
+ return;
536
+ }
537
+ if (provider) {
538
+ this.options.controller.cancel({ sessionId, provider });
539
+ }
540
+ this.dispatchIfOwned(sessionId, "provider-recovery");
541
+ }, Math.min(2_147_483_647, Math.max(0, dueAt - this.now())));
542
+ };
543
+ arm();
544
+ return true;
545
+ }
546
+
419
547
  private scheduleQuotaReset(candidate: ProviderFailureCandidate, sessionId: string): boolean {
420
548
  const { failure, provider } = candidate;
421
549
  if (failure.kind !== "usage-exhausted" && failure.kind !== "rate-limit") return false;
@@ -522,15 +650,25 @@ export class ProviderRecoveryRuntime {
522
650
  }
523
651
 
524
652
  /**
525
- * Start the timer of the overload resume.
653
+ * Schedule the overload resume.
654
+ *
655
+ * The executor of the overload owns the timer and the budget, so
656
+ * every overload shares them: one countdown, one resume, and the same
657
+ * limit of attempts. A compaction that fails with the same overload is
658
+ * such an overload - it is a request of its own, and it fails with the
659
+ * same number - so it comes here too.
660
+ *
661
+ * The method returns whether a countdown was armed. A refusal - the
662
+ * budget is spent, or the user cancelled the delay - is not a silent
663
+ * one: the caller reports it.
526
664
  */
527
- private startOverloadResume(): void {
665
+ scheduleOverloadResume(): boolean {
528
666
  const limit = this.options.overloadMaxAttempts ?? 3;
529
667
  if (this.overloadAttempts >= limit) {
530
668
  this.log(
531
669
  `Provider overload resume not scheduled: ${this.overloadAttempts}/${limit} attempts used`,
532
670
  );
533
- return;
671
+ return false;
534
672
  }
535
673
  this.cancelOverloadResume();
536
674
  this.overloadAttempts += 1;
@@ -551,6 +689,7 @@ export class ProviderRecoveryRuntime {
551
689
  this.options.actions.remove(this.options.overloadActionId);
552
690
  this.dispatchIfOwned(sessionId, "provider-overload");
553
691
  }, delayMs);
692
+ return true;
554
693
  }
555
694
 
556
695
  /**
@@ -0,0 +1,178 @@
1
+ /**
2
+ * The decision of the human about an empty weekly allowance.
3
+ *
4
+ * The weekly allowance of a provider blocks the work until the human
5
+ * decides what happens. There are two choices:
6
+ *
7
+ * - the harness counts down to the reset of the week and continues then,
8
+ * - the human deals with the account itself.
9
+ *
10
+ * The decision belongs to the human alone. The judge is never asked, and
11
+ * there is no timeout that decides: a silence keeps the work paused. The
12
+ * registry therefore holds the decision, the delivery of the message and
13
+ * the identity of the answer - and it holds the first answer, because a
14
+ * second click on an old button must not change a decision that was made.
15
+ */
16
+
17
+ /** The choices of the human. */
18
+ export type WeeklyDecision = "countdown" | "manual";
19
+
20
+ /** The channel a decision came from. */
21
+ export type WeeklyDecisionChannel = "telegram" | "line";
22
+
23
+ /**
24
+ * One exhausted weekly allowance.
25
+ */
26
+ export interface WeeklyExhaustionRecord {
27
+ /** The canonical id of the decision. */
28
+ requestId: string;
29
+ /** The provider whose weekly allowance is empty. */
30
+ provider: string;
31
+ /** The absolute epoch of the weekly reset. */
32
+ resetAt: number;
33
+ /** When the decision was requested. */
34
+ createdAt: number;
35
+ /** Did the message reach the user? */
36
+ delivered: boolean;
37
+ /** The choice of the human. */
38
+ decision?: WeeklyDecision;
39
+ /** When the human decided. */
40
+ decidedAt?: number;
41
+ /** The channel the decision came from. */
42
+ channel?: WeeklyDecisionChannel;
43
+ }
44
+
45
+ /**
46
+ * The result of a claim of the registry.
47
+ *
48
+ * The shape is flat on purpose: the harness compiles the strict and the
49
+ * lenient variant of TypeScript, and the narrowing of a discriminated
50
+ * union is not available in both of them.
51
+ */
52
+ export interface WeeklyClaimResult {
53
+ /** Did the human take the decision? */
54
+ ok: boolean;
55
+ /** The decision that was taken. */
56
+ record?: WeeklyExhaustionRecord;
57
+ /** Why the decision was refused. */
58
+ reason?: string;
59
+ }
60
+
61
+ /**
62
+ * The registry of the weekly decisions.
63
+ *
64
+ * One entry per exhausted weekly allowance. The entry is registered
65
+ * before the message is delivered, so that a click that arrives before
66
+ * the delivery is acknowledged still finds its decision; and it is
67
+ * removed when the delivery fails, because a decision nobody can reach
68
+ * would wait for an answer that never comes.
69
+ */
70
+ export class WeeklyExhaustionRegistry {
71
+ private readonly records = new Map<string, WeeklyExhaustionRecord>();
72
+
73
+ /**
74
+ * Register the decision of an exhausted weekly allowance.
75
+ *
76
+ * A decision that is already registered is kept: the second
77
+ * registration of the same exhaustion is the same decision.
78
+ */
79
+ register(params: {
80
+ requestId: string;
81
+ provider: string;
82
+ resetAt: number;
83
+ now: number;
84
+ }): WeeklyExhaustionRecord {
85
+ const existing = this.records.get(params.requestId);
86
+ if (existing) return existing;
87
+ const record: WeeklyExhaustionRecord = {
88
+ requestId: params.requestId,
89
+ provider: params.provider,
90
+ resetAt: params.resetAt,
91
+ createdAt: params.now,
92
+ delivered: false,
93
+ };
94
+ this.records.set(params.requestId, record);
95
+ return record;
96
+ }
97
+
98
+ /** The decision of an id. */
99
+ get(requestId: string): WeeklyExhaustionRecord | undefined {
100
+ return this.records.get(requestId);
101
+ }
102
+
103
+ /** Every decision that waits for an answer. */
104
+ get pending(): WeeklyExhaustionRecord[] {
105
+ return [...this.records.values()].filter(
106
+ (record) => record.decision === undefined,
107
+ );
108
+ }
109
+
110
+ /** Did the message of the decision reach the user? */
111
+ markDelivered(requestId: string): boolean {
112
+ const record = this.records.get(requestId);
113
+ if (!record) return false;
114
+ record.delivered = true;
115
+ return true;
116
+ }
117
+
118
+ /**
119
+ * Take the decision of the human.
120
+ *
121
+ * The first answer wins: a second answer for the same decision is
122
+ * stale, and the reason says so. An answer for a decision that does
123
+ * not exist is stale as well - the button is older than the session.
124
+ */
125
+ claim(
126
+ requestId: string,
127
+ decision: WeeklyDecision,
128
+ channel: WeeklyDecisionChannel,
129
+ now: number,
130
+ ): WeeklyClaimResult {
131
+ const record = this.records.get(requestId);
132
+ if (!record) {
133
+ return { ok: false, reason: "the decision does not exist any more" };
134
+ }
135
+ if (record.decision !== undefined) {
136
+ return {
137
+ ok: false,
138
+ reason: `the decision was already made (${record.decision})`,
139
+ };
140
+ }
141
+ record.decision = decision;
142
+ record.decidedAt = now;
143
+ record.channel = channel;
144
+ return { ok: true, record };
145
+ }
146
+
147
+ /** Remove a decision. */
148
+ remove(requestId: string): boolean {
149
+ return this.records.delete(requestId);
150
+ }
151
+
152
+ /** Remove every decision. */
153
+ clear(): void {
154
+ this.records.clear();
155
+ }
156
+ }
157
+
158
+ /**
159
+ * The canonical id of a weekly decision.
160
+ *
161
+ * The id travels through the callback data of a button, and that data is
162
+ * split on the underscore: an id with an underscore would be cut in two.
163
+ * The id therefore holds no underscore, and it is short enough for the
164
+ * postback data of LINE.
165
+ */
166
+ export function buildWeeklyRequestId(
167
+ provider: string,
168
+ resetAt: number,
169
+ ): string {
170
+ const key = `${provider.toLowerCase()}:${resetAt}`;
171
+ let hash = 2166136261;
172
+ for (let i = 0; i < key.length; i += 1) {
173
+ hash ^= key.charCodeAt(i);
174
+ hash = Math.imul(hash, 16777619);
175
+ }
176
+ const hex = (hash >>> 0).toString(16).padStart(8, "0");
177
+ return `week-${provider.toLowerCase()}-${hex}`;
178
+ }