chainlesschain 0.162.188 → 0.162.193

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 (337) hide show
  1. package/README.md +61 -11
  2. package/bin/chainlesschain.js +7 -52
  3. package/completions/_cc +209 -0
  4. package/completions/cc.bash +18 -0
  5. package/completions/cc.fish +13 -0
  6. package/completions/cc.ps1 +226 -0
  7. package/package.json +10 -2
  8. package/src/assets/web-panel/assets/{AIOps-Brr1LVcE.js → AIOps-DBLkaTje.js} +1 -1
  9. package/src/assets/web-panel/assets/{ActionButton-DQU74DKG.js → ActionButton-BAy-Qebo.js} +1 -1
  10. package/src/assets/web-panel/assets/{Analytics-CYp9178y.js → Analytics-Dfb1Mlau.js} +3 -3
  11. package/src/assets/web-panel/assets/{AppLayout-DW4SCYsW.js → AppLayout-BbFkN8m0.js} +5 -5
  12. package/src/assets/web-panel/assets/{Artifacts-CYlD_ed1.js → Artifacts-kM4-cEEH.js} +1 -1
  13. package/src/assets/web-panel/assets/{Audit-CWl1rZOi.js → Audit-BSQfYWf3.js} +1 -1
  14. package/src/assets/web-panel/assets/{BackgroundAgents-BOR-LPsa.js → BackgroundAgents-CWDbI_fG.js} +1 -1
  15. package/src/assets/web-panel/assets/{Backup-DLpG7j1X.js → Backup-BxLPbq_Q.js} +1 -1
  16. package/src/assets/web-panel/assets/{BaseInput-B35K9wdr.js → BaseInput-DuIbdrp6.js} +1 -1
  17. package/src/assets/web-panel/assets/{Chat-CwUJb9gB.js → Chat-NEmjGahU.js} +5 -5
  18. package/src/assets/web-panel/assets/{ChatBubbleRenderer-1v6aMS1m.js → ChatBubbleRenderer-DfJEo-5_.js} +1 -1
  19. package/src/assets/web-panel/assets/{Checkbox-pi3-tPNW.js → Checkbox-CaoeG3Ns.js} +1 -1
  20. package/src/assets/web-panel/assets/{Codegen-FyNF35eL.js → Codegen-BFf_g3xY.js} +1 -1
  21. package/src/assets/web-panel/assets/{Col-tGt_JDEr.js → Col-CNOd8mdQ.js} +1 -1
  22. package/src/assets/web-panel/assets/{Community-CC7LonQX.js → Community-BhpDqz-i.js} +1 -1
  23. package/src/assets/web-panel/assets/{Compact-BGXrHHjE.js → Compact-CQ42T7Z6.js} +1 -1
  24. package/src/assets/web-panel/assets/{Compliance-DSW0TBZ8.js → Compliance-DI5PcLMN.js} +1 -1
  25. package/src/assets/web-panel/assets/{Cowork-Bhk7rbvE.js → Cowork-wYYZe0wR.js} +3 -3
  26. package/src/assets/web-panel/assets/{Cron-DxyiQ2NZ.js → Cron-Dlq03DD_.js} +2 -2
  27. package/src/assets/web-panel/assets/{Crosschain-B2ZkxHok.js → Crosschain-BzqS8PP3.js} +1 -1
  28. package/src/assets/web-panel/assets/{DID-yOJV99eJ.js → DID-It55Yem7.js} +2 -2
  29. package/src/assets/web-panel/assets/{Dashboard-CKsttz7D.js → Dashboard-9HkH6oxn.js} +2 -2
  30. package/src/assets/web-panel/assets/{Dropdown-CVFldXSL.js → Dropdown-00e2YWRB.js} +1 -1
  31. package/src/assets/web-panel/assets/{EmailListRenderer-Bufv638J.js → EmailListRenderer-By-ugRDL.js} +1 -1
  32. package/src/assets/web-panel/assets/{FamilyGuardDashboard-4ncjoIjL.js → FamilyGuardDashboard-C396yu5m.js} +1 -1
  33. package/src/assets/web-panel/assets/{Federation-DsknEDoX.js → Federation-BME5sbZY.js} +1 -1
  34. package/src/assets/web-panel/assets/{FormItemContext-Cqe5jWXA.js → FormItemContext-B4TEZCr-.js} +1 -1
  35. package/src/assets/web-panel/assets/{GenericCardRenderer-NAJaFKxc.js → GenericCardRenderer-_9CX9ieY.js} +1 -1
  36. package/src/assets/web-panel/assets/{Git-CszKQpnl.js → Git-BrS6WVSr.js} +2 -2
  37. package/src/assets/web-panel/assets/{Governance-BXGodXi6.js → Governance-BMdCWnKF.js} +1 -1
  38. package/src/assets/web-panel/assets/{Inference-CkoYuG2c.js → Inference-Bcp3vzcA.js} +1 -1
  39. package/src/assets/web-panel/assets/{KnowledgeGraph-DFlEr_T0.js → KnowledgeGraph-DlLuqGY5.js} +1 -1
  40. package/src/assets/web-panel/assets/{Logs-CVaENddA.js → Logs-D-W_6x09.js} +2 -2
  41. package/src/assets/web-panel/assets/MarkdownRenderer-DElGPxCZ.js +1 -0
  42. package/src/assets/web-panel/assets/{Marketplace-CDlLT0fw.js → Marketplace-Dzn2guvI.js} +1 -1
  43. package/src/assets/web-panel/assets/{McpTools-DdwOyszN.js → McpTools-uPict-KL.js} +6 -6
  44. package/src/assets/web-panel/assets/{Memory-DKQnkKuG.js → Memory-BCw43kOb.js} +2 -2
  45. package/src/assets/web-panel/assets/{MobileBridge-DGseqlzJ.js → MobileBridge-DmV8Wv7F.js} +1 -1
  46. package/src/assets/web-panel/assets/{MobileProjects-COBbEOlj.js → MobileProjects-C-HaCmSM.js} +1 -1
  47. package/src/assets/web-panel/assets/{Mtc-O61Vwyli.js → Mtc-C6jxJ34Y.js} +5 -5
  48. package/src/assets/web-panel/assets/{MtcAudit-Dw2SyasS.js → MtcAudit-Za8ExwhQ.js} +5 -5
  49. package/src/assets/web-panel/assets/{Multisig-hSu_l8kf.js → Multisig-KKDbuEgb.js} +3 -3
  50. package/src/assets/web-panel/assets/{NLProgramming-CX1Epurr.js → NLProgramming-Dj97zbCk.js} +1 -1
  51. package/src/assets/web-panel/assets/{Notes-R9xX8o8_.js → Notes-DBXvMraU.js} +4 -4
  52. package/src/assets/web-panel/assets/{NotificationSettings-jtSNLCuK.js → NotificationSettings-DOxITLYl.js} +1 -1
  53. package/src/assets/web-panel/assets/OrderTableRenderer-7DVjZwMM.js +1 -0
  54. package/src/assets/web-panel/assets/{Organization-Pu2WO-U3.js → Organization-D1i73mjb.js} +4 -4
  55. package/src/assets/web-panel/assets/{Overflow-BjnqUyFp.js → Overflow-kW6Q3rvg.js} +1 -1
  56. package/src/assets/web-panel/assets/{P2P-jjkvz44c.js → P2P-C-v_8p2v.js} +2 -2
  57. package/src/assets/web-panel/assets/PdhVaultBrowser-tUbbY64W.js +7 -0
  58. package/src/assets/web-panel/assets/{Permissions-D4yDpivd.js → Permissions-DkHxEZ58.js} +4 -4
  59. package/src/assets/web-panel/assets/{PersonalDataHub-0qsL6iH1.js → PersonalDataHub-DWuMPGrK.js} +5 -5
  60. package/src/assets/web-panel/assets/{Pipeline-Cx7Ybrk2.js → Pipeline-30IYXWWm.js} +1 -1
  61. package/src/assets/web-panel/assets/{Privacy-PbfR_M_V.js → Privacy-DZNQ4RrH.js} +1 -1
  62. package/src/assets/web-panel/assets/{ProjectInit-CyV6Gsub.js → ProjectInit-De2MCElf.js} +2 -2
  63. package/src/assets/web-panel/assets/{ProjectSettings-C7KZ2Wdk.js → ProjectSettings-5uHk9wsC.js} +2 -2
  64. package/src/assets/web-panel/assets/{Projects-DQDjO-yK.js → Projects-XjDfrFLb.js} +1 -1
  65. package/src/assets/web-panel/assets/{Providers-DyFVBBMX.js → Providers-Bgwj6gcE.js} +1 -1
  66. package/src/assets/web-panel/assets/{QrScannerModal-CzB1BC9_.js → QrScannerModal-gKql9umv.js} +1 -1
  67. package/src/assets/web-panel/assets/{QuickAsk-Bk636mC1.js → QuickAsk-BWvmwkh7.js} +1 -1
  68. package/src/assets/web-panel/assets/{Recommend-DoWxHIT3.js → Recommend-Uok4hZPd.js} +1 -1
  69. package/src/assets/web-panel/assets/{RemoteSession-oOVIv9wq.js → RemoteSession-DLJzTk9a.js} +3 -3
  70. package/src/assets/web-panel/assets/{Reputation-BucoReGG.js → Reputation-ZVwIPMSO.js} +1 -1
  71. package/src/assets/web-panel/assets/{Row-DzmOdJU7.js → Row-CN04HxWR.js} +1 -1
  72. package/src/assets/web-panel/assets/{RssFeed-C1tK7KGU.js → RssFeed-BdSrEG4g.js} +3 -3
  73. package/src/assets/web-panel/assets/{Search-CSnInOqk.js → Search-5PwVd0IR.js} +1 -1
  74. package/src/assets/web-panel/assets/{Security-dlejr15l.js → Security-DdBo4zjN.js} +3 -3
  75. package/src/assets/web-panel/assets/{Services-BioPZuNh.js → Services-D3letU7M.js} +2 -2
  76. package/src/assets/web-panel/assets/{Skeleton-DWMibwpC.js → Skeleton--Jb83f1v.js} +1 -1
  77. package/src/assets/web-panel/assets/{Skills-BAAnx1B2.js → Skills-Bg-CulHX.js} +1 -1
  78. package/src/assets/web-panel/assets/{Sla-jWNp4hNO.js → Sla-7QOa7S-X.js} +1 -1
  79. package/src/assets/web-panel/assets/{SpeechSettings-y5kqKha-.js → SpeechSettings-DQwppjRw.js} +1 -1
  80. package/src/assets/web-panel/assets/{SyncSettings-B9GNsc3e.js → SyncSettings-dNPQGL-s.js} +2 -2
  81. package/src/assets/web-panel/assets/{Tasks-BDBYKRen.js → Tasks-Ggs-Z48q.js} +1 -1
  82. package/src/assets/web-panel/assets/{Templates-DRiE5eaN.js → Templates-78TYHgRO.js} +1 -1
  83. package/src/assets/web-panel/assets/{Tenant-BGlAvExF.js → Tenant-xHwwv9vO.js} +1 -1
  84. package/src/assets/web-panel/assets/{Terminal-B8uzrbNY.js → Terminal-BJXSJfm4.js} +2 -2
  85. package/src/assets/web-panel/assets/{TimelineRenderer-Df48iveY.js → TimelineRenderer-fLbjRhJw.js} +1 -1
  86. package/src/assets/web-panel/assets/{Tokens-CcmHndN6.js → Tokens-oMSBSBmB.js} +1 -1
  87. package/src/assets/web-panel/assets/{Trigger-DPkWxmQ2.js → Trigger-CfnY_wX_.js} +1 -1
  88. package/src/assets/web-panel/assets/{Trust-DTb5a5AV.js → Trust-AdyTgYKO.js} +1 -1
  89. package/src/assets/web-panel/assets/{UkeySign-CBmg5vch.js → UkeySign-C5K_81dS.js} +1 -1
  90. package/src/assets/web-panel/assets/{VideoEditing-B0mZrz4O.js → VideoEditing-vcGVDqki.js} +1 -1
  91. package/src/assets/web-panel/assets/{Wallet-Bxs7_mpd.js → Wallet-hhOc3hlY.js} +4 -4
  92. package/src/assets/web-panel/assets/{WebAuthn-C8x3cMxU.js → WebAuthn-CVloC11s.js} +3 -3
  93. package/src/assets/web-panel/assets/{WorkflowEditor-DPrNznrP.js → WorkflowEditor-CYeE32R5.js} +1 -1
  94. package/src/assets/web-panel/assets/{chat-D3bYWu7S.js → chat-CNROR5bN.js} +1 -1
  95. package/src/assets/web-panel/assets/{colors-DY-PwMu4.js → colors-Cjx-cnwU.js} +1 -1
  96. package/src/assets/web-panel/assets/{compact-item-LDk10Kw6.js → compact-item-DOIfelvD.js} +1 -1
  97. package/src/assets/web-panel/assets/{createContext-C-2MZnFq.js → createContext-DfA7UZ8u.js} +1 -1
  98. package/src/assets/web-panel/assets/devWarning-ChcCBGs7.js +1 -0
  99. package/src/assets/web-panel/assets/{hasIn-BQIBjcnB.js → hasIn-BMSCzcfM.js} +1 -1
  100. package/src/assets/web-panel/assets/{index-CQVb2dWp.js → index-5-HXgOX5.js} +1 -1
  101. package/src/assets/web-panel/assets/{index-BdXnYMCZ.js → index-AWg-0M1S.js} +1 -1
  102. package/src/assets/web-panel/assets/{index-Cx6D_dx2.js → index-B4iYzpkL.js} +1 -1
  103. package/src/assets/web-panel/assets/{index-_HRO_cIu.js → index-B5Udeb_6.js} +1 -1
  104. package/src/assets/web-panel/assets/{index-DlRYqt3S.js → index-B7gf77CJ.js} +1 -1
  105. package/src/assets/web-panel/assets/{index-BrnRO9yE.js → index-BEMwBBHk.js} +1 -1
  106. package/src/assets/web-panel/assets/{index-VCh5zNJo.js → index-BM1y_9hM.js} +1 -1
  107. package/src/assets/web-panel/assets/{index-BRI3ngNg.js → index-BUonmKSE.js} +1 -1
  108. package/src/assets/web-panel/assets/{index-C3GNvExG.js → index-BbQ2eQ8H.js} +1 -1
  109. package/src/assets/web-panel/assets/{index-DSvo_bp0.js → index-BemJ2u_E.js} +1 -1
  110. package/src/assets/web-panel/assets/{index-L6qixyLc.js → index-BolaOQxx.js} +1 -1
  111. package/src/assets/web-panel/assets/{index-BI4KgcYC.js → index-BxOk9vkG.js} +1 -1
  112. package/src/assets/web-panel/assets/{index-CY4KnaO9.js → index-By61ojUx.js} +1 -1
  113. package/src/assets/web-panel/assets/{index-L3smcoQX.js → index-C2K9SNVX.js} +1 -1
  114. package/src/assets/web-panel/assets/{index-BX2b9Orc.js → index-C3L5gdiD.js} +1 -1
  115. package/src/assets/web-panel/assets/{index-Cz4b6Z_7.js → index-C7xn0Nub.js} +1 -1
  116. package/src/assets/web-panel/assets/{index-COG61sRv.js → index-CAnvhwg6.js} +1 -1
  117. package/src/assets/web-panel/assets/{index-C7FC8cP2.js → index-CEKMcOyU.js} +1 -1
  118. package/src/assets/web-panel/assets/{index-BN-xdSWZ.js → index-CNC5onm4.js} +1 -1
  119. package/src/assets/web-panel/assets/{index-DY2FIrmz.js → index-CVL27kXC.js} +1 -1
  120. package/src/assets/web-panel/assets/{index-CiTvBAr-.js → index-CVm1_i3t.js} +1 -1
  121. package/src/assets/web-panel/assets/{index-DhRt9cYJ.js → index-CdYBye8B.js} +1 -1
  122. package/src/assets/web-panel/assets/{index-B5pgtZnY.js → index-ClNMrqEY.js} +1 -1
  123. package/src/assets/web-panel/assets/{index-7xKu7Fns.js → index-Cs6l7uRu.js} +1 -1
  124. package/src/assets/web-panel/assets/{index-D4K1weKc.js → index-CshQbilz.js} +1 -1
  125. package/src/assets/web-panel/assets/{index-k7C_oDCO.js → index-Cyweh0Hy.js} +1 -1
  126. package/src/assets/web-panel/assets/{index-D3Oq-DLL.js → index-DBpWXFed.js} +3 -3
  127. package/src/assets/web-panel/assets/{index-DYyLJPlF.js → index-DHtpHZAQ.js} +1 -1
  128. package/src/assets/web-panel/assets/{index-Dh-tkpKQ.js → index-DLmn0BoK.js} +1 -1
  129. package/src/assets/web-panel/assets/{index-8JC9BJa1.js → index-DPAWBrMf.js} +1 -1
  130. package/src/assets/web-panel/assets/{index-Dd2Km97U.js → index-DjEsxO5h.js} +1 -1
  131. package/src/assets/web-panel/assets/{index-KFZO_lcx.js → index-FBc_CJBd.js} +1 -1
  132. package/src/assets/web-panel/assets/{index-DTIZpPtG.js → index-Icdoqmzt.js} +1 -1
  133. package/src/assets/web-panel/assets/index-Q2IajL54.js +1 -0
  134. package/src/assets/web-panel/assets/index-bRkHgOMc.js +1 -0
  135. package/src/assets/web-panel/assets/{index-lmm9p-jm.js → index-dCd8cSUq.js} +1 -1
  136. package/src/assets/web-panel/assets/{index-HasPt4-h.js → index-m2vG9gG_.js} +1 -1
  137. package/src/assets/web-panel/assets/{index-CaslYch6.js → index-mTpHoEzr.js} +1 -1
  138. package/src/assets/web-panel/assets/{index-CbR6ROOa.js → index-ti_lnTWl.js} +1 -1
  139. package/src/assets/web-panel/assets/{initDefaultProps-zQPSHf2C.js → initDefaultProps-Bu8k7H1Y.js} +1 -1
  140. package/src/assets/web-panel/assets/{motion-CKCStGVk.js → motion-s3iVK41k.js} +1 -1
  141. package/src/assets/web-panel/assets/{move-BufVDGYF.js → move-B6B-E5Jz.js} +1 -1
  142. package/src/assets/web-panel/assets/{mtc-parser-DcaFxy5D.js → mtc-parser-BiYgTidA.js} +1 -1
  143. package/src/assets/web-panel/assets/{omit-EScpkGdo.js → omit-pU1RdUDA.js} +1 -1
  144. package/src/assets/web-panel/assets/{pickAttrs-72hG_qfT.js → pickAttrs-Cdoq_SeM.js} +1 -1
  145. package/src/assets/web-panel/assets/{placementArrow-CMFWiH20.js → placementArrow-DIuvAn2K.js} +1 -1
  146. package/src/assets/web-panel/assets/{responsiveObserve-DKQHS41p.js → responsiveObserve-8w16YR2D.js} +1 -1
  147. package/src/assets/web-panel/assets/{slide-QVAFHTIQ.js → slide-VZ01cZe3.js} +1 -1
  148. package/src/assets/web-panel/assets/{statusUtils-DIz38e2G.js → statusUtils-lh8YMN8Z.js} +1 -1
  149. package/src/assets/web-panel/assets/{styleChecker-zK5cyLby.js → styleChecker-CmDyreec.js} +1 -1
  150. package/src/assets/web-panel/assets/{useFlexGapSupport-DhZngk62.js → useFlexGapSupport-hiJWMU5y.js} +1 -1
  151. package/src/assets/web-panel/assets/{useFs-BvV2cvkg.js → useFs-Thnu-Iaj.js} +1 -1
  152. package/src/assets/web-panel/assets/{usePersonalDataHub-CRmxb9l3.js → usePersonalDataHub-LBdOxjwY.js} +1 -1
  153. package/src/assets/web-panel/assets/{vnode-CgQIbobP.js → vnode-Cg6lFY_X.js} +1 -1
  154. package/src/assets/web-panel/assets/{zoom-D4XrrO0R.js → zoom-DVfsR1YO.js} +1 -1
  155. package/src/assets/web-panel/index.html +1 -1
  156. package/src/cli-help.js +181 -0
  157. package/src/command-help-index.json +181 -0
  158. package/src/command-manifest.json +1107 -175
  159. package/src/command-surface-policy.js +197 -0
  160. package/src/commands/agent.js +98 -33
  161. package/src/commands/artifacts.js +400 -2
  162. package/src/commands/background-session.js +41 -3
  163. package/src/commands/checkpoint-managed.js +1059 -0
  164. package/src/commands/checkpoint-restore-recovery.js +1476 -0
  165. package/src/commands/checkpoint.js +950 -22
  166. package/src/commands/compact.js +101 -25
  167. package/src/commands/config.js +506 -20
  168. package/src/commands/doctor.js +4 -1
  169. package/src/commands/hub.js +1 -1
  170. package/src/commands/mcp.js +688 -24
  171. package/src/commands/pack.js +16 -2
  172. package/src/commands/plugin.js +20 -12
  173. package/src/commands/session-mcp-recovery.js +218 -0
  174. package/src/commands/session.js +470 -110
  175. package/src/commands/setup.js +36 -10
  176. package/src/commands/skill.js +181 -110
  177. package/src/commands/status.js +21 -5
  178. package/src/commands/team-distributed.js +3324 -0
  179. package/src/commands/team.js +1130 -74
  180. package/src/commands/update.js +68 -6
  181. package/src/constants.js +11 -0
  182. package/src/data/changelog.json +26 -0
  183. package/src/gateways/ws/action-protocol.js +10 -0
  184. package/src/gateways/ws/session-protocol.js +555 -27
  185. package/src/gateways/ws/ws-agent-handler.js +541 -14
  186. package/src/gateways/ws/ws-session-gateway.js +129 -22
  187. package/src/gateways/ws/ws-session-state.js +431 -0
  188. package/src/harness/background-task-manager.js +233 -36
  189. package/src/harness/jsonl-session-store.js +2551 -167
  190. package/src/harness/mcp-client.js +802 -61
  191. package/src/harness/prompt-compressor.js +227 -27
  192. package/src/harness/session-index.js +89 -38
  193. package/src/harness/session-list-index.js +254 -0
  194. package/src/harness/structured-handoff.js +410 -0
  195. package/src/lazy-dispatch.js +747 -84
  196. package/src/lib/__tests__/logger.test.js +50 -2
  197. package/src/lib/advisor-runtime.js +1047 -0
  198. package/src/lib/agent-core.js +2 -0
  199. package/src/lib/agent-sandbox.js +120 -26
  200. package/src/lib/agent-session-export.js +20 -0
  201. package/src/lib/agent-team/task-lease.js +271 -3
  202. package/src/lib/agent-team/team-adjudication.js +1501 -0
  203. package/src/lib/agent-team/team-budget.js +4 -1
  204. package/src/lib/agent-team/team-control-store.js +582 -0
  205. package/src/lib/agent-team/team-distributed-queue.js +5246 -0
  206. package/src/lib/agent-team/team-process-checkpoint.js +211 -0
  207. package/src/lib/agent-team/team-runner.js +543 -24
  208. package/src/lib/agent-team/team-worktree.js +1403 -95
  209. package/src/lib/artifact-store.js +131 -8
  210. package/src/lib/background-agent-supervisor.js +185 -13
  211. package/src/lib/background-interaction-journal.js +37 -9
  212. package/src/lib/background-launch-profile.js +1058 -0
  213. package/src/lib/checkpoint-restore-already-completed-controller.js +902 -0
  214. package/src/lib/checkpoint-restore-orchestrator.js +987 -0
  215. package/src/lib/checkpoint-restore-partial-rollback-controller.js +1953 -0
  216. package/src/lib/checkpoint-restore-recovery-controller.js +689 -0
  217. package/src/lib/checkpoint-restore-recovery.js +884 -0
  218. package/src/lib/checkpoint-restore-retention.js +126 -0
  219. package/src/lib/checkpoint-restore-saga.js +5079 -0
  220. package/src/lib/checkpoint-restore-session-recovery.js +1178 -0
  221. package/src/lib/checkpoint-restore-workspace-target-verifier.js +270 -0
  222. package/src/lib/checkpoint-store.js +1688 -97
  223. package/src/lib/checkpoint-timeline-authority.js +522 -0
  224. package/src/lib/checkpoint-timeline.js +642 -0
  225. package/src/lib/config-keys.js +18 -119
  226. package/src/lib/config-manager.js +446 -27
  227. package/src/lib/config-redaction.js +57 -0
  228. package/src/lib/config-schema.js +853 -0
  229. package/src/lib/cowork-mcp-tools.js +5 -0
  230. package/src/lib/cowork-task-runner.js +458 -63
  231. package/src/lib/delivery-coordinator.js +1234 -0
  232. package/src/lib/delivery-evidence.js +450 -0
  233. package/src/lib/doctor-checkup.js +199 -14
  234. package/src/lib/executable-path.js +34 -0
  235. package/src/lib/fatal-handler.js +16 -0
  236. package/src/lib/file-checkpoint.js +4909 -186
  237. package/src/lib/file-lines.js +125 -0
  238. package/src/lib/headless-config-command.js +16 -5
  239. package/src/lib/hook-runner.cjs +139 -38
  240. package/src/lib/hooks-v2-workspace-context.js +10 -0
  241. package/src/lib/impacted-gate-selector.js +424 -0
  242. package/src/lib/interaction-adapter.js +62 -0
  243. package/src/lib/jsonl-session-store.js +1 -35
  244. package/src/lib/logger.js +66 -14
  245. package/src/lib/managed-checkpoint-render.js +60 -0
  246. package/src/lib/managed-tool-checkpoint.js +194 -0
  247. package/src/lib/mcp-call-ledger-store.js +1069 -0
  248. package/src/lib/mcp-call-ledger.js +747 -0
  249. package/src/lib/mcp-client.js +5 -0
  250. package/src/lib/mcp-conflict-scheduler.js +468 -0
  251. package/src/lib/mcp-effect-contract.js +102 -0
  252. package/src/lib/mcp-headers-helper-trust.js +145 -0
  253. package/src/lib/mcp-headers-helper.js +616 -0
  254. package/src/lib/mcp-host-recovery-runtime.js +131 -0
  255. package/src/lib/mcp-ledger-recovery-admission.js +1065 -0
  256. package/src/lib/mcp-recovery-adjudication.js +443 -0
  257. package/src/lib/output-context.js +86 -0
  258. package/src/lib/packer/file-identity.js +170 -0
  259. package/src/lib/packer/index.js +3 -0
  260. package/src/lib/packer/native-update-state.js +277 -0
  261. package/src/lib/packer/pack-update-applier.js +1983 -136
  262. package/src/lib/packer/pack-update-checker.js +34 -0
  263. package/src/lib/packer/pack-update-downloader.js +875 -86
  264. package/src/lib/packer/pack-update-signature.js +86 -0
  265. package/src/lib/packer/pkg-config-generator.js +6 -0
  266. package/src/lib/paths.js +65 -10
  267. package/src/lib/plan-mode.js +831 -14
  268. package/src/lib/plan-persistence.js +540 -0
  269. package/src/lib/plugin-runtime/hooks.js +227 -69
  270. package/src/lib/plugin-runtime/plugin-options.js +189 -44
  271. package/src/lib/pr-automation-policy.js +146 -8
  272. package/src/lib/process-execution-broker/credential-agent.js +7 -0
  273. package/src/lib/process-execution-broker/index.js +491 -13
  274. package/src/lib/process-execution-broker/linux-generic-bwrap-runtime.js +28 -1
  275. package/src/lib/process-execution-broker/linux-generic-bwrap.js +28 -4
  276. package/src/lib/process-execution-broker/platform-sandbox.js +92 -70
  277. package/src/lib/process-execution-broker/windows-sandbox-helper.dll +0 -0
  278. package/src/lib/process-execution-broker/windows-sandbox-helper.exe +0 -0
  279. package/src/lib/process-execution-broker/windows-sandbox.cs +284 -19
  280. package/src/lib/process-execution-broker/workspace-transaction.js +4459 -0
  281. package/src/lib/project-instructions.js +165 -29
  282. package/src/lib/project-mcp-trust.js +67 -0
  283. package/src/lib/public-ide-capability-manifest.js +272 -0
  284. package/src/lib/public-ide-capability-validation.js +351 -0
  285. package/src/lib/secret-store.js +267 -43
  286. package/src/lib/secure-file-identity.js +433 -0
  287. package/src/lib/secure-fs.js +1089 -0
  288. package/src/lib/security-audit.js +58 -0
  289. package/src/lib/service-manager.js +34 -13
  290. package/src/lib/session-budget-runtime.js +1452 -0
  291. package/src/lib/session-host-snapshot.js +388 -0
  292. package/src/lib/session-message-provenance.js +429 -0
  293. package/src/lib/session-projection.js +804 -0
  294. package/src/lib/session-resource-budget.js +1495 -0
  295. package/src/lib/settings-hooks.cjs +138 -22
  296. package/src/lib/settings-loader.cjs +25 -2
  297. package/src/lib/side-effect-ledger-store.js +45 -23
  298. package/src/lib/skill-execution-identity.js +217 -0
  299. package/src/lib/skill-loader.js +299 -18
  300. package/src/lib/sub-agent-context.js +236 -28
  301. package/src/lib/sub-agent-registry.js +5 -0
  302. package/src/lib/subagent-contract.js +94 -0
  303. package/src/lib/todo-manager.js +185 -18
  304. package/src/lib/todo-persistence.js +417 -0
  305. package/src/lib/turn-binding-store.js +41 -23
  306. package/src/lib/turn-binding.js +160 -2
  307. package/src/lib/with-file-lock.js +165 -24
  308. package/src/lib/ws-chat-handler.js +21 -0
  309. package/src/program-base.js +18 -0
  310. package/src/repl/advisor-command.js +103 -0
  311. package/src/repl/agent-repl.js +2175 -146
  312. package/src/repl/btw-command.js +93 -10
  313. package/src/repl/clipboard-image.js +119 -0
  314. package/src/repl/config-summary.js +64 -108
  315. package/src/repl/prompt-editor.js +233 -0
  316. package/src/repl/prompt-interactions.js +344 -0
  317. package/src/repl/prompt-stash.js +354 -0
  318. package/src/repl/prompt-suggestions.js +312 -0
  319. package/src/repl/repl-keybindings.js +227 -0
  320. package/src/repl/session-recap.js +217 -0
  321. package/src/repl/slash-command-registry.js +22 -0
  322. package/src/repl/terminal-layout.js +88 -0
  323. package/src/runtime/agent-core.js +1630 -447
  324. package/src/runtime/coding-agent-contract-shared.cjs +13 -1
  325. package/src/runtime/coding-agent-managed-tool-policy.cjs +7 -2
  326. package/src/runtime/diagnostics.js +32 -13
  327. package/src/runtime/headless-runner.js +310 -118
  328. package/src/runtime/headless-stream.js +356 -95
  329. package/src/runtime/mcp-config.js +148 -14
  330. package/src/runtime/policies/agent-policy.js +14 -0
  331. package/src/runtime/status-diagnostics-lite.js +137 -0
  332. package/src/assets/web-panel/assets/MarkdownRenderer-7iWGwZ-r.js +0 -1
  333. package/src/assets/web-panel/assets/OrderTableRenderer-BU2Yqq5H.js +0 -1
  334. package/src/assets/web-panel/assets/PdhVaultBrowser-69ca_WeR.js +0 -7
  335. package/src/assets/web-panel/assets/devWarning-B4dXIJqD.js +0 -1
  336. package/src/assets/web-panel/assets/index-C-C7DaG6.js +0 -1
  337. package/src/assets/web-panel/assets/index-DkfWzWtd.js +0 -1
@@ -0,0 +1,1495 @@
1
+ /**
2
+ * SessionResourceBudget tracks resource admissions for callers that explicitly
3
+ * share the same instance.
4
+ *
5
+ * Admission limits (concurrency, total spawns, depth and turns) are checked
6
+ * synchronously, so multiple Promise continuations cannot oversubscribe them.
7
+ * Continuous limits (tokens, USD, wall time and aggregate tool time) actively
8
+ * abort the session as soon as they are exhausted; callers do not have to wait
9
+ * until the next spawn or model turn to notice.
10
+ *
11
+ * Snapshots retain settled totals and identify work that was in flight. A
12
+ * restored dirty snapshot is fail-closed until the caller adjudicates every
13
+ * listed resource. Process downtime is not charged to wall time, matching the
14
+ * existing resumable TeamBudget contract.
15
+ */
16
+
17
+ import { AsyncLocalStorage } from "node:async_hooks";
18
+ import { randomUUID } from "node:crypto";
19
+ import { CostBudget } from "./cost-budget.js";
20
+
21
+ export const SESSION_RESOURCE_BUDGET_VERSION = 1;
22
+
23
+ const INTEGER_LIMITS = new Set([
24
+ "maxConcurrent",
25
+ "maxSpawns",
26
+ "maxDepth",
27
+ "maxTurns",
28
+ "maxTokens",
29
+ ]);
30
+
31
+ const LIMIT_FIELDS = Object.freeze([
32
+ "maxConcurrent",
33
+ "maxSpawns",
34
+ "maxDepth",
35
+ "maxTurns",
36
+ "maxTokens",
37
+ "maxUsd",
38
+ "maxWallMs",
39
+ "maxToolMs",
40
+ ]);
41
+
42
+ const CONTINUOUS_REASONS = new Set([
43
+ "max-tokens",
44
+ "unpriced-usage",
45
+ "max-usd",
46
+ "max-wall-ms",
47
+ "max-tool-ms",
48
+ ]);
49
+
50
+ const USAGE_TOKEN_FIELDS = Object.freeze([
51
+ "input_tokens",
52
+ "output_tokens",
53
+ "cache_read_input_tokens",
54
+ "cache_creation_input_tokens",
55
+ ]);
56
+
57
+ const MAX_TIMER_DELAY = 2_147_483_647;
58
+ const RESOURCE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:@-]{0,159}$/;
59
+ const OPAQUE_AUTHORITY_ID_PATTERNS = Object.freeze({
60
+ work: /^work-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
61
+ tool: /^tool-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
62
+ usage:
63
+ /^usage-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
64
+ });
65
+ const OBSERVER_INVOCATION_CONTEXT = new AsyncLocalStorage();
66
+ const PERSISTED_WORK_KINDS = new Set([
67
+ "work",
68
+ "spawn",
69
+ "sub-agent",
70
+ "background",
71
+ "background-task",
72
+ "team-task",
73
+ "usage-settlement",
74
+ ]);
75
+ const PERSISTED_ABORT_REASONS = new Set([
76
+ "session-aborted",
77
+ "parent-aborted",
78
+ "host-aborted",
79
+ "persistence-failed",
80
+ "invalid-usage",
81
+ "max-tokens",
82
+ "unpriced-usage",
83
+ "max-usd",
84
+ "max-wall-ms",
85
+ "max-tool-ms",
86
+ "max-turns",
87
+ "max-spawns",
88
+ ]);
89
+
90
+ function isRecord(value) {
91
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
92
+ return false;
93
+ }
94
+ const proto = Object.getPrototypeOf(value);
95
+ return proto === Object.prototype || proto === null;
96
+ }
97
+
98
+ function normalizeLimit(field, raw) {
99
+ if (raw === undefined || raw === null || raw === "") return null;
100
+ const value = Number(raw);
101
+ const allowsZero = field === "maxDepth";
102
+ if (
103
+ !Number.isFinite(value) ||
104
+ (allowsZero ? value < 0 : value <= 0) ||
105
+ (INTEGER_LIMITS.has(field) && !Number.isSafeInteger(value))
106
+ ) {
107
+ throw new TypeError(`invalid session budget limit: ${field}`);
108
+ }
109
+ return value;
110
+ }
111
+
112
+ function normalizeNonNegativeInteger(field, raw) {
113
+ const value = Number(raw);
114
+ if (!Number.isSafeInteger(value) || value < 0) {
115
+ throw new TypeError(`invalid session budget total: ${field}`);
116
+ }
117
+ return value;
118
+ }
119
+
120
+ function normalizeNonNegativeNumber(field, raw) {
121
+ const value = Number(raw);
122
+ if (!Number.isFinite(value) || value < 0) {
123
+ throw new TypeError(`invalid session budget total: ${field}`);
124
+ }
125
+ return value;
126
+ }
127
+
128
+ function normalizeUsageTokens(usage) {
129
+ const fields = Object.fromEntries(
130
+ USAGE_TOKEN_FIELDS.map((field) => [field, 0]),
131
+ );
132
+ if (usage == null) return { fields, total: 0 };
133
+ if (!isRecord(usage)) {
134
+ throw new TypeError("invalid session budget usage");
135
+ }
136
+ let total = 0;
137
+ for (const field of USAGE_TOKEN_FIELDS) {
138
+ const raw = usage[field];
139
+ if (raw === undefined || raw === null) continue;
140
+ const value = Number(raw);
141
+ if (!Number.isSafeInteger(value) || value < 0) {
142
+ throw new TypeError(`invalid session budget usage: ${field}`);
143
+ }
144
+ fields[field] = value;
145
+ total += value;
146
+ if (!Number.isSafeInteger(total)) {
147
+ throw new TypeError("session budget token total exceeds safe integer");
148
+ }
149
+ }
150
+ return { fields, total };
151
+ }
152
+
153
+ function safeReason(reason, fallback = "session-aborted") {
154
+ if (reason instanceof Error) return reason;
155
+ const text = String(reason || fallback).slice(0, 512);
156
+ const error = new Error(text || fallback);
157
+ error.code = "ERR_SESSION_ABORTED";
158
+ return error;
159
+ }
160
+
161
+ function persistedKind(kind, resourceType) {
162
+ if (resourceType === "tool") return "tool";
163
+ return PERSISTED_WORK_KINDS.has(kind) ? kind : "work";
164
+ }
165
+
166
+ function snapshotResource(entry, now, resourceType) {
167
+ return {
168
+ id: entry.id,
169
+ kind: persistedKind(entry.kind, resourceType),
170
+ ...(entry.depth !== null ? { depth: entry.depth } : {}),
171
+ ...(entry.startedAt !== null
172
+ ? { elapsedMs: Math.max(0, now - entry.startedAt) }
173
+ : {}),
174
+ };
175
+ }
176
+
177
+ function validateResourceList(value, field) {
178
+ if (!Array.isArray(value)) {
179
+ throw new TypeError(`invalid session budget in-flight list: ${field}`);
180
+ }
181
+ const seen = new Set();
182
+ return value.map((entry) => {
183
+ const validAuthorityId =
184
+ typeof entry?.id === "string" &&
185
+ (field === "tools"
186
+ ? OPAQUE_AUTHORITY_ID_PATTERNS.tool.test(entry.id)
187
+ : OPAQUE_AUTHORITY_ID_PATTERNS.work.test(entry.id) ||
188
+ OPAQUE_AUTHORITY_ID_PATTERNS.usage.test(entry.id));
189
+ if (
190
+ !isRecord(entry) ||
191
+ !validAuthorityId ||
192
+ typeof entry.kind !== "string" ||
193
+ (field === "tools"
194
+ ? entry.kind !== "tool"
195
+ : !PERSISTED_WORK_KINDS.has(entry.kind)) ||
196
+ seen.has(entry.id)
197
+ ) {
198
+ throw new TypeError(`invalid session budget in-flight entry: ${field}`);
199
+ }
200
+ seen.add(entry.id);
201
+ const normalized = { id: entry.id, kind: entry.kind };
202
+ if (entry.depth !== undefined) {
203
+ normalized.depth = normalizeNonNegativeInteger("depth", entry.depth);
204
+ }
205
+ if (entry.elapsedMs !== undefined) {
206
+ normalized.elapsedMs = normalizeNonNegativeNumber(
207
+ "elapsedMs",
208
+ entry.elapsedMs,
209
+ );
210
+ }
211
+ return normalized;
212
+ });
213
+ }
214
+
215
+ function validateSnapshot(snapshot) {
216
+ if (
217
+ !isRecord(snapshot) ||
218
+ snapshot.version !== SESSION_RESOURCE_BUDGET_VERSION ||
219
+ !isRecord(snapshot.limits) ||
220
+ !isRecord(snapshot.totals) ||
221
+ !isRecord(snapshot.inFlight) ||
222
+ !isRecord(snapshot.state)
223
+ ) {
224
+ throw new TypeError("invalid session resource budget snapshot");
225
+ }
226
+ const limits = {};
227
+ for (const field of LIMIT_FIELDS) {
228
+ if (!Object.hasOwn(snapshot.limits, field)) {
229
+ throw new TypeError(`missing session budget limit: ${field}`);
230
+ }
231
+ limits[field] = normalizeLimit(field, snapshot.limits[field]);
232
+ }
233
+ const totals = {
234
+ spawns: normalizeNonNegativeInteger("spawns", snapshot.totals.spawns),
235
+ turns: normalizeNonNegativeInteger("turns", snapshot.totals.turns),
236
+ tokens: normalizeNonNegativeInteger("tokens", snapshot.totals.tokens),
237
+ spentUsd: normalizeNonNegativeNumber("spentUsd", snapshot.totals.spentUsd),
238
+ elapsedMs: normalizeNonNegativeNumber(
239
+ "elapsedMs",
240
+ snapshot.totals.elapsedMs,
241
+ ),
242
+ toolMs: normalizeNonNegativeNumber("toolMs", snapshot.totals.toolMs),
243
+ unpricedUsage: snapshot.totals.unpricedUsage,
244
+ };
245
+ if (typeof totals.unpricedUsage !== "boolean") {
246
+ throw new TypeError("invalid session budget unpriced usage state");
247
+ }
248
+ if (typeof snapshot.state.started !== "boolean") {
249
+ throw new TypeError("invalid session budget started state");
250
+ }
251
+ if (
252
+ snapshot.state.abort !== null &&
253
+ (!isRecord(snapshot.state.abort) ||
254
+ typeof snapshot.state.abort.reason !== "string" ||
255
+ typeof snapshot.state.abort.message !== "string")
256
+ ) {
257
+ throw new TypeError("invalid session budget abort state");
258
+ }
259
+ const work = validateResourceList(snapshot.inFlight.work, "work");
260
+ const tools = validateResourceList(snapshot.inFlight.tools, "tools");
261
+ const workIds = new Set(work.map((entry) => entry.id));
262
+ if (tools.some((entry) => workIds.has(entry.id))) {
263
+ throw new TypeError(
264
+ "duplicate session budget in-flight id across work and tools",
265
+ );
266
+ }
267
+ return {
268
+ limits,
269
+ totals,
270
+ state: {
271
+ started: snapshot.state.started,
272
+ abort: snapshot.state.abort,
273
+ },
274
+ inFlight: {
275
+ work,
276
+ tools,
277
+ },
278
+ };
279
+ }
280
+
281
+ function tightenLimit(field, stored, override) {
282
+ const prior = normalizeLimit(field, stored);
283
+ if (override === undefined || override === null || override === "") {
284
+ return prior;
285
+ }
286
+ const next = normalizeLimit(field, override);
287
+ if (prior === null) return next;
288
+ return Math.min(prior, next);
289
+ }
290
+
291
+ function hasLimitValue(value) {
292
+ return value !== undefined && value !== null && value !== "";
293
+ }
294
+
295
+ function normalizeLimitOverrides(overrides) {
296
+ if (!isRecord(overrides)) {
297
+ throw new TypeError("invalid session budget limit overrides");
298
+ }
299
+ const normalized = {};
300
+ for (const field of LIMIT_FIELDS) {
301
+ if (field !== "maxUsd" && hasLimitValue(overrides[field])) {
302
+ normalized[field] = normalizeLimit(field, overrides[field]);
303
+ }
304
+ }
305
+ const usd = [];
306
+ if (hasLimitValue(overrides.maxUsd)) {
307
+ usd.push(normalizeLimit("maxUsd", overrides.maxUsd));
308
+ }
309
+ if (hasLimitValue(overrides.maxCostUsd)) {
310
+ usd.push(normalizeLimit("maxUsd", overrides.maxCostUsd));
311
+ }
312
+ if (usd.length > 0) normalized.maxUsd = Math.min(...usd);
313
+ return normalized;
314
+ }
315
+
316
+ /**
317
+ * Validate and copy only the content-free authority fields accepted by the
318
+ * durable sidecar. Unknown keys and caller-owned object references never cross
319
+ * this boundary.
320
+ */
321
+ export function normalizeSessionResourceBudgetSnapshot(snapshot) {
322
+ const normalized = validateSnapshot(snapshot);
323
+ const rawAbortReason = normalized.state.abort?.reason || "";
324
+ const abortReason = PERSISTED_ABORT_REASONS.has(rawAbortReason)
325
+ ? rawAbortReason
326
+ : "session-aborted";
327
+ return {
328
+ version: SESSION_RESOURCE_BUDGET_VERSION,
329
+ limits: { ...normalized.limits },
330
+ totals: { ...normalized.totals },
331
+ inFlight: {
332
+ work: normalized.inFlight.work.map((entry) => ({ ...entry })),
333
+ tools: normalized.inFlight.tools.map((entry) => ({ ...entry })),
334
+ },
335
+ state: {
336
+ started: normalized.state.started,
337
+ abort: normalized.state.abort
338
+ ? {
339
+ reason: abortReason,
340
+ message: `Session resource budget stopped: ${abortReason}`,
341
+ }
342
+ : null,
343
+ },
344
+ };
345
+ }
346
+
347
+ export class SessionBudgetError extends Error {
348
+ constructor(reason, message = null) {
349
+ super(message || `Session resource budget exhausted: ${reason}`);
350
+ this.name = "SessionBudgetError";
351
+ this.code = "ERR_SESSION_RESOURCE_BUDGET";
352
+ this.budgetReason = reason;
353
+ this.retryable = false;
354
+ }
355
+ }
356
+
357
+ export class SessionResourceBudget {
358
+ constructor({
359
+ maxConcurrent = null,
360
+ maxSpawns = null,
361
+ maxDepth = null,
362
+ maxTurns = null,
363
+ maxTokens = null,
364
+ maxUsd = null,
365
+ maxCostUsd = undefined,
366
+ maxWallMs = null,
367
+ maxToolMs = null,
368
+ table = undefined,
369
+ now = () => Date.now(),
370
+ setTimer = (fn, delay) => setTimeout(fn, delay),
371
+ clearTimer = (timer) => clearTimeout(timer),
372
+ signal = null,
373
+ onEvent = null,
374
+ onAuthorityChange = null,
375
+ queueObservation = (callback) => queueMicrotask(callback),
376
+ } = {}) {
377
+ this._now = typeof now === "function" ? now : () => Number(now);
378
+ this._setTimer = setTimer;
379
+ this._clearTimer = clearTimer;
380
+ this._onEvent = typeof onEvent === "function" ? onEvent : null;
381
+ this._onAuthorityChange =
382
+ typeof onAuthorityChange === "function" ? onAuthorityChange : null;
383
+ this._queueObservation =
384
+ typeof queueObservation === "function"
385
+ ? queueObservation
386
+ : (callback) => queueMicrotask(callback);
387
+ this._eventSeq = 0;
388
+ this._eventQueue = [];
389
+ this._eventDrainScheduled = false;
390
+
391
+ const normalizedLimits = normalizeLimitOverrides({
392
+ maxConcurrent,
393
+ maxSpawns,
394
+ maxDepth,
395
+ maxTurns,
396
+ maxTokens,
397
+ maxUsd,
398
+ maxCostUsd,
399
+ maxWallMs,
400
+ maxToolMs,
401
+ });
402
+ this.maxConcurrent = normalizedLimits.maxConcurrent ?? null;
403
+ this.maxSpawns = normalizedLimits.maxSpawns ?? null;
404
+ this.maxDepth = normalizedLimits.maxDepth ?? null;
405
+ this.maxTurns = normalizedLimits.maxTurns ?? null;
406
+ this.maxTokens = normalizedLimits.maxTokens ?? null;
407
+ this.maxWallMs = normalizedLimits.maxWallMs ?? null;
408
+ this.maxToolMs = normalizedLimits.maxToolMs ?? null;
409
+ this.cost = new CostBudget({
410
+ limitUsd: normalizedLimits.maxUsd ?? null,
411
+ table,
412
+ });
413
+
414
+ this.spawns = 0;
415
+ this.turns = 0;
416
+ this.tokens = 0;
417
+ this.unpricedUsage = false;
418
+ this._elapsedMs = 0;
419
+ this._startedAt = null;
420
+ this._toolMs = 0;
421
+ this._activeWork = new Map();
422
+ this._activeTools = new Map();
423
+ this._activeWorkLabels = new Map();
424
+ this._activeToolLabels = new Map();
425
+ this._pendingUsage = new Map();
426
+ this._issuedAuthorityIds = new Set();
427
+ this._abortables = new Map();
428
+ this._recoveryUnknown = new Map();
429
+ this._deadlineTimer = null;
430
+ this._abortController = new AbortController();
431
+ this._abortState = null;
432
+ this._authorityFailure = null;
433
+ this._revocationError = null;
434
+ this._externalSignal = signal || null;
435
+ this._externalAbortListener = null;
436
+
437
+ if (this._externalSignal) {
438
+ this._externalAbortListener = () => {
439
+ try {
440
+ this.abort(this._externalSignal.reason || "parent-aborted", {
441
+ reason: "parent-aborted",
442
+ });
443
+ } catch {
444
+ // The authority transition already failed closed and cascaded abort.
445
+ }
446
+ };
447
+ if (this._externalSignal.aborted) this._externalAbortListener();
448
+ else {
449
+ this._externalSignal.addEventListener?.(
450
+ "abort",
451
+ this._externalAbortListener,
452
+ { once: true },
453
+ );
454
+ }
455
+ }
456
+ }
457
+
458
+ get signal() {
459
+ return this._abortController.signal;
460
+ }
461
+
462
+ enabled() {
463
+ return LIMIT_FIELDS.some((field) =>
464
+ field === "maxUsd" ? this.cost.limitUsd !== null : this[field] !== null,
465
+ );
466
+ }
467
+
468
+ /**
469
+ * Apply additional limits without ever relaxing an authority that is already
470
+ * in use. This is primarily used when another host opens the same session in
471
+ * the current process: the shared object keeps its identity, while a stricter
472
+ * caller can still reduce the remaining envelope.
473
+ */
474
+ tightenLimits(overrides = {}) {
475
+ this._assertAuthorityMutationAllowed();
476
+ const requested = normalizeLimitOverrides(overrides);
477
+ const next = {};
478
+ for (const field of LIMIT_FIELDS) {
479
+ if (
480
+ requested[field] === undefined ||
481
+ requested[field] === null ||
482
+ requested[field] === ""
483
+ ) {
484
+ continue;
485
+ }
486
+ const current = field === "maxUsd" ? this.cost.limitUsd : this[field];
487
+ next[field] = tightenLimit(field, current, requested[field]);
488
+ }
489
+
490
+ for (const [field, value] of Object.entries(next)) {
491
+ if (field === "maxUsd") this.cost.limitUsd = value;
492
+ else this[field] = value;
493
+ }
494
+ if (Object.keys(next).length > 0) {
495
+ this._authorityChanged("budget:limits-tightened", {
496
+ limits: { ...next },
497
+ });
498
+ const reason = this._continuousReason();
499
+ if (reason) this._abortFor(reason);
500
+ else this._armDeadline();
501
+ }
502
+ return this.status();
503
+ }
504
+
505
+ start(now = this._now()) {
506
+ this._assertAuthorityMutationAllowed();
507
+ if (this._startedAt === null) {
508
+ this._startedAt = now;
509
+ this._authorityChanged(
510
+ "budget:started",
511
+ {},
512
+ {
513
+ rollback: () => {
514
+ this._startedAt = null;
515
+ },
516
+ },
517
+ );
518
+ this._armDeadline(now);
519
+ }
520
+ return this;
521
+ }
522
+
523
+ _emit(type, detail) {
524
+ if (!this._onEvent) return;
525
+ this._eventQueue.push({
526
+ type,
527
+ eventId: `event-${randomUUID()}`,
528
+ sequence: ++this._eventSeq,
529
+ at: this._now(),
530
+ ...detail,
531
+ });
532
+ if (this._eventDrainScheduled) return;
533
+ this._eventDrainScheduled = true;
534
+ try {
535
+ this._queueObservation(() => {
536
+ this._eventDrainScheduled = false;
537
+ const events = this._eventQueue.splice(0);
538
+ for (const event of events) {
539
+ try {
540
+ OBSERVER_INVOCATION_CONTEXT.run(
541
+ Object.freeze({ eventId: event.eventId }),
542
+ () => {
543
+ const pending = this._onEvent?.(event);
544
+ void Promise.resolve(pending).catch(() => {});
545
+ },
546
+ );
547
+ } catch {
548
+ // Observability is never part of the resource authority.
549
+ }
550
+ }
551
+ });
552
+ } catch {
553
+ // A broken observation scheduler may drop diagnostics, but it must never
554
+ // fall back to synchronous callbacks inside an authority method.
555
+ this._eventQueue.length = 0;
556
+ this._eventDrainScheduled = false;
557
+ }
558
+ }
559
+
560
+ _assertAuthorityMutationAllowed() {
561
+ if (OBSERVER_INVOCATION_CONTEXT.getStore()) {
562
+ throw new SessionBudgetError(
563
+ "notification-reentrancy",
564
+ "Session budget authority cannot mutate from an observation context",
565
+ );
566
+ }
567
+ if (this._revocationError) throw this._revocationError;
568
+ if (this._authorityFailure) throw this._authorityFailure;
569
+ }
570
+
571
+ _nextAuthorityId(resourceType) {
572
+ const pattern = OPAQUE_AUTHORITY_ID_PATTERNS[resourceType];
573
+ if (!pattern) throw new TypeError("invalid session budget authority type");
574
+ for (let attempt = 0; attempt < 8; attempt += 1) {
575
+ const authorityId = `${resourceType}-${randomUUID()}`;
576
+ if (
577
+ pattern.test(authorityId) &&
578
+ !this._issuedAuthorityIds.has(authorityId)
579
+ ) {
580
+ this._issuedAuthorityIds.add(authorityId);
581
+ return authorityId;
582
+ }
583
+ }
584
+ throw new Error("could not allocate unique session budget authority id");
585
+ }
586
+
587
+ _authorityChanged(type, detail, { rollback = null } = {}) {
588
+ if (this._authorityFailure) throw this._authorityFailure;
589
+ if (this._onAuthorityChange) {
590
+ try {
591
+ this._onAuthorityChange({
592
+ type,
593
+ at: this._now(),
594
+ snapshot: this.snapshot(),
595
+ });
596
+ } catch (error) {
597
+ if (typeof rollback === "function") {
598
+ try {
599
+ rollback();
600
+ } catch {
601
+ // The persistence failure still closes this budget even if a
602
+ // defensive local rollback unexpectedly fails.
603
+ }
604
+ }
605
+ this._failClosedAuthorityPersistence(error, type);
606
+ throw error;
607
+ }
608
+ }
609
+ this._emit(type, detail);
610
+ }
611
+
612
+ _failClosedAuthorityPersistence(error, authorityType = "runtime") {
613
+ const failure =
614
+ error instanceof Error
615
+ ? error
616
+ : new Error(String(error || "session budget persistence failed"));
617
+ if (this._authorityFailure) return this._authorityFailure;
618
+ this._authorityFailure = failure;
619
+ try {
620
+ this._abortUnchecked(failure, {
621
+ reason: "persistence-failed",
622
+ skipAuthorityChange: true,
623
+ });
624
+ } catch {
625
+ // The original persistence error remains the rejection authority.
626
+ }
627
+ this._emit("budget:authority-persistence-failed", { authorityType });
628
+ return failure;
629
+ }
630
+
631
+ _revokeRuntimeAuthority() {
632
+ if (this._revocationError) return false;
633
+ if (this._authorityFailure) throw this._authorityFailure;
634
+ const error = new SessionBudgetError(
635
+ "runtime-closed",
636
+ "Session resource budget runtime is closed",
637
+ );
638
+ // Install the fence before invoking cleanup callbacks so callback re-entry
639
+ // cannot mutate authority after the final durable snapshot was written.
640
+ this._revocationError = error;
641
+ this._abortUnchecked(error, {
642
+ reason: "runtime-closed",
643
+ skipAuthorityChange: true,
644
+ });
645
+ if (this._externalSignal && this._externalAbortListener) {
646
+ try {
647
+ this._externalSignal.removeEventListener?.(
648
+ "abort",
649
+ this._externalAbortListener,
650
+ );
651
+ } catch {
652
+ // Revocation is already installed; listener cleanup is best effort.
653
+ }
654
+ }
655
+ this._externalAbortListener = null;
656
+ this._emit("budget:runtime-revoked", {
657
+ activeWork: this._activeWork.size,
658
+ activeTools: this._activeTools.size,
659
+ });
660
+ return true;
661
+ }
662
+
663
+ _persistenceAdmissionFailure(error, extra = {}) {
664
+ if (!this._authorityFailure || error !== this._authorityFailure) {
665
+ throw error;
666
+ }
667
+ return this._admissionFailure("persistence-failed", extra);
668
+ }
669
+
670
+ _elapsedAt(now = this._now()) {
671
+ return (
672
+ this._elapsedMs +
673
+ (this._startedAt === null ? 0 : Math.max(0, now - this._startedAt))
674
+ );
675
+ }
676
+
677
+ _toolMsAt(now = this._now()) {
678
+ let live = this._toolMs;
679
+ for (const tool of this._activeTools.values()) {
680
+ live += Math.max(0, now - tool.startedAt);
681
+ }
682
+ return live;
683
+ }
684
+
685
+ _continuousReason(now = this._now()) {
686
+ if (this.maxTokens !== null && this.tokens >= this.maxTokens) {
687
+ return "max-tokens";
688
+ }
689
+ if (this.cost.enabled() && this.unpricedUsage) {
690
+ return "unpriced-usage";
691
+ }
692
+ if (this.cost.exceeded()) return "max-usd";
693
+ if (this.maxWallMs !== null && this._elapsedAt(now) >= this.maxWallMs) {
694
+ return "max-wall-ms";
695
+ }
696
+ if (this.maxToolMs !== null && this._toolMsAt(now) >= this.maxToolMs) {
697
+ return "max-tool-ms";
698
+ }
699
+ return null;
700
+ }
701
+
702
+ reason(now = this._now()) {
703
+ if (this._abortState) return this._abortState.reason;
704
+ if (this._pendingUsage.size > 0) return "usage-settlement-pending";
705
+ if (this._recoveryUnknown.size > 0) return "recovery-required";
706
+ const continuous = this._continuousReason(now);
707
+ if (continuous) return continuous;
708
+ if (this.maxTurns !== null && this.turns >= this.maxTurns) {
709
+ return "max-turns";
710
+ }
711
+ if (this.maxSpawns !== null && this.spawns >= this.maxSpawns) {
712
+ return "max-spawns";
713
+ }
714
+ return null;
715
+ }
716
+
717
+ shouldStop(now = this._now()) {
718
+ return this.reason(now) !== null;
719
+ }
720
+
721
+ _admissionFailure(reason, extra = {}) {
722
+ this._emit("budget:admission-denied", { reason, ...extra });
723
+ return { ok: false, reason, retryable: reason === "max-concurrent" };
724
+ }
725
+
726
+ consumeTurn({ id = null } = {}) {
727
+ this._assertAuthorityMutationAllowed();
728
+ try {
729
+ this.start();
730
+ } catch (error) {
731
+ return this._persistenceAdmissionFailure(error, { id });
732
+ }
733
+ if (this.signal.aborted) {
734
+ return this._admissionFailure(this.reason() || "session-aborted", { id });
735
+ }
736
+ if (this._pendingUsage.size > 0) {
737
+ return this._admissionFailure("usage-settlement-pending", { id });
738
+ }
739
+ if (this._recoveryUnknown.size > 0) {
740
+ return this._admissionFailure("recovery-required", { id });
741
+ }
742
+ if (this.maxTurns !== null && this.turns >= this.maxTurns) {
743
+ return this._admissionFailure("max-turns", { id });
744
+ }
745
+ const previousTurns = this.turns;
746
+ this.turns = previousTurns + 1;
747
+ try {
748
+ this._authorityChanged(
749
+ "budget:turn-consumed",
750
+ { id, turns: this.turns },
751
+ {
752
+ rollback: () => {
753
+ this.turns = previousTurns;
754
+ },
755
+ },
756
+ );
757
+ } catch (error) {
758
+ return this._persistenceAdmissionFailure(error, { id });
759
+ }
760
+ return { ok: true, turns: this.turns, remaining: this.turnsRemaining() };
761
+ }
762
+
763
+ turnsRemaining() {
764
+ return this.maxTurns === null
765
+ ? Infinity
766
+ : Math.max(0, this.maxTurns - this.turns);
767
+ }
768
+
769
+ acquireWork({ id, kind = "spawn", depth = 1 } = {}) {
770
+ this._assertAuthorityMutationAllowed();
771
+ const key = String(id || "");
772
+ if (!key) throw new TypeError("session budget work id is required");
773
+ if (!RESOURCE_ID_PATTERN.test(key)) {
774
+ throw new TypeError("invalid session budget work id");
775
+ }
776
+ const normalizedKind = String(kind || "spawn");
777
+ if (!normalizedKind || normalizedKind.length > 128) {
778
+ throw new TypeError("invalid session budget work kind");
779
+ }
780
+ const normalizedDepth = normalizeNonNegativeInteger("depth", depth);
781
+ try {
782
+ this.start();
783
+ } catch (error) {
784
+ return this._persistenceAdmissionFailure(error, { id: key });
785
+ }
786
+ if (this._activeWorkLabels.has(key)) {
787
+ return this._admissionFailure("duplicate-work-id", { id: key });
788
+ }
789
+ if (this._activeToolLabels.has(key)) {
790
+ return this._admissionFailure("duplicate-resource-id", { id: key });
791
+ }
792
+ if (this.signal.aborted) {
793
+ return this._admissionFailure(this.reason() || "session-aborted", {
794
+ id: key,
795
+ });
796
+ }
797
+ if (this._pendingUsage.size > 0) {
798
+ return this._admissionFailure("usage-settlement-pending", { id: key });
799
+ }
800
+ if (this._recoveryUnknown.size > 0) {
801
+ return this._admissionFailure("recovery-required", { id: key });
802
+ }
803
+ if (this.maxDepth !== null && normalizedDepth > this.maxDepth) {
804
+ return this._admissionFailure("max-depth", {
805
+ id: key,
806
+ depth: normalizedDepth,
807
+ });
808
+ }
809
+ if (
810
+ this.maxConcurrent !== null &&
811
+ this._activeWork.size >= this.maxConcurrent
812
+ ) {
813
+ return this._admissionFailure("max-concurrent", { id: key });
814
+ }
815
+ if (this.maxSpawns !== null && this.spawns >= this.maxSpawns) {
816
+ return this._admissionFailure("max-spawns", { id: key });
817
+ }
818
+
819
+ const authorityId = this._nextAuthorityId("work");
820
+ const entry = {
821
+ id: authorityId,
822
+ label: key,
823
+ kind: normalizedKind,
824
+ depth: normalizedDepth,
825
+ startedAt: this._now(),
826
+ };
827
+ const previousSpawns = this.spawns;
828
+ this._activeWork.set(authorityId, entry);
829
+ this._activeWorkLabels.set(key, authorityId);
830
+ this.spawns = previousSpawns + 1;
831
+ try {
832
+ this._authorityChanged(
833
+ "budget:work-acquired",
834
+ {
835
+ id: key,
836
+ kind: normalizedKind,
837
+ depth: normalizedDepth,
838
+ active: this._activeWork.size,
839
+ spawns: this.spawns,
840
+ },
841
+ {
842
+ rollback: () => {
843
+ this._activeWork.delete(authorityId);
844
+ this._activeWorkLabels.delete(key);
845
+ this.spawns = previousSpawns;
846
+ },
847
+ },
848
+ );
849
+ } catch (error) {
850
+ return this._persistenceAdmissionFailure(error, { id: key });
851
+ }
852
+ let released = false;
853
+ const release = () => {
854
+ if (released) return false;
855
+ const didRelease = this.releaseWork(authorityId);
856
+ if (didRelease) released = true;
857
+ return didRelease;
858
+ };
859
+ return {
860
+ ok: true,
861
+ id: key,
862
+ authorityId,
863
+ kind: normalizedKind,
864
+ depth: normalizedDepth,
865
+ release,
866
+ };
867
+ }
868
+
869
+ releaseWork(id) {
870
+ this._assertAuthorityMutationAllowed();
871
+ const key = String(id || "");
872
+ const entry = this._activeWork.get(key);
873
+ if (!entry) return false;
874
+ this._activeWork.delete(key);
875
+ this._activeWorkLabels.delete(entry.label);
876
+ this._authorityChanged(
877
+ "budget:work-released",
878
+ {
879
+ id: entry.label,
880
+ kind: entry.kind,
881
+ active: this._activeWork.size,
882
+ },
883
+ {
884
+ rollback: () => {
885
+ this._activeWork.set(key, entry);
886
+ this._activeWorkLabels.set(entry.label, key);
887
+ },
888
+ },
889
+ );
890
+ return true;
891
+ }
892
+
893
+ beginTool({ id, kind = "tool" } = {}) {
894
+ this._assertAuthorityMutationAllowed();
895
+ const key = String(id || "");
896
+ if (!key) throw new TypeError("session budget tool id is required");
897
+ if (!RESOURCE_ID_PATTERN.test(key)) {
898
+ throw new TypeError("invalid session budget tool id");
899
+ }
900
+ const normalizedKind = String(kind || "tool");
901
+ if (!normalizedKind || normalizedKind.length > 128) {
902
+ throw new TypeError("invalid session budget tool kind");
903
+ }
904
+ try {
905
+ this.start();
906
+ } catch (error) {
907
+ return this._persistenceAdmissionFailure(error, { id: key });
908
+ }
909
+ if (this._activeToolLabels.has(key)) {
910
+ return this._admissionFailure("duplicate-tool-id", { id: key });
911
+ }
912
+ if (this._activeWorkLabels.has(key)) {
913
+ return this._admissionFailure("duplicate-resource-id", { id: key });
914
+ }
915
+ if (this.signal.aborted) {
916
+ return this._admissionFailure(this.reason() || "session-aborted", {
917
+ id: key,
918
+ });
919
+ }
920
+ if (this._pendingUsage.size > 0) {
921
+ return this._admissionFailure("usage-settlement-pending", { id: key });
922
+ }
923
+ if (this._recoveryUnknown.size > 0) {
924
+ return this._admissionFailure("recovery-required", { id: key });
925
+ }
926
+ const now = this._now();
927
+ if (this.maxToolMs !== null && this._toolMsAt(now) >= this.maxToolMs) {
928
+ this._abortFor("max-tool-ms");
929
+ return this._admissionFailure("max-tool-ms", { id: key });
930
+ }
931
+ const authorityId = this._nextAuthorityId("tool");
932
+ this._activeTools.set(authorityId, {
933
+ id: authorityId,
934
+ label: key,
935
+ kind: normalizedKind,
936
+ depth: null,
937
+ startedAt: now,
938
+ });
939
+ this._activeToolLabels.set(key, authorityId);
940
+ try {
941
+ this._authorityChanged(
942
+ "budget:tool-started",
943
+ {
944
+ id: key,
945
+ kind: normalizedKind,
946
+ active: this._activeTools.size,
947
+ },
948
+ {
949
+ rollback: () => {
950
+ this._activeTools.delete(authorityId);
951
+ this._activeToolLabels.delete(key);
952
+ },
953
+ },
954
+ );
955
+ } catch (error) {
956
+ return this._persistenceAdmissionFailure(error, { id: key });
957
+ }
958
+ this._armDeadline(now);
959
+ let ended = false;
960
+ const end = () => {
961
+ if (ended) return false;
962
+ const didEnd = this.endTool(authorityId);
963
+ if (didEnd) ended = true;
964
+ return didEnd;
965
+ };
966
+ return { ok: true, id: key, authorityId, kind: normalizedKind, end };
967
+ }
968
+
969
+ endTool(id, now = this._now()) {
970
+ this._assertAuthorityMutationAllowed();
971
+ const key = String(id || "");
972
+ const entry = this._activeTools.get(key);
973
+ if (!entry) return false;
974
+ const previousToolMs = this._toolMs;
975
+ this._activeTools.delete(key);
976
+ this._activeToolLabels.delete(entry.label);
977
+ this._toolMs += Math.max(0, now - entry.startedAt);
978
+ this._authorityChanged(
979
+ "budget:tool-ended",
980
+ {
981
+ id: entry.label,
982
+ kind: entry.kind,
983
+ toolMs: this._toolMs,
984
+ active: this._activeTools.size,
985
+ },
986
+ {
987
+ rollback: () => {
988
+ this._activeTools.set(key, entry);
989
+ this._activeToolLabels.set(entry.label, key);
990
+ this._toolMs = previousToolMs;
991
+ },
992
+ },
993
+ );
994
+ const reason = this._continuousReason(now);
995
+ if (reason) this._abortFor(reason);
996
+ else this._armDeadline(now);
997
+ return true;
998
+ }
999
+
1000
+ recordUsage({ usage = null, usageRecords = null, provider, model } = {}) {
1001
+ this._assertAuthorityMutationAllowed();
1002
+ this.start();
1003
+ if (this._pendingUsage.size > 0) {
1004
+ throw new SessionBudgetError("usage-settlement-pending");
1005
+ }
1006
+ let tokenCount;
1007
+ let pricedRecords;
1008
+ try {
1009
+ if (usageRecords != null && !Array.isArray(usageRecords)) {
1010
+ throw new TypeError("invalid session budget usage records");
1011
+ }
1012
+ if (Array.isArray(usageRecords) && usageRecords.length > 0) {
1013
+ const detailedFields = Object.fromEntries(
1014
+ USAGE_TOKEN_FIELDS.map((field) => [field, 0]),
1015
+ );
1016
+ let detailedTokenCount = 0;
1017
+ pricedRecords = usageRecords.map((record, index) => {
1018
+ if (!isRecord(record) || !isRecord(record.usage)) {
1019
+ throw new TypeError(
1020
+ `invalid session budget usage record at index ${index}`,
1021
+ );
1022
+ }
1023
+ const normalized = normalizeUsageTokens(record.usage);
1024
+ for (const field of USAGE_TOKEN_FIELDS) {
1025
+ detailedFields[field] += normalized.fields[field];
1026
+ if (!Number.isSafeInteger(detailedFields[field])) {
1027
+ throw new TypeError(
1028
+ `session budget usage record aggregate exceeds safe integer: ${field}`,
1029
+ );
1030
+ }
1031
+ }
1032
+ detailedTokenCount += normalized.total;
1033
+ if (!Number.isSafeInteger(detailedTokenCount)) {
1034
+ throw new TypeError(
1035
+ "session budget token total exceeds safe integer",
1036
+ );
1037
+ }
1038
+ return { record, tokens: normalized.total };
1039
+ });
1040
+ if (usage != null) {
1041
+ const aggregate = normalizeUsageTokens(usage);
1042
+ for (const field of USAGE_TOKEN_FIELDS) {
1043
+ if (aggregate.fields[field] !== detailedFields[field]) {
1044
+ throw new TypeError(
1045
+ `session budget usage records do not match aggregate usage: ${field}`,
1046
+ );
1047
+ }
1048
+ }
1049
+ tokenCount = aggregate.total;
1050
+ } else {
1051
+ tokenCount = detailedTokenCount;
1052
+ }
1053
+ } else {
1054
+ tokenCount = normalizeUsageTokens(usage).total;
1055
+ pricedRecords =
1056
+ usage == null
1057
+ ? []
1058
+ : [{ record: { provider, model, usage }, tokens: tokenCount }];
1059
+ }
1060
+ if (!Number.isSafeInteger(tokenCount)) {
1061
+ throw new TypeError("session budget token total exceeds safe integer");
1062
+ }
1063
+ } catch (error) {
1064
+ this.abort(error, { reason: "invalid-usage" });
1065
+ throw error;
1066
+ }
1067
+ const nextTokens = this.tokens + tokenCount;
1068
+ if (!Number.isSafeInteger(nextTokens)) {
1069
+ const error = new TypeError(
1070
+ "session budget token total exceeds safe integer",
1071
+ );
1072
+ this.abort(error, { reason: "invalid-usage" });
1073
+ throw error;
1074
+ }
1075
+ const settlementId = this._nextUsageSettlementId();
1076
+ this._pendingUsage.set(settlementId, {
1077
+ id: settlementId,
1078
+ kind: "usage-settlement",
1079
+ depth: 0,
1080
+ startedAt: this._now(),
1081
+ });
1082
+ this._authorityChanged("budget:usage-settlement-started", {
1083
+ pendingUsage: this._pendingUsage.size,
1084
+ });
1085
+ this.tokens = nextTokens;
1086
+
1087
+ try {
1088
+ for (const { record, tokens: recordTokens } of pricedRecords) {
1089
+ const estimate = this.cost.add(record);
1090
+ const price = Number(estimate?.totalCost);
1091
+ if (
1092
+ this.cost.enabled() &&
1093
+ recordTokens > 0 &&
1094
+ estimate?.free !== true &&
1095
+ (estimate?.matched !== true || !Number.isFinite(price) || price < 0)
1096
+ ) {
1097
+ this.unpricedUsage = true;
1098
+ }
1099
+ }
1100
+ } catch (error) {
1101
+ this.abort(error, { reason: "invalid-usage" });
1102
+ throw error;
1103
+ }
1104
+ const pendingSettlement = this._pendingUsage.get(settlementId);
1105
+ this._pendingUsage.delete(settlementId);
1106
+ this._authorityChanged(
1107
+ "budget:usage-recorded",
1108
+ {
1109
+ tokens: this.tokens,
1110
+ spentUsd: this.cost.spentUsd,
1111
+ },
1112
+ {
1113
+ rollback: () => {
1114
+ this._pendingUsage.set(settlementId, pendingSettlement);
1115
+ },
1116
+ },
1117
+ );
1118
+ const reason = this._continuousReason();
1119
+ if (reason) this._abortFor(reason);
1120
+ return this.status();
1121
+ }
1122
+
1123
+ _nextUsageSettlementId() {
1124
+ return this._nextAuthorityId("usage");
1125
+ }
1126
+
1127
+ registerAbortable(id, stop) {
1128
+ this._assertAuthorityMutationAllowed();
1129
+ const key = String(id || "");
1130
+ if (!key) throw new TypeError("session budget abortable id is required");
1131
+ if (this._abortables.has(key)) {
1132
+ throw new Error(`session budget abortable already registered: ${key}`);
1133
+ }
1134
+ let callback;
1135
+ if (typeof stop === "function") callback = stop;
1136
+ else if (stop && typeof stop.abort === "function") {
1137
+ callback = (reason) => stop.abort(reason);
1138
+ } else if (stop && typeof stop.kill === "function") {
1139
+ callback = () => stop.kill("SIGTERM");
1140
+ } else {
1141
+ throw new TypeError("session budget abortable must be callable");
1142
+ }
1143
+
1144
+ if (this.signal.aborted) {
1145
+ try {
1146
+ callback(this.signal.reason);
1147
+ } catch {
1148
+ // The budget remains aborted even when a descendant cleanup fails.
1149
+ }
1150
+ return () => false;
1151
+ }
1152
+ this._abortables.set(key, callback);
1153
+ this._emit("budget:abortable-registered", {
1154
+ id: key,
1155
+ resources: this._abortables.size,
1156
+ });
1157
+ let registered = true;
1158
+ return () => {
1159
+ this._assertAuthorityMutationAllowed();
1160
+ if (!registered) return false;
1161
+ registered = false;
1162
+ const deleted = this._abortables.delete(key);
1163
+ if (deleted) {
1164
+ this._emit("budget:abortable-unregistered", {
1165
+ id: key,
1166
+ resources: this._abortables.size,
1167
+ });
1168
+ }
1169
+ return deleted;
1170
+ };
1171
+ }
1172
+
1173
+ _abortFor(reason) {
1174
+ return this.abort(new SessionBudgetError(reason), { reason });
1175
+ }
1176
+
1177
+ abort(
1178
+ reason = "session-aborted",
1179
+ { reason: reasonCode = null, skipAuthorityChange = false } = {},
1180
+ ) {
1181
+ this._assertAuthorityMutationAllowed();
1182
+ return this._abortUnchecked(reason, {
1183
+ reason: reasonCode,
1184
+ skipAuthorityChange,
1185
+ });
1186
+ }
1187
+
1188
+ _abortUnchecked(
1189
+ reason = "session-aborted",
1190
+ { reason: reasonCode = null, skipAuthorityChange = false } = {},
1191
+ ) {
1192
+ if (this._abortState) return false;
1193
+ const error = safeReason(reason);
1194
+ const code = String(
1195
+ reasonCode || error.budgetReason || error.code || "session-aborted",
1196
+ ).slice(0, 128);
1197
+ this._abortState = {
1198
+ reason: code,
1199
+ message: String(error.message || code).slice(0, 512),
1200
+ at: this._now(),
1201
+ };
1202
+ this._clearDeadline();
1203
+ try {
1204
+ this._abortController.abort(error);
1205
+ } catch {
1206
+ this._abortController.abort();
1207
+ }
1208
+ const callbacks = [...this._abortables.entries()];
1209
+ this._abortables.clear();
1210
+ const cleanupErrors = [];
1211
+ for (const [id, callback] of callbacks) {
1212
+ try {
1213
+ callback(error);
1214
+ } catch (cleanupError) {
1215
+ cleanupErrors.push({
1216
+ id,
1217
+ message: String(cleanupError?.message || cleanupError).slice(0, 256),
1218
+ });
1219
+ }
1220
+ }
1221
+ const detail = {
1222
+ reason: code,
1223
+ cleanupErrors,
1224
+ activeWork: this._activeWork.size,
1225
+ activeTools: this._activeTools.size,
1226
+ };
1227
+ if (skipAuthorityChange) this._emit("budget:aborted", detail);
1228
+ else this._authorityChanged("budget:aborted", detail);
1229
+ return true;
1230
+ }
1231
+
1232
+ _clearDeadline() {
1233
+ if (this._deadlineTimer === null) return;
1234
+ this._clearTimer(this._deadlineTimer);
1235
+ this._deadlineTimer = null;
1236
+ }
1237
+
1238
+ _armDeadline(now = this._now()) {
1239
+ this._clearDeadline();
1240
+ if (this.signal.aborted || this._recoveryUnknown.size > 0) return;
1241
+ const immediate = this._continuousReason(now);
1242
+ if (immediate) {
1243
+ this._abortFor(immediate);
1244
+ return;
1245
+ }
1246
+ let delay = Infinity;
1247
+ if (this.maxWallMs !== null && this._startedAt !== null) {
1248
+ delay = Math.min(delay, this.maxWallMs - this._elapsedAt(now));
1249
+ }
1250
+ if (this.maxToolMs !== null && this._activeTools.size > 0) {
1251
+ const remaining = this.maxToolMs - this._toolMsAt(now);
1252
+ delay = Math.min(delay, remaining / this._activeTools.size);
1253
+ }
1254
+ if (!Number.isFinite(delay)) return;
1255
+ const wait = Math.max(1, Math.min(MAX_TIMER_DELAY, Math.ceil(delay)));
1256
+ this._deadlineTimer = this._setTimer(() => {
1257
+ this._deadlineTimer = null;
1258
+ try {
1259
+ const reason = this._continuousReason(this._now());
1260
+ if (reason) this._abortFor(reason);
1261
+ else this._armDeadline(this._now());
1262
+ } catch {
1263
+ // Persistence rejection already failed the authority closed. Timer
1264
+ // callbacks must not turn that handled safety stop into an uncaught
1265
+ // process exception.
1266
+ }
1267
+ }, wait);
1268
+ this._deadlineTimer?.unref?.();
1269
+ }
1270
+
1271
+ pendingRecovery() {
1272
+ return [...this._recoveryUnknown.values()].map((entry) => {
1273
+ const copy = { ...entry };
1274
+ delete copy.resourceType;
1275
+ return copy;
1276
+ });
1277
+ }
1278
+
1279
+ adjudicateRecovery({ abandoned = [] } = {}) {
1280
+ this._assertAuthorityMutationAllowed();
1281
+ if (!Array.isArray(abandoned)) {
1282
+ throw new TypeError(
1283
+ "session budget abandoned recovery ids must be an array",
1284
+ );
1285
+ }
1286
+ const supplied = new Set(abandoned.map((id) => String(id)));
1287
+ const expected = new Set(this._recoveryUnknown.keys());
1288
+ if (
1289
+ supplied.size !== expected.size ||
1290
+ [...expected].some((id) => !supplied.has(id))
1291
+ ) {
1292
+ return {
1293
+ ok: false,
1294
+ reason: "recovery-adjudication-incomplete",
1295
+ pending: this.pendingRecovery(),
1296
+ };
1297
+ }
1298
+ const previousRecovery = [...this._recoveryUnknown.entries()];
1299
+ this._recoveryUnknown.clear();
1300
+ this._authorityChanged(
1301
+ "budget:recovery-adjudicated",
1302
+ {
1303
+ abandonedCount: supplied.size,
1304
+ },
1305
+ {
1306
+ rollback: () => {
1307
+ for (const [id, entry] of previousRecovery) {
1308
+ this._recoveryUnknown.set(id, entry);
1309
+ }
1310
+ },
1311
+ },
1312
+ );
1313
+ this._armDeadline();
1314
+ return { ok: true, abandoned: [...supplied].sort() };
1315
+ }
1316
+
1317
+ status(now = this._now()) {
1318
+ return {
1319
+ spawns: this.spawns,
1320
+ maxSpawns: this.maxSpawns,
1321
+ active: this._activeWork.size,
1322
+ maxConcurrent: this.maxConcurrent,
1323
+ maxDepth: this.maxDepth,
1324
+ turns: this.turns,
1325
+ maxTurns: this.maxTurns,
1326
+ tokens: this.tokens,
1327
+ maxTokens: this.maxTokens,
1328
+ spentUsd: this.cost.spentUsd,
1329
+ maxUsd: this.cost.limitUsd,
1330
+ elapsedMs: this._elapsedAt(now),
1331
+ maxWallMs: this.maxWallMs,
1332
+ toolMs: this._toolMsAt(now),
1333
+ maxToolMs: this.maxToolMs,
1334
+ activeTools: this._activeTools.size,
1335
+ resources: this._abortables.size,
1336
+ recoveryRequired: this._recoveryUnknown.size > 0,
1337
+ pendingRecovery: this._recoveryUnknown.size,
1338
+ unpricedUsage: this.unpricedUsage,
1339
+ aborted: this.signal.aborted,
1340
+ reason: this.reason(now),
1341
+ };
1342
+ }
1343
+
1344
+ snapshot(now = this._now()) {
1345
+ const activeWork = [...this._activeWork.values()].map((entry) =>
1346
+ snapshotResource(entry, now, "work"),
1347
+ );
1348
+ const pendingUsage = [...this._pendingUsage.values()].map((entry) =>
1349
+ snapshotResource(entry, now, "work"),
1350
+ );
1351
+ const activeTools = [...this._activeTools.values()].map((entry) =>
1352
+ snapshotResource(entry, now, "tool"),
1353
+ );
1354
+ const recoveryWork = [];
1355
+ const recoveryTools = [];
1356
+ for (const entry of this._recoveryUnknown.values()) {
1357
+ const { resourceType, ...persisted } = entry;
1358
+ if (resourceType === "tool") recoveryTools.push({ ...persisted });
1359
+ else recoveryWork.push({ ...persisted });
1360
+ }
1361
+ return {
1362
+ version: SESSION_RESOURCE_BUDGET_VERSION,
1363
+ limits: {
1364
+ maxConcurrent: this.maxConcurrent,
1365
+ maxSpawns: this.maxSpawns,
1366
+ maxDepth: this.maxDepth,
1367
+ maxTurns: this.maxTurns,
1368
+ maxTokens: this.maxTokens,
1369
+ maxUsd: this.cost.limitUsd,
1370
+ maxWallMs: this.maxWallMs,
1371
+ maxToolMs: this.maxToolMs,
1372
+ },
1373
+ totals: {
1374
+ spawns: this.spawns,
1375
+ turns: this.turns,
1376
+ tokens: this.tokens,
1377
+ spentUsd: this.cost.spentUsd,
1378
+ elapsedMs: this._elapsedAt(now),
1379
+ toolMs: this._toolMsAt(now),
1380
+ unpricedUsage: this.unpricedUsage,
1381
+ },
1382
+ inFlight: {
1383
+ work: [...activeWork, ...pendingUsage, ...recoveryWork],
1384
+ tools: [...activeTools, ...recoveryTools],
1385
+ },
1386
+ state: {
1387
+ started: this._startedAt !== null,
1388
+ abort: this._abortState ? { ...this._abortState } : null,
1389
+ },
1390
+ };
1391
+ }
1392
+
1393
+ static restore(
1394
+ snapshot,
1395
+ {
1396
+ overrides = {},
1397
+ table = undefined,
1398
+ now = () => Date.now(),
1399
+ setTimer = (fn, delay) => setTimeout(fn, delay),
1400
+ clearTimer = (timer) => clearTimeout(timer),
1401
+ signal = null,
1402
+ onEvent = null,
1403
+ onAuthorityChange = null,
1404
+ queueObservation = (callback) => queueMicrotask(callback),
1405
+ recoverUnsettled = "require-adjudication",
1406
+ } = {},
1407
+ ) {
1408
+ const normalized = normalizeSessionResourceBudgetSnapshot(snapshot);
1409
+ if (
1410
+ recoverUnsettled !== "require-adjudication" &&
1411
+ recoverUnsettled !== "abandon"
1412
+ ) {
1413
+ throw new TypeError("invalid session budget recovery policy");
1414
+ }
1415
+ const requestedLimits = normalizeLimitOverrides(overrides);
1416
+ const limits = {};
1417
+ for (const field of LIMIT_FIELDS) {
1418
+ limits[field] = tightenLimit(
1419
+ field,
1420
+ normalized.limits[field],
1421
+ requestedLimits[field],
1422
+ );
1423
+ }
1424
+ const budget = new SessionResourceBudget({
1425
+ ...limits,
1426
+ table,
1427
+ now,
1428
+ setTimer,
1429
+ clearTimer,
1430
+ signal,
1431
+ onEvent,
1432
+ onAuthorityChange,
1433
+ queueObservation,
1434
+ });
1435
+ budget.spawns = normalized.totals.spawns;
1436
+ budget.turns = normalized.totals.turns;
1437
+ budget.tokens = normalized.totals.tokens;
1438
+ budget.cost.spentUsd = normalized.totals.spentUsd;
1439
+ if (budget.cost.spentUsd > 0) budget.cost.priced = true;
1440
+ budget.unpricedUsage = normalized.totals.unpricedUsage;
1441
+ budget._elapsedMs = normalized.totals.elapsedMs;
1442
+ budget._toolMs = normalized.totals.toolMs;
1443
+ const restoredAt = budget._now();
1444
+ budget._startedAt = normalized.state.started ? restoredAt : null;
1445
+
1446
+ if (recoverUnsettled === "require-adjudication") {
1447
+ for (const entry of normalized.inFlight.work) {
1448
+ budget._issuedAuthorityIds.add(entry.id);
1449
+ budget._recoveryUnknown.set(entry.id, {
1450
+ ...entry,
1451
+ resourceType: "work",
1452
+ });
1453
+ }
1454
+ for (const entry of normalized.inFlight.tools) {
1455
+ budget._issuedAuthorityIds.add(entry.id);
1456
+ budget._recoveryUnknown.set(entry.id, {
1457
+ ...entry,
1458
+ resourceType: "tool",
1459
+ });
1460
+ }
1461
+ }
1462
+
1463
+ if (normalized.state.abort) {
1464
+ const error = new SessionBudgetError(
1465
+ normalized.state.abort.reason,
1466
+ normalized.state.abort.message,
1467
+ );
1468
+ budget.abort(error, { reason: normalized.state.abort.reason });
1469
+ } else if (budget._recoveryUnknown.size === 0) {
1470
+ const reason = budget._continuousReason(restoredAt);
1471
+ if (reason) budget._abortFor(reason);
1472
+ else budget._armDeadline(restoredAt);
1473
+ }
1474
+ budget._emit("budget:restored", {
1475
+ recoveryRequired: budget._recoveryUnknown.size > 0,
1476
+ });
1477
+ return budget;
1478
+ }
1479
+
1480
+ dispose() {
1481
+ this._assertAuthorityMutationAllowed();
1482
+ this._clearDeadline();
1483
+ if (this._externalSignal && this._externalAbortListener) {
1484
+ this._externalSignal.removeEventListener?.(
1485
+ "abort",
1486
+ this._externalAbortListener,
1487
+ );
1488
+ }
1489
+ this._externalAbortListener = null;
1490
+ }
1491
+ }
1492
+
1493
+ export function isContinuousSessionBudgetReason(reason) {
1494
+ return CONTINUOUS_REASONS.has(reason);
1495
+ }