@humain/humain-code 0.4.15 → 0.4.18
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.
- package/CHANGELOG.md +86 -0
- package/README.md +1 -1
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/anthropic-messages-TSNY5MWH.js +67 -0
- package/dist/bundle/chunks/azure-openai-responses-Z4DCXO2G.js +15 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +59 -42
- package/dist/bundle/chunks/{chunk-W2QRCQBX.js → chunk-26EAEXO5.js} +18 -16
- package/dist/bundle/chunks/chunk-2ZFUMXOZ.js +1790 -0
- package/dist/bundle/chunks/{chunk-W5YJZKPF.js → chunk-3UXBFT4Q.js} +2264 -2432
- package/dist/bundle/chunks/{chunk-OX2IBCCA.js → chunk-3XDL5ZE4.js} +88 -82
- package/dist/bundle/chunks/{chunk-LUL775V7.js → chunk-5K5RFXXO.js} +4 -4
- package/dist/bundle/chunks/{chunk-AIXI6RIE.js → chunk-7PRU6YW3.js} +114 -82
- package/dist/bundle/chunks/{chunk-DUSJT2W4.js → chunk-7VY5IL74.js} +1 -1
- package/dist/bundle/chunks/chunk-AWCJWXGD.js +212 -0
- package/dist/bundle/chunks/chunk-FZUJXM6D.js +816 -0
- package/dist/bundle/chunks/{chunk-KK3KUUMM.js → chunk-G6ABHCPB.js} +115 -95
- package/dist/bundle/chunks/{chunk-NNKA2PAP.js → chunk-HPSQKIWK.js} +1 -1
- package/dist/bundle/chunks/chunk-IJYVMOB4.js +6 -0
- package/dist/bundle/chunks/{chunk-36Q5UVQL.js → chunk-L5OUCJ7N.js} +9 -9
- package/dist/bundle/chunks/chunk-NCQ6WAQK.js +125 -0
- package/dist/bundle/chunks/chunk-NSMMDV3N.js +131 -0
- package/dist/bundle/chunks/{chunk-Z74ZYQPX.js → chunk-OKALNPTJ.js} +80 -210
- package/dist/bundle/chunks/{chunk-UHLW4KJ7.js → chunk-OWLBGSXY.js} +94 -91
- package/dist/bundle/chunks/{chunk-JRX7GYW3.js → chunk-P4UKLIQB.js} +8 -8
- package/dist/bundle/chunks/chunk-PY7SOXCA.js +10 -0
- package/dist/bundle/chunks/chunk-Q7VXYXY3.js +7 -0
- package/dist/bundle/chunks/{chunk-COF5P635.js → chunk-QEF72EIZ.js} +13 -13
- package/dist/bundle/chunks/{chunk-EYIYBQAR.js → chunk-RXOCQRBG.js} +1 -1
- package/dist/bundle/chunks/{chunk-BVHXWQLD.js → chunk-SCBU5WOP.js} +1 -1
- package/dist/bundle/chunks/{chunk-DNGJMRJW.js → chunk-SCIGZFN5.js} +11 -11
- package/dist/bundle/chunks/{chunk-UDVC7A5S.js → chunk-TIFFHHW6.js} +16 -14
- package/dist/bundle/chunks/{chunk-L3J4P5JR.js → chunk-UGJAAWNC.js} +1 -1
- package/dist/bundle/chunks/chunk-V76YPIMT.js +48 -0
- package/dist/bundle/chunks/{chunk-Y3RFGBG2.js → chunk-X3O5MCKJ.js} +1 -1
- package/dist/bundle/chunks/chunk-Y26OS23T.js +80 -0
- package/dist/bundle/chunks/chunk-YDBNMIA3.js +34 -0
- package/dist/bundle/chunks/chunk-YLYOJQQX.js +1951 -0
- package/dist/bundle/chunks/{chunk-TJG52LZB.js → chunk-YMBXWW36.js} +1 -1
- package/dist/bundle/chunks/{cli-SRI4UOSL.js → cli-2NKM2RNJ.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-JGN7NZCV.js → cloudflare-workers-ai-system-one-MUJQ6LT2.js} +1 -1
- package/dist/bundle/chunks/{compat-2S3PCPEI.js → compat-VDGEZSVM.js} +8 -8
- package/dist/bundle/chunks/dist-LKDZAEUQ.js +7 -0
- package/dist/bundle/chunks/{dist-JXEXN6S2.js → dist-XVXV2CL4.js} +1 -1
- package/dist/bundle/chunks/{dist-SGQMXO45.js → dist-ZJIYY3GA.js} +1416 -866
- package/dist/bundle/chunks/dist-cjs-AXBW3N4F.js +182 -0
- package/dist/bundle/chunks/{easter-egg-3d-ZJ2JUFOA.js → easter-egg-3d-VGJ77XZQ.js} +1 -1
- package/dist/bundle/chunks/es-N6YFJOD7.js +1901 -0
- package/dist/bundle/chunks/{esm-NCUV2DF7.js → esm-GIR7QH65.js} +1 -1
- package/dist/bundle/chunks/{execute-LRTXH4YJ.js → execute-ZBEZNJ4E.js} +10 -9
- package/dist/bundle/chunks/{extract-OZW5JHG6.js → extract-RFWEHH6W.js} +16 -15
- package/dist/bundle/chunks/github-copilot.js +34 -47
- package/dist/bundle/chunks/{google-generative-ai-YXXFSTX7.js → google-generative-ai-4OVYRP24.js} +2 -2
- package/dist/bundle/chunks/{google-vertex-3IVWLYJ5.js → google-vertex-3WQAZJQD.js} +2 -2
- package/dist/bundle/chunks/host-63SNKK5Y.js +2 -0
- package/dist/bundle/chunks/jiti-static-loader-7OZNBOCI.js +2 -0
- package/dist/bundle/chunks/{mistral-conversations-Y7GWO3QB.js → mistral-conversations-G3GN6CMT.js} +20 -20
- package/dist/bundle/chunks/{node-ELWNZC34.js → node-A6SZ3T7E.js} +185 -185
- package/dist/bundle/chunks/{node-SPBTZUUS.js → node-DZCAT4Q6.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-NSXWHIDT.js → openai-codex-responses-FJFDAWHI.js} +17 -17
- package/dist/bundle/chunks/openai-completions-IC7WRLTI.js +82 -0
- package/dist/bundle/chunks/{openai-decisions-QWEISDVO.js → openai-decisions-HESOHYZB.js} +1 -1
- package/dist/bundle/chunks/openai-responses-XXCYDFSM.js +24 -0
- package/dist/bundle/chunks/{openrouter-images-BMVMAROU.js → openrouter-images-DT2HMZNO.js} +1 -1
- package/dist/bundle/chunks/pdfjs-EK6K7CXX.js +3593 -0
- package/dist/bundle/chunks/{pi-messages-XNEG23NU.js → pi-messages-SAOV3JNW.js} +1 -1
- package/dist/bundle/chunks/{runtime-VGSK3QCM.js → runtime-HJEUOD4R.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-62YHYXZV.js → typesafe-system-one-HCMGHK6A.js} +1 -1
- package/dist/bundle/chunks/{undici-7EW63V4X.js → undici-4BK3MVJV.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-CFJTDIXL.js +5 -0
- package/dist/bundle/cli-runtime.js +3 -3
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/flow/package.json +6 -5
- package/dist/bundle/index.js +8 -8
- package/dist/bundle/rpc-entry.js +3 -3
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +4 -4
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/coordination/adapter/index.d.ts.map +1 -1
- package/dist/coordination/adapter/index.js +1 -1
- package/dist/coordination/adapter/index.js.map +1 -1
- package/dist/coordination/adapter/integration-notices.d.ts +1 -1
- package/dist/coordination/adapter/integration-notices.d.ts.map +1 -1
- package/dist/coordination/adapter/integration-notices.js +5 -2
- package/dist/coordination/adapter/integration-notices.js.map +1 -1
- package/dist/coordination/broker/extension-state.js +3 -3
- package/dist/coordination/broker/extension-state.js.map +1 -1
- package/dist/coordination/transport/framing.d.ts.map +1 -1
- package/dist/coordination/transport/framing.js +2 -1
- package/dist/coordination/transport/framing.js.map +1 -1
- package/dist/core/account-reporting.d.ts +3 -1
- package/dist/core/account-reporting.d.ts.map +1 -1
- package/dist/core/account-reporting.js +12 -2
- package/dist/core/account-reporting.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +39 -36
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +4 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +5 -4
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/codex-usage.d.ts +11 -2
- package/dist/core/codex-usage.d.ts.map +1 -1
- package/dist/core/codex-usage.js +74 -2
- package/dist/core/codex-usage.js.map +1 -1
- package/dist/core/export-html/template.js +21 -16
- package/dist/core/model-config.d.ts +33 -8
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +22 -4
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts +56 -43
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +256 -361
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +6 -3
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +19 -5
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js +7 -2
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/oauth-account-pool.d.ts +9 -1
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +63 -12
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +7 -2
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +2 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +2 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +11 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +4 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +8 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/slash-commands.js +1 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +2 -0
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +21 -0
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/renderers/read.d.ts.map +1 -1
- package/dist/core/tools/renderers/read.js +7 -10
- package/dist/core/tools/renderers/read.js.map +1 -1
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +4 -7
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/trace/redaction.d.ts.map +1 -1
- package/dist/core/trace/redaction.js +3 -1
- package/dist/core/trace/redaction.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +12 -0
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/index.d.ts.map +1 -1
- package/dist/extensions/codemode/index.js +5 -0
- package/dist/extensions/codemode/index.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +74 -20
- package/dist/humain/flow-accounts-host.d.ts.map +1 -1
- package/dist/humain/flow-accounts-host.js +3 -0
- package/dist/humain/flow-accounts-host.js.map +1 -1
- package/dist/humain/node-provider.d.ts.map +1 -1
- package/dist/humain/node-provider.js +2 -0
- package/dist/humain/node-provider.js.map +1 -1
- package/dist/humain/trace-capture/index.js +3 -3
- package/dist/humain/trace-capture/index.js.map +1 -1
- package/dist/humain/web-access/vendor/credential-source.d.ts +2 -0
- package/dist/humain/web-access/vendor/credential-source.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/credential-source.js +50 -4
- package/dist/humain/web-access/vendor/credential-source.js.map +1 -1
- package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-page.js +3 -1
- package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.js +2 -0
- package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
- package/dist/humain/web-access/vendor/deepseek.d.ts +4 -0
- package/dist/humain/web-access/vendor/deepseek.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/deepseek.js +201 -0
- package/dist/humain/web-access/vendor/deepseek.js.map +1 -0
- package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/extract.js +4 -2
- package/dist/humain/web-access/vendor/extract.js.map +1 -1
- package/dist/humain/web-access/vendor/gemini-adc.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/gemini-adc.js +49 -5
- package/dist/humain/web-access/vendor/gemini-adc.js.map +1 -1
- package/dist/humain/web-access/vendor/gemini-search.d.ts +3 -3
- package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/gemini-search.js +11 -4
- package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
- package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/index.js +16 -1
- package/dist/humain/web-access/vendor/index.js.map +1 -1
- package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/page-query.js +12 -6
- package/dist/humain/web-access/vendor/page-query.js.map +1 -1
- package/dist/humain/web-access/vendor/query-rewrite.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/query-rewrite.js +11 -4
- package/dist/humain/web-access/vendor/query-rewrite.js.map +1 -1
- package/dist/humain/web-access/vendor/searxng.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/searxng.js +2 -1
- package/dist/humain/web-access/vendor/searxng.js.map +1 -1
- package/dist/humain/web-access/vendor/ssrf-protection.d.ts +1 -0
- package/dist/humain/web-access/vendor/ssrf-protection.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/ssrf-protection.js +10 -0
- package/dist/humain/web-access/vendor/ssrf-protection.js.map +1 -1
- package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/summary-review.js +17 -6
- package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
- package/dist/humain/web-access/vendor/utils.d.ts +2 -0
- package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/utils.js +18 -0
- package/dist/humain/web-access/vendor/utils.js.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-core.d.ts +2 -0
- package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +10 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +5 -0
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-indicator.js +27 -2
- package/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +2 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +4 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +2 -9
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +28 -14
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/oauth-account-format.d.ts +4 -4
- package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
- package/dist/modes/interactive/oauth-account-format.js +5 -2
- package/dist/modes/interactive/oauth-account-format.js.map +1 -1
- package/dist/modes/interactive/session-share.d.ts.map +1 -1
- package/dist/modes/interactive/session-share.js +9 -2
- package/dist/modes/interactive/session-share.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +8 -3
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +2 -1
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/cli.md +3 -3
- package/docs/codemode.md +3 -1
- package/docs/coordination.md +6 -0
- package/docs/docs.json +4 -0
- package/docs/environment-variables.md +4 -0
- package/docs/flow.md +6 -0
- package/docs/humain-code-forge-flow-walkthrough.md +1 -1
- package/docs/humain-code.md +2 -4
- package/docs/json.md +2 -2
- package/docs/llama-cpp.md +1 -1
- package/docs/nvidia-rtx-llama-cpp.md +96 -0
- package/docs/rpc-commands.md +1 -1
- package/docs/rpc.md +9 -1
- package/docs/sessions.md +1 -1
- package/docs/settings.md +2 -0
- package/docs/trace.md +4 -0
- package/docs/usage.md +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +16 -6
- package/examples/extensions/custom-provider-anthropic/package.json +2 -2
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +16 -16
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/minimal-mode.ts +4 -4
- package/examples/extensions/sandbox/package-lock.json +6 -6
- package/examples/extensions/sandbox/package.json +2 -2
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/plugins/pi-example-plugin/package.json +2 -2
- package/examples/rpc-subagent-progress-host.ts +6 -2
- package/npm-shrinkwrap.json +129 -171
- package/package.json +19 -19
- package/schemas/models.schema.json +9 -5
- package/schemas/settings.schema.json +32 -0
- package/src/coordination/UPSTREAM.md +31 -1
- package/src/coordination/upstream.json +3 -3
- package/src/humain/adhd/UPSTREAM.md +8 -0
- package/src/humain/caveman/UPSTREAM.md +19 -3
- package/src/humain/caveman/upstream.json +2 -2
- package/src/humain/ponytail/UPSTREAM.md +23 -2
- package/src/humain/ponytail/upstream.json +8 -8
- package/src/humain/ponytail/vendor/skills/ponytail/SKILL.md +1 -1
- package/src/humain/ponytail/vendor/skills/ponytail-debt/SKILL.md +1 -2
- package/src/humain/ponytail/vendor/skills/ponytail-gain/SKILL.md +0 -1
- package/src/humain/web-access/UPSTREAM.md +45 -1
- package/src/humain/web-access/upstream.json +4 -4
- package/dist/bundle/chunks/anthropic-messages-YSAHA7QM.js +0 -67
- package/dist/bundle/chunks/azure-openai-responses-Z5XYDPHS.js +0 -15
- package/dist/bundle/chunks/chunk-2TTB6GIB.js +0 -47
- package/dist/bundle/chunks/chunk-5JHUWRJN.js +0 -1790
- package/dist/bundle/chunks/chunk-A7QKOI62.js +0 -572
- package/dist/bundle/chunks/chunk-FRUFMISJ.js +0 -505
- package/dist/bundle/chunks/chunk-MF2NEHP4.js +0 -1575
- package/dist/bundle/chunks/chunk-MG5PX4KU.js +0 -31
- package/dist/bundle/chunks/chunk-OEOXBLWI.js +0 -540
- package/dist/bundle/chunks/chunk-RYC5BYVE.js +0 -5
- package/dist/bundle/chunks/chunk-YJ3NQWES.js +0 -9
- package/dist/bundle/chunks/dist-MNSGVI4C.js +0 -7
- package/dist/bundle/chunks/dist-cjs-4BMVQ74V.js +0 -179
- package/dist/bundle/chunks/es-YEFEOGR3.js +0 -1905
- package/dist/bundle/chunks/host-2RMBOGA7.js +0 -2
- package/dist/bundle/chunks/jiti-static-loader-2RCDI6B4.js +0 -2
- package/dist/bundle/chunks/openai-completions-WGBQHTYA.js +0 -79
- package/dist/bundle/chunks/openai-responses-OKGCSIEY.js +0 -23
- package/dist/bundle/chunks/pdfjs-6UVU6XFX.js +0 -3564
- package/dist/bundle/chunks/virtual-modules-7HDINPIK.js +0 -5
- /package/dist/bundle/chunks/{chunk-XQRYOCHA.js → chunk-WZMA7HAJ.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-state.js","sourceRoot":"","sources":["../../../src/coordination/broker/extension-state.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,EAAE,IA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derived from pi-intercom (MIT, Copyright (c) 2026 Nico Bailon), commit a5fad4df; modified for HUMAIN Code CLI.\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, readdirSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { ensureRuntimeDir } from \"../transport/paths.ts\";\nimport { readJsonFile, writeJsonAtomic } from \"./atomic-file.ts\";\n\nconst DEFAULT_MAX_STATE_BYTES = 64 * 1024;\n/** Payload limit of the broker's own manager: a 64 KiB record value plus its envelope. */\nexport const BROKER_STATE_MAX_PAYLOAD_BYTES = 72 * 1024;\nconst STATE_FILE_NAME = /^([a-f0-9]{64})\\.json(\\.bak)?$/;\n\ninterface StateEnvelope {\n\tformatVersion: 1;\n\tnamespace: string;\n\trevision: number;\n\tupdatedAt: number;\n\tpayloadSha256: string;\n\tpayload: unknown;\n}\n\nexport interface StateCommitResult {\n\tcommitted: boolean;\n\trevision: number;\n\treason?: string;\n\tpayload?: unknown;\n\t/** True only when the write failed in the persist step; nothing changed. */\n\tpersistFailed?: boolean;\n}\n\n/** Where a state read by `loadStateDetailed` came from. */\nexport type StateSource = \"main\" | \"backup\" | \"none\";\n\nexport interface DetailedState {\n\tstate: { revision: number; payload: unknown } | null;\n\tsource: StateSource;\n\t/** The main file exists but is invalid; `state` is then the valid `.bak` (source \"backup\") or null. */\n\tmainInvalid: boolean;\n}\n\nexport interface ListedState {\n\tnamespace: string;\n\trevision: number;\n\tupdatedAt: number;\n\tpayload: unknown;\n}\n\nfunction serializePayload(payload: unknown, maxBytes: number): string | null {\n\ttry {\n\t\tconst json = JSON.stringify(payload);\n\t\tif (json === undefined || Buffer.byteLength(json, \"utf8\") > maxBytes) {\n\t\t\treturn null;\n\t\t}\n\t\treturn json;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction payloadHash(payloadJson: string): string {\n\treturn createHash(\"sha256\").update(payloadJson).digest(\"hex\");\n}\n\nexport class ExtensionStateManager {\n\tprivate readonly states = new Map<string, { revision: number; payload: unknown }>();\n\tprivate readonly stateDir: string;\n\tprivate readonly maxPayloadBytes: number;\n\t/** Envelope overhead (namespace, revision, hash) on top of the payload limit. */\n\tprivate readonly maxFileBytes: number;\n\n\tconstructor(runtimeDir: string, options: { maxPayloadBytes?: number } = {}) {\n\t\tthis.stateDir = join(runtimeDir, \"extension-state\");\n\t\tconst maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_STATE_BYTES;\n\t\tif (!Number.isSafeInteger(maxPayloadBytes) || maxPayloadBytes <= 0) {\n\t\t\tthrow new Error(`maxPayloadBytes must be a positive integer, got ${maxPayloadBytes}`);\n\t\t}\n\t\tthis.maxPayloadBytes = maxPayloadBytes;\n\t\tthis.maxFileBytes = this.maxPayloadBytes * 2;\n\t\tensureRuntimeDir(this.stateDir);\n\t}\n\n\tprivate statePath(namespace: string): string {\n\t\tconst hash = createHash(\"sha256\").update(namespace).digest(\"hex\");\n\t\treturn join(this.stateDir, `${hash}.json`);\n\t}\n\n\tprivate backupPath(namespace: string): string {\n\t\treturn `${this.statePath(namespace)}.bak`;\n\t}\n\n\t/** The backup is only a fallback for a main file that exists but is invalid; a backup alone is a leftover. */\n\tprivate mainFileExists(mainPath: string): boolean {\n\t\ttry {\n\t\t\tlstatSync(mainPath);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** `namespace` undefined accepts the namespace the file names; the caller then checks it against the file name. */\n\tprivate readEnvelope(filePath: string, namespace?: string): StateEnvelope | null {\n\t\ttry {\n\t\t\t// Bounded, regular-file-only and no-follow: a FIFO, symlink or oversized file at the path reads as\n\t\t\t// \"no state\" instead of blocking or being followed.\n\t\t\tconst value = readJsonFile(filePath, this.maxFileBytes);\n\t\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\n\t\t\tconst envelope = value as Record<string, unknown>;\n\t\t\tconst revision = envelope.revision;\n\t\t\tconst updatedAt = envelope.updatedAt;\n\t\t\tconst payloadSha256 = envelope.payloadSha256;\n\t\t\tif (\n\t\t\t\tenvelope.formatVersion !== 1 ||\n\t\t\t\ttypeof envelope.namespace !== \"string\" ||\n\t\t\t\t(namespace !== undefined && envelope.namespace !== namespace) ||\n\t\t\t\ttypeof revision !== \"number\" ||\n\t\t\t\t!Number.isSafeInteger(revision) ||\n\t\t\t\trevision < 0 ||\n\t\t\t\ttypeof updatedAt !== \"number\" ||\n\t\t\t\ttypeof payloadSha256 !== \"string\"\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst payloadJson = serializePayload(envelope.payload, this.maxPayloadBytes);\n\t\t\tif (payloadJson === null || payloadHash(payloadJson) !== payloadSha256) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tformatVersion: 1,\n\t\t\t\tnamespace: envelope.namespace,\n\t\t\t\trevision,\n\t\t\t\tupdatedAt,\n\t\t\t\tpayloadSha256,\n\t\t\t\tpayload: envelope.payload,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tloadState(namespace: string): { revision: number; payload: unknown } | null {\n\t\tconst cached = this.states.get(namespace);\n\t\tif (cached) return cached;\n\n\t\tconst envelope =\n\t\t\tthis.readEnvelope(this.statePath(namespace), namespace) ??\n\t\t\t(this.mainFileExists(this.statePath(namespace))\n\t\t\t\t? this.readEnvelope(this.backupPath(namespace), namespace)\n\t\t\t\t: null);\n\t\tif (!envelope) return null;\n\n\t\tconst state = { revision: envelope.revision, payload: envelope.payload };\n\t\tthis.states.set(namespace, state);\n\t\treturn state;\n\t}\n\n\tcommitState(namespace: string, expectedRevision: number, payload: unknown): StateCommitResult {\n\t\tconst payloadJson = serializePayload(payload, this.maxPayloadBytes);\n\t\t// Invariant: observable state is the disk plus what loadState/getCurrentRevision return. Filling an empty\n\t\t// cache from unchanged disk here, even when the persist below fails, changes neither.\n\t\tconst current = this.loadState(namespace);\n\t\tconst currentRevision = current?.revision ?? 0;\n\n\t\tif (payloadJson === null) {\n\t\t\treturn {\n\t\t\t\tcommitted: false,\n\t\t\t\trevision: currentRevision,\n\t\t\t\treason: `Invalid extension state or payload exceeds ${this.maxPayloadBytes / 1024} KiB limit`,\n\t\t\t};\n\t\t}\n\t\tif (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) {\n\t\t\treturn { committed: false, revision: currentRevision, reason: \"Invalid expected revision\" };\n\t\t}\n\t\tif (expectedRevision !== currentRevision) {\n\t\t\treturn {\n\t\t\t\tcommitted: false,\n\t\t\t\trevision: currentRevision,\n\t\t\t\treason: \"Revision mismatch\",\n\t\t\t\t...(current ? { payload: current.payload } : {}),\n\t\t\t};\n\t\t}\n\n\t\tconst envelope: StateEnvelope = {\n\t\t\tformatVersion: 1,\n\t\t\tnamespace,\n\t\t\trevision: currentRevision + 1,\n\t\t\tupdatedAt: Date.now(),\n\t\t\tpayloadSha256: payloadHash(payloadJson),\n\t\t\tpayload,\n\t\t};\n\t\tconst statePath = this.statePath(namespace);\n\t\tconst backupPath = this.backupPath(namespace);\n\n\t\ttry {\n\t\t\t// Main first: a failed write leaves the main file and the backup exactly as they were.\n\t\t\t// The previous envelope is the one loadState recovered: main if valid, else the backup beside an\n\t\t\t// existing main. Retaining it keeps the recovery copy across a commit over a corrupt main.\n\t\t\tconst previous =\n\t\t\t\tthis.readEnvelope(statePath, namespace) ??\n\t\t\t\t(this.mainFileExists(statePath) ? this.readEnvelope(backupPath, namespace) : null);\n\t\t\t// Recreating a deleted state: drop a stale backup first, so a later corrupt main cannot recover the\n\t\t\t// old incarnation from it. If it cannot be removed, nothing is written.\n\t\t\tif (!previous && !this.mainFileExists(statePath)) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(backupPath);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteJsonAtomic(statePath, envelope, this.maxFileBytes);\n\t\t\t// The new state is durable now. The backup (previous state, re-serialized from the validated envelope\n\t\t\t// and written atomically so a planted symlink is replaced) is best-effort; with no previous state a\n\t\t\t// stale backup of an older incarnation is dropped so it cannot be recovered later.\n\t\t\ttry {\n\t\t\t\tif (previous) writeJsonAtomic(backupPath, previous, this.maxFileBytes);\n\t\t\t\telse unlinkSync(backupPath);\n\t\t\t} catch {\n\t\t\t\t// Recovery copy only; the commit stands.\n\t\t\t}\n\n\t\t\tconst state = { revision: envelope.revision, payload };\n\t\t\tthis.states.set(namespace, state);\n\t\t\treturn { committed: true, revision: envelope.revision };\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tcommitted: false,\n\t\t\t\trevision: currentRevision,\n\t\t\t\treason: \"Failed to persist extension state\",\n\t\t\t\tpersistFailed: true,\n\t\t\t};\n\t\t}\n\t}\n\n\tgetCurrentRevision(namespace: string): number {\n\t\treturn this.loadState(namespace)?.revision ?? 0;\n\t}\n\n\t/**\n\t * Like `loadState`, but reads the disk (not the cache) and says where the state came from. `loadState` falls\n\t * back to a valid older `.bak` when the main file exists but is invalid; a caller for which an older state\n\t * is wrong (the integration state: it would roll back a fencing generation) uses this to tell the two apart.\n\t */\n\tloadStateDetailed(namespace: string): DetailedState {\n\t\tconst mainPath = this.statePath(namespace);\n\t\tconst main = this.readEnvelope(mainPath, namespace);\n\t\tif (main)\n\t\t\treturn { state: { revision: main.revision, payload: main.payload }, source: \"main\", mainInvalid: false };\n\t\tif (!this.mainFileExists(mainPath)) return { state: null, source: \"none\", mainInvalid: false };\n\t\tconst backup = this.readEnvelope(this.backupPath(namespace), namespace);\n\t\treturn {\n\t\t\tstate: backup ? { revision: backup.revision, payload: backup.payload } : null,\n\t\t\tsource: backup ? \"backup\" : \"none\",\n\t\t\tmainInvalid: true,\n\t\t};\n\t}\n\n\t/**\n\t * Every valid envelope whose stored namespace starts with `prefix`, sorted by namespace. A file is listed\n\t * only when its name equals the hash of its stored namespace and its payload hash verifies; an invalid main\n\t * file falls back to its .bak sibling, as loadState does. Reads disk, not the cache.\n\t */\n\tlistStates(prefix: string): ListedState[] {\n\t\tconst hashes = new Set<string>();\n\t\tfor (const name of readdirSync(this.stateDir)) {\n\t\t\tconst match = STATE_FILE_NAME.exec(name);\n\t\t\tif (match?.[1]) hashes.add(match[1]);\n\t\t}\n\t\tconst listed: ListedState[] = [];\n\t\tfor (const hash of hashes) {\n\t\t\tconst mainPath = join(this.stateDir, `${hash}.json`);\n\t\t\tif (!this.mainFileExists(mainPath)) continue;\n\t\t\tfor (const filePath of [mainPath, `${mainPath}.bak`]) {\n\t\t\t\tconst envelope = this.readEnvelope(filePath);\n\t\t\t\tif (!envelope || createHash(\"sha256\").update(envelope.namespace).digest(\"hex\") !== hash) continue;\n\t\t\t\tif (envelope.namespace.startsWith(prefix)) {\n\t\t\t\t\tlisted.push({\n\t\t\t\t\t\tnamespace: envelope.namespace,\n\t\t\t\t\t\trevision: envelope.revision,\n\t\t\t\t\t\tupdatedAt: envelope.updatedAt,\n\t\t\t\t\t\tpayload: envelope.payload,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn listed.sort((a, b) => (a.namespace < b.namespace ? -1 : a.namespace > b.namespace ? 1 : 0));\n\t}\n\n\t/** Removes the state file, its backup and the cache entry. Absent = true. Returns false on failure. */\n\tdeleteState(namespace: string): boolean {\n\t\t// Main first: on failure both files stay as they were. Once main is gone a leftover backup is inert\n\t\t// (loadState and listStates only read it beside an existing main file), so its removal is best-effort.\n\t\ttry {\n\t\t\tunlinkSync(this.statePath(namespace));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") return false;\n\t\t}\n\t\ttry {\n\t\t\tunlinkSync(this.backupPath(namespace));\n\t\t} catch {\n\t\t\t// Inert leftover.\n\t\t}\n\t\tthis.states.delete(namespace);\n\t\treturn true;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"extension-state.js","sourceRoot":"","sources":["../../../src/coordination/broker/extension-state.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gBAAE,OAAO,KAAK,CAAC;QACtE,CAAC;QACD,IAAI,CAAC;YACJ,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;QACxC,CAAC;QAAC,MAAM,CAAC;YACR,kBAAkB;QACnB,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC9B,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["// Derived from pi-intercom (MIT, Copyright (c) 2026 Nico Bailon), commit ddf28818; modified for HUMAIN Code CLI.\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, readdirSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { ensureRuntimeDir } from \"../transport/paths.ts\";\nimport { readJsonFile, writeJsonAtomic } from \"./atomic-file.ts\";\n\nconst DEFAULT_MAX_STATE_BYTES = 64 * 1024;\n/** Payload limit of the broker's own manager: a 64 KiB record value plus its envelope. */\nexport const BROKER_STATE_MAX_PAYLOAD_BYTES = 72 * 1024;\nconst STATE_FILE_NAME = /^([a-f0-9]{64})\\.json(\\.bak)?$/;\n\ninterface StateEnvelope {\n\tformatVersion: 1;\n\tnamespace: string;\n\trevision: number;\n\tupdatedAt: number;\n\tpayloadSha256: string;\n\tpayload: unknown;\n}\n\nexport interface StateCommitResult {\n\tcommitted: boolean;\n\trevision: number;\n\treason?: string;\n\tpayload?: unknown;\n\t/** True only when the write failed in the persist step; nothing changed. */\n\tpersistFailed?: boolean;\n}\n\n/** Where a state read by `loadStateDetailed` came from. */\nexport type StateSource = \"main\" | \"backup\" | \"none\";\n\nexport interface DetailedState {\n\tstate: { revision: number; payload: unknown } | null;\n\tsource: StateSource;\n\t/** The main file exists but is invalid; `state` is then the valid `.bak` (source \"backup\") or null. */\n\tmainInvalid: boolean;\n}\n\nexport interface ListedState {\n\tnamespace: string;\n\trevision: number;\n\tupdatedAt: number;\n\tpayload: unknown;\n}\n\nfunction serializePayload(payload: unknown, maxBytes: number): string | null {\n\ttry {\n\t\tconst json = JSON.stringify(payload);\n\t\tif (json === undefined || Buffer.byteLength(json, \"utf8\") > maxBytes) {\n\t\t\treturn null;\n\t\t}\n\t\treturn json;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction payloadHash(payloadJson: string): string {\n\treturn createHash(\"sha256\").update(payloadJson).digest(\"hex\");\n}\n\nexport class ExtensionStateManager {\n\tprivate readonly states = new Map<string, { revision: number; payload: unknown }>();\n\tprivate readonly stateDir: string;\n\tprivate readonly maxPayloadBytes: number;\n\t/** Envelope overhead (namespace, revision, hash) on top of the payload limit. */\n\tprivate readonly maxFileBytes: number;\n\n\tconstructor(runtimeDir: string, options: { maxPayloadBytes?: number } = {}) {\n\t\tthis.stateDir = join(runtimeDir, \"extension-state\");\n\t\tconst maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_STATE_BYTES;\n\t\tif (!Number.isSafeInteger(maxPayloadBytes) || maxPayloadBytes <= 0) {\n\t\t\tthrow new Error(`maxPayloadBytes must be a positive integer, got ${maxPayloadBytes}`);\n\t\t}\n\t\tthis.maxPayloadBytes = maxPayloadBytes;\n\t\tthis.maxFileBytes = this.maxPayloadBytes * 2;\n\t\tensureRuntimeDir(this.stateDir);\n\t}\n\n\tprivate statePath(namespace: string): string {\n\t\tconst hash = createHash(\"sha256\").update(namespace).digest(\"hex\");\n\t\treturn join(this.stateDir, `${hash}.json`);\n\t}\n\n\tprivate backupPath(namespace: string): string {\n\t\treturn `${this.statePath(namespace)}.bak`;\n\t}\n\n\t/** The backup is only a fallback for a main file that exists but is invalid; a backup alone is a leftover. */\n\tprivate mainFileExists(mainPath: string): boolean {\n\t\ttry {\n\t\t\tlstatSync(mainPath);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** `namespace` undefined accepts the namespace the file names; the caller then checks it against the file name. */\n\tprivate readEnvelope(filePath: string, namespace?: string): StateEnvelope | null {\n\t\ttry {\n\t\t\t// Bounded, regular-file-only and no-follow: a FIFO, symlink or oversized file at the path reads as\n\t\t\t// \"no state\" instead of blocking or being followed.\n\t\t\tconst value = readJsonFile(filePath, this.maxFileBytes);\n\t\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\n\t\t\tconst envelope = value as Record<string, unknown>;\n\t\t\tconst revision = envelope.revision;\n\t\t\tconst updatedAt = envelope.updatedAt;\n\t\t\tconst payloadSha256 = envelope.payloadSha256;\n\t\t\tif (\n\t\t\t\tenvelope.formatVersion !== 1 ||\n\t\t\t\ttypeof envelope.namespace !== \"string\" ||\n\t\t\t\t(namespace !== undefined && envelope.namespace !== namespace) ||\n\t\t\t\ttypeof revision !== \"number\" ||\n\t\t\t\t!Number.isSafeInteger(revision) ||\n\t\t\t\trevision < 0 ||\n\t\t\t\ttypeof updatedAt !== \"number\" ||\n\t\t\t\ttypeof payloadSha256 !== \"string\"\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst payloadJson = serializePayload(envelope.payload, this.maxPayloadBytes);\n\t\t\tif (payloadJson === null || payloadHash(payloadJson) !== payloadSha256) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tformatVersion: 1,\n\t\t\t\tnamespace: envelope.namespace,\n\t\t\t\trevision,\n\t\t\t\tupdatedAt,\n\t\t\t\tpayloadSha256,\n\t\t\t\tpayload: envelope.payload,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tloadState(namespace: string): { revision: number; payload: unknown } | null {\n\t\tconst cached = this.states.get(namespace);\n\t\tif (cached) return cached;\n\n\t\tconst envelope =\n\t\t\tthis.readEnvelope(this.statePath(namespace), namespace) ??\n\t\t\t(this.mainFileExists(this.statePath(namespace))\n\t\t\t\t? this.readEnvelope(this.backupPath(namespace), namespace)\n\t\t\t\t: null);\n\t\tif (!envelope) return null;\n\n\t\tconst state = { revision: envelope.revision, payload: envelope.payload };\n\t\tthis.states.set(namespace, state);\n\t\treturn state;\n\t}\n\n\tcommitState(namespace: string, expectedRevision: number, payload: unknown): StateCommitResult {\n\t\tconst payloadJson = serializePayload(payload, this.maxPayloadBytes);\n\t\t// Invariant: observable state is the disk plus what loadState/getCurrentRevision return. Filling an empty\n\t\t// cache from unchanged disk here, even when the persist below fails, changes neither.\n\t\tconst current = this.loadState(namespace);\n\t\tconst currentRevision = current?.revision ?? 0;\n\n\t\tif (payloadJson === null) {\n\t\t\treturn {\n\t\t\t\tcommitted: false,\n\t\t\t\trevision: currentRevision,\n\t\t\t\treason: `Invalid extension state or payload exceeds ${this.maxPayloadBytes / 1024} KiB limit`,\n\t\t\t};\n\t\t}\n\t\tif (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) {\n\t\t\treturn { committed: false, revision: currentRevision, reason: \"Invalid expected revision\" };\n\t\t}\n\t\tif (expectedRevision !== currentRevision) {\n\t\t\treturn {\n\t\t\t\tcommitted: false,\n\t\t\t\trevision: currentRevision,\n\t\t\t\treason: \"Revision mismatch\",\n\t\t\t\t...(current ? { payload: current.payload } : {}),\n\t\t\t};\n\t\t}\n\n\t\tconst envelope: StateEnvelope = {\n\t\t\tformatVersion: 1,\n\t\t\tnamespace,\n\t\t\trevision: currentRevision + 1,\n\t\t\tupdatedAt: Date.now(),\n\t\t\tpayloadSha256: payloadHash(payloadJson),\n\t\t\tpayload,\n\t\t};\n\t\tconst statePath = this.statePath(namespace);\n\t\tconst backupPath = this.backupPath(namespace);\n\n\t\ttry {\n\t\t\t// Main first: a failed write leaves the main file and the backup exactly as they were.\n\t\t\t// The previous envelope is the one loadState recovered: main if valid, else the backup beside an\n\t\t\t// existing main. Retaining it keeps the recovery copy across a commit over a corrupt main.\n\t\t\tconst previous =\n\t\t\t\tthis.readEnvelope(statePath, namespace) ??\n\t\t\t\t(this.mainFileExists(statePath) ? this.readEnvelope(backupPath, namespace) : null);\n\t\t\t// Recreating a deleted state: drop a stale backup first, so a later corrupt main cannot recover the\n\t\t\t// old incarnation from it. If it cannot be removed, nothing is written.\n\t\t\tif (!previous && !this.mainFileExists(statePath)) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(backupPath);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteJsonAtomic(statePath, envelope, this.maxFileBytes);\n\t\t\t// The new state is durable now. The backup (previous state, re-serialized from the validated envelope\n\t\t\t// and written atomically so a planted symlink is replaced) is best-effort; with no previous state a\n\t\t\t// stale backup of an older incarnation is dropped so it cannot be recovered later.\n\t\t\ttry {\n\t\t\t\tif (previous) writeJsonAtomic(backupPath, previous, this.maxFileBytes);\n\t\t\t\telse unlinkSync(backupPath);\n\t\t\t} catch {\n\t\t\t\t// Recovery copy only; the commit stands.\n\t\t\t}\n\n\t\t\tconst state = { revision: envelope.revision, payload };\n\t\t\tthis.states.set(namespace, state);\n\t\t\treturn { committed: true, revision: envelope.revision };\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tcommitted: false,\n\t\t\t\trevision: currentRevision,\n\t\t\t\treason: `Failed to persist extension state: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\tpersistFailed: true,\n\t\t\t};\n\t\t}\n\t}\n\n\tgetCurrentRevision(namespace: string): number {\n\t\treturn this.loadState(namespace)?.revision ?? 0;\n\t}\n\n\t/**\n\t * Like `loadState`, but reads the disk (not the cache) and says where the state came from. `loadState` falls\n\t * back to a valid older `.bak` when the main file exists but is invalid; a caller for which an older state\n\t * is wrong (the integration state: it would roll back a fencing generation) uses this to tell the two apart.\n\t */\n\tloadStateDetailed(namespace: string): DetailedState {\n\t\tconst mainPath = this.statePath(namespace);\n\t\tconst main = this.readEnvelope(mainPath, namespace);\n\t\tif (main)\n\t\t\treturn { state: { revision: main.revision, payload: main.payload }, source: \"main\", mainInvalid: false };\n\t\tif (!this.mainFileExists(mainPath)) return { state: null, source: \"none\", mainInvalid: false };\n\t\tconst backup = this.readEnvelope(this.backupPath(namespace), namespace);\n\t\treturn {\n\t\t\tstate: backup ? { revision: backup.revision, payload: backup.payload } : null,\n\t\t\tsource: backup ? \"backup\" : \"none\",\n\t\t\tmainInvalid: true,\n\t\t};\n\t}\n\n\t/**\n\t * Every valid envelope whose stored namespace starts with `prefix`, sorted by namespace. A file is listed\n\t * only when its name equals the hash of its stored namespace and its payload hash verifies; an invalid main\n\t * file falls back to its .bak sibling, as loadState does. Reads disk, not the cache.\n\t */\n\tlistStates(prefix: string): ListedState[] {\n\t\tconst hashes = new Set<string>();\n\t\tfor (const name of readdirSync(this.stateDir)) {\n\t\t\tconst match = STATE_FILE_NAME.exec(name);\n\t\t\tif (match?.[1]) hashes.add(match[1]);\n\t\t}\n\t\tconst listed: ListedState[] = [];\n\t\tfor (const hash of hashes) {\n\t\t\tconst mainPath = join(this.stateDir, `${hash}.json`);\n\t\t\tif (!this.mainFileExists(mainPath)) continue;\n\t\t\tfor (const filePath of [mainPath, `${mainPath}.bak`]) {\n\t\t\t\tconst envelope = this.readEnvelope(filePath);\n\t\t\t\tif (!envelope || createHash(\"sha256\").update(envelope.namespace).digest(\"hex\") !== hash) continue;\n\t\t\t\tif (envelope.namespace.startsWith(prefix)) {\n\t\t\t\t\tlisted.push({\n\t\t\t\t\t\tnamespace: envelope.namespace,\n\t\t\t\t\t\trevision: envelope.revision,\n\t\t\t\t\t\tupdatedAt: envelope.updatedAt,\n\t\t\t\t\t\tpayload: envelope.payload,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn listed.sort((a, b) => (a.namespace < b.namespace ? -1 : a.namespace > b.namespace ? 1 : 0));\n\t}\n\n\t/** Removes the state file, its backup and the cache entry. Absent = true. Returns false on failure. */\n\tdeleteState(namespace: string): boolean {\n\t\t// Main first: on failure both files stay as they were. Once main is gone a leftover backup is inert\n\t\t// (loadState and listStates only read it beside an existing main file), so its removal is best-effort.\n\t\ttry {\n\t\t\tunlinkSync(this.statePath(namespace));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") return false;\n\t\t}\n\t\ttry {\n\t\t\tunlinkSync(this.backupPath(namespace));\n\t\t} catch {\n\t\t\t// Inert leftover.\n\t\t}\n\t\tthis.states.delete(namespace);\n\t\treturn true;\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framing.d.ts","sourceRoot":"","sources":["../../../src/coordination/transport/framing.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAElC,8EAA8E;AAC9E,eAAO,MAAM,eAAe,QAAc,CAAC;AAE3C;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAEtD;AAED;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAkB,CAAC;AAE9D,+CAA+C;AAC/C,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,EAAE,OAAO,GAAG,gBAAgB,GAAG,SAAS,CAAC,CAAC;AAEjF;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"framing.d.ts","sourceRoot":"","sources":["../../../src/coordination/transport/framing.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC;AAElC,8EAA8E;AAC9E,eAAO,MAAM,eAAe,QAAc,CAAC;AAE3C;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAEtD;AAED;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAkB,CAAC;AAE9D,+CAA+C;AAC/C,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,MAAM,EAAE,OAAO,GAAG,gBAAgB,GAAG,SAAS,CAAC,CAAC;AAEjF;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,CAStE;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAClC,SAAS,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,EACjC,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,EAC/B,aAAa,SAAkB,UA4BjB,MAAM,UA6DpB"}
|
|
@@ -22,7 +22,8 @@ export const MAX_SOCKET_WRITE_BACKLOG_BYTES = 8 * 1024 * 1024;
|
|
|
22
22
|
export function writeMessage(socket, msg) {
|
|
23
23
|
const json = JSON.stringify(msg);
|
|
24
24
|
const payloadLength = Buffer.byteLength(json, "utf-8");
|
|
25
|
-
|
|
25
|
+
// Unpooled frames do not pin an entire slab while a slow peer retains a small write.
|
|
26
|
+
const frame = Buffer.allocUnsafeSlow(4 + payloadLength);
|
|
26
27
|
frame.writeUInt32BE(payloadLength, 0);
|
|
27
28
|
frame.write(json, 4, payloadLength, "utf-8");
|
|
28
29
|
socket.write(frame);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framing.js","sourceRoot":"","sources":["../../../src/coordination/transport/framing.ts"],"names":[],"mappings":"AAGA,8EAA8E;AAC9E,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,GAAG,IAAI,CAAC;AAE3C;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAY;IAC7C,OAAO,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;AACxD,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAK9D;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAAC,MAAqB,EAAE,GAAY;IAC/D,MAAM,IAAI,GAAG,IAAI,CAAC,SA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,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;YAC7C,CAAC;YACD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,aAAa,GAAG,YAAY,EAAE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;YAC3E,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC,CAAC;YACzD,YAAY,IAAI,KAAK,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC;YAEhB,IAAI,YAAY,GAAG,aAAa,EAAE,CAAC;gBAClC,OAAO;YACR,CAAC;YAED,MAAM,YAAY,GAAG,OAAO,CAAC;YAC7B,WAAW,GAAG,CAAC,CAAC;YAChB,OAAO,GAAG,IAAI,CAAC;YACf,YAAY,GAAG,CAAC,CAAC;YACjB,aAAa,GAAG,CAAC,CAAC;YAClB,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE,CAAC;gBAClC,OAAO;YACR,CAAC;QACF,CAAC;IACF,CAAC,CAAC;AACH,CAAC","sourcesContent":["// Derived from pi-intercom (MIT, Copyright (c) 2026 Nico Bailon), commit ddf28818; modified for HUMAIN Code CLI.\nimport type { Socket } from \"net\";\n\n/** Largest JSON payload a frame may carry; readers reject anything bigger. */\nexport const MAX_FRAME_BYTES = 1024 * 1024;\n\n/**\n * Size in bytes of the JSON payload writeMessage would frame for `msg` (excluding the 4-byte length\n * prefix). Compare it with MAX_FRAME_BYTES before sending anything a peer's reader could refuse.\n */\nexport function framePayloadBytes(msg: unknown): number {\n\treturn Buffer.byteLength(JSON.stringify(msg), \"utf-8\");\n}\n\n/**\n * Most bytes a peer may leave unread in the socket's write queue. A consumer that lets more than this pile\n * up is not reading; it is destroyed instead of letting one slow peer grow the broker's memory without bound.\n */\nexport const MAX_SOCKET_WRITE_BACKLOG_BYTES = 8 * 1024 * 1024;\n\n/** The part of a socket writeMessage needs. */\nexport type MessageSocket = Pick<Socket, \"write\" | \"writableLength\" | \"destroy\">;\n\n/**\n * Write a length-prefixed message to a socket.\n * Format: 4-byte big-endian length + JSON payload\n *\n * Destroys the socket (a slow consumer) when more than MAX_SOCKET_WRITE_BACKLOG_BYTES are left queued after\n * the write. The socket emits its usual close event; no error is raised to the caller.\n */\nexport function writeMessage(socket: MessageSocket, msg: unknown): void {\n\tconst json = JSON.stringify(msg);\n\tconst payloadLength = Buffer.byteLength(json, \"utf-8\");\n\t// Unpooled frames do not pin an entire slab while a slow peer retains a small write.\n\tconst frame = Buffer.allocUnsafeSlow(4 + payloadLength);\n\tframe.writeUInt32BE(payloadLength, 0);\n\tframe.write(json, 4, payloadLength, \"utf-8\");\n\tsocket.write(frame);\n\tif (socket.writableLength > MAX_SOCKET_WRITE_BACKLOG_BYTES) socket.destroy();\n}\n\n/**\n * Create a message reader that handles partial reads.\n * Calls onMessage for each complete message received.\n * Protocol or handler errors are reported to onError so the caller can close the socket.\n */\nexport function createMessageReader(\n\tonMessage: (msg: unknown) => void,\n\tonError: (error: Error) => void,\n\tmaxFrameBytes = MAX_FRAME_BYTES,\n) {\n\tconst header = Buffer.allocUnsafe(4);\n\tlet headerBytes = 0;\n\tlet payload: Buffer | null = null;\n\tlet payloadBytes = 0;\n\tlet payloadLength = 0;\n\n\tfunction reportMessage(framePayload: Buffer): boolean {\n\t\tlet msg: unknown;\n\t\ttry {\n\t\t\tmsg = JSON.parse(framePayload.toString(\"utf-8\"));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tonError(new Error(`Failed to parse intercom message: ${message}`, { cause: error }));\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\tonMessage(msg);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tonError(new Error(`Failed to handle intercom message: ${message}`, { cause: error }));\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn (data: Buffer) => {\n\t\tlet offset = 0;\n\n\t\twhile (offset < data.length) {\n\t\t\tif (headerBytes < 4) {\n\t\t\t\tconst bytes = Math.min(4 - headerBytes, data.length - offset);\n\t\t\t\tdata.copy(header, headerBytes, offset, offset + bytes);\n\t\t\t\theaderBytes += bytes;\n\t\t\t\toffset += bytes;\n\t\t\t\tif (headerBytes < 4) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tpayloadLength = header.readUInt32BE(0);\n\t\t\t\tif (payloadLength > maxFrameBytes) {\n\t\t\t\t\theaderBytes = 0;\n\t\t\t\t\tonError(new Error(`Intercom frame length ${payloadLength} exceeds maximum ${maxFrameBytes} bytes`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Fast path: the whole payload is already in this chunk, so parse it\n\t\t\t// in place without copying into a reassembly buffer.\n\t\t\tif (payloadBytes === 0 && data.length - offset >= payloadLength) {\n\t\t\t\tconst framePayload = data.subarray(offset, offset + payloadLength);\n\t\t\t\toffset += payloadLength;\n\t\t\t\theaderBytes = 0;\n\t\t\t\tpayload = null;\n\t\t\t\tpayloadLength = 0;\n\t\t\t\tif (!reportMessage(framePayload)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// A buffer allocated for a previous frame (e.g. when a chunk ended\n\t\t\t// exactly on a header boundary) must not be reused for a frame of a\n\t\t\t// different size, so the reassembly buffer is size-checked, not just\n\t\t\t// presence-checked.\n\t\t\tif (payload === null || payload.length !== payloadLength) {\n\t\t\t\tpayload = Buffer.allocUnsafe(payloadLength);\n\t\t\t}\n\t\t\tconst bytes = Math.min(payloadLength - payloadBytes, data.length - offset);\n\t\t\tdata.copy(payload, payloadBytes, offset, offset + bytes);\n\t\t\tpayloadBytes += bytes;\n\t\t\toffset += bytes;\n\n\t\t\tif (payloadBytes < payloadLength) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst framePayload = payload;\n\t\t\theaderBytes = 0;\n\t\t\tpayload = null;\n\t\t\tpayloadBytes = 0;\n\t\t\tpayloadLength = 0;\n\t\t\tif (!reportMessage(framePayload)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t};\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { OAuthAccount } from "./oauth-account-pool.ts";
|
|
1
|
+
import type { OAuthAccount, OAuthAccountPool } from "./oauth-account-pool.ts";
|
|
2
2
|
/**
|
|
3
3
|
* Host-owned, consent-bound account reporting. Nothing here runs unless the host calls `refreshAccountUsage` after an
|
|
4
4
|
* explicit "Refresh usage" action. Listing accounts or opening Advanced never reaches this module.
|
|
@@ -98,6 +98,8 @@ export declare function formatAccountUsageReport(report: AccountUsageReport, now
|
|
|
98
98
|
export interface CodexUsageCollectorDeps {
|
|
99
99
|
/** Stored Codex account for a pool key. No OAuth refresh happens here: expired sign-ins are reported as expired. */
|
|
100
100
|
readAccount(accountKey: string, signal: AbortSignal): Promise<OAuthAccount | undefined>;
|
|
101
|
+
/** Clear only a matching saved cooldown when fresh provider usage explicitly permits it. */
|
|
102
|
+
accountPool?: OAuthAccountPool;
|
|
101
103
|
fetch?: typeof fetch;
|
|
102
104
|
now?: () => number;
|
|
103
105
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-reporting.d.ts","sourceRoot":"","sources":["../../src/core/account-reporting.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"account-reporting.d.ts","sourceRoot":"","sources":["../../src/core/account-reporting.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE9E;;;;;;GAMG;AAEH,eAAO,MAAM,0BAA0B,QAAS,CAAC;AACjD,eAAO,MAAM,iCAAiC,QAAS,CAAC;AACxD,eAAO,MAAM,2BAA2B,QAAS,CAAC;AAQlD,MAAM,WAAW,mBAAmB;IACnC,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,k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,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAoC1F;AAqBD,MAAM,WAAW,uBAAuB;IACvC,oHAAoH;IACpH,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CAAC;IACxF,4FAA4F;IAC5F,WAAW,CAAC,EAAE,gBAAgB,CAAC;IAC/B,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACnB;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,uBAAuB,GAAG,sBAAsB,CAgD/F"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CODEX_USAGE_PROVIDER_ID, fetchCodexWeeklyUsage } from "./codex-usage.js";
|
|
1
|
+
import { CODEX_USAGE_PROVIDER_ID, fetchCodexWeeklyUsage, getCodexAvailability, } from "./codex-usage.js";
|
|
2
2
|
/**
|
|
3
3
|
* Host-owned, consent-bound account reporting. Nothing here runs unless the host calls `refreshAccountUsage` after an
|
|
4
4
|
* explicit "Refresh usage" action. Listing accounts or opening Advanced never reaches this module.
|
|
@@ -300,6 +300,7 @@ export function createCodexUsageCollector(deps) {
|
|
|
300
300
|
const result = await fetchCodexWeeklyUsage(account, {
|
|
301
301
|
signal: AbortSignal.any([signal, AbortSignal.timeout(ACCOUNT_REPORT_REQUEST_TIMEOUT_MS)]),
|
|
302
302
|
fetch: deps.fetch,
|
|
303
|
+
accountPool: deps.accountPool,
|
|
303
304
|
now,
|
|
304
305
|
});
|
|
305
306
|
if (result.status === "unavailable") {
|
|
@@ -321,7 +322,16 @@ export function createCodexUsageCollector(deps) {
|
|
|
321
322
|
unit: "%",
|
|
322
323
|
...(result.usage.resetsAt === undefined ? {} : { resetsAt: new Date(result.usage.resetsAt).toISOString() }),
|
|
323
324
|
};
|
|
324
|
-
|
|
325
|
+
const notes = [
|
|
326
|
+
`Provider availability: ${getCodexAvailability(result.usage)} at ${new Date(now).toISOString()}`,
|
|
327
|
+
"not a check of every model",
|
|
328
|
+
];
|
|
329
|
+
const cooldown = new Date(account.exhaustedUntil ?? Number.NaN);
|
|
330
|
+
if (result.cooldownCleared)
|
|
331
|
+
notes.push("cached local cooldown cleared");
|
|
332
|
+
else if (cooldown.getTime() > now)
|
|
333
|
+
notes.push(`cached local cooldown until ${cooldown.toISOString()}`);
|
|
334
|
+
return { status: "ok", target, scope, updatedAt: now, metrics: [metric], reason: notes.join("; ") };
|
|
325
335
|
},
|
|
326
336
|
};
|
|
327
337
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-reporting.js","sourceRoot":"","sources":["../../src/core/account-reporting.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAoC,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAGpH;;;;;;GAMG;AAEH,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAC;AACjD,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAClD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,mHAAmH;AACnH,MAAM,kBAAkB,GAAG,0CAA0C,CAAC;AA+DtE,MAAM,UAAU,iBAAiB,CAChC,MAA2B,EAC3B,KAAyB,EACzB,MAAc,EACd,UAAmB;IAEnB,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AAC7G,CAAC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AI,MAAM,CAAC,MAAM,KAAK,kBAAkB,EAAE,CAAC;oBAC1C,OAAO;wBACN,MAAM,EAAE,OAAO;wBACf,MAAM;wBACN,KAAK;wBACL,SAAS,EAAE,GAAG;wBACd,OAAO,EAAE,EAAE;wBACX,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC;qBACpC,CAAC;gBACH,CAAC;gBACD,OAAO,iBAAiB,CAAC,MAAM,EAAE,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;YAC1G,CAAC;YACD,MAAM,MAAM,GAAuB;gBAClC,IAAI,EAAE,4BAA4B;gBAClC,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,gBAAgB;gBACpC,IAAI,EAAE,GAAG;gBACT,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC;aAC3G,CAAC;YACF,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;QAC3E,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { CODEX_USAGE_PROVIDER_ID, type CodexUsageUnavailableReason, fetchCodexWeeklyUsage } from \"./codex-usage.ts\";\nimport type { OAuthAccount } from \"./oauth-account-pool.ts\";\n\n/**\n * Host-owned, consent-bound account reporting. Nothing here runs unless the host calls `refreshAccountUsage` after an\n * explicit \"Refresh usage\" action. Listing accounts or opening Advanced never reaches this module.\n *\n * Reports never fabricate zero: unavailable, empty, partial and stale states keep their own labels, and every report\n * names its scope (source), target (account/source, region, UTC period) and last update time.\n */\n\nexport const ACCOUNT_REPORT_DEADLINE_MS = 30_000;\nexport const ACCOUNT_REPORT_REQUEST_TIMEOUT_MS = 10_000;\nexport const ACCOUNT_REPORT_CACHE_TTL_MS = 60_000;\nconst MAX_CACHE_ENTRIES = 64;\nconst MAX_ACCOUNT_KEY_LENGTH = 256;\nconst MAX_PROVIDER_ID_LENGTH = 128;\nconst MAX_LABEL_LENGTH = 64;\n// C0/C1 controls, DEL and Unicode line/paragraph separators: they would reach the terminal or cache keys verbatim.\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/;\n\nexport interface AccountReportPeriod {\n\t/** UTC, RFC 3339 with a `Z` suffix. */\n\tstart: string;\n\t/** UTC, RFC 3339 with a `Z` suffix. Exclusive. */\n\tend: string;\n}\n\nexport interface AccountReportTarget {\n\tproviderId: string;\n\t/** Opaque account identity. Never a credential. Empty only when `source` names a non-account reporting source. */\n\taccountKey: string;\n\t/** Explicit reporting source that is not an account (for example organization-wide reporting). */\n\tsource?: string;\n\t/** Region for providers whose figures are regional (for example Bedrock). */\n\tregion?: string;\n\tperiod: AccountReportPeriod;\n}\n\nexport type AccountReportStatus = \"ok\" | \"partial\" | \"empty\" | \"unavailable\";\n\n/** What a report measures. Distinct scopes are never merged or linked to each other. */\nexport type AccountReportScope =\n\t| \"openai-codex-oauth-usage\"\n\t| \"anthropic-api-rate-limits\"\n\t| \"anthropic-organization-usage\"\n\t| \"bedrock-cloudwatch\"\n\t| \"unsupported\";\n\nexport interface AccountUsageMetric {\n\tname: string;\n\tvalue: number;\n\tunit: string;\n\t/** UTC RFC 3339 time when the window this metric belongs to resets, when the source reports one. */\n\tresetsAt?: string;\n}\n\nexport interface AccountUsageReport {\n\tstatus: AccountReportStatus;\n\ttarget: AccountReportTarget;\n\tscope: AccountReportScope;\n\t/** Epoch ms of the observation: when the source answered, or when the observed response arrived. */\n\tupdatedAt?: number;\n\t/** Present metrics only. Missing data is never listed as zero. */\n\tmetrics: AccountUsageMetric[];\n\t/** Safe, fixed text. Never raw provider or transport errors. */\n\treason?: string;\n\t/** Specific next action for the user, when one exists. */\n\tnextAction?: string;\n\t/** True when the observation is older than the cache window or a later refresh failed. */\n\tstale?: boolean;\n}\n\nexport interface AccountReportCollector {\n\t/** Scope this collector reports for the target, used to label unavailable states too. */\n\tscopeFor(target: AccountReportTarget): AccountReportScope;\n\t/** Collect one report. Must honour the signal and return only safe reasons. */\n\tcollect(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport>;\n\t/** Return false for targets whose `collect` only reads local state, so every refresh sees the newest observation. */\n\tcachesTarget?(target: AccountReportTarget): boolean;\n}\n\nexport function unavailableReport(\n\ttarget: AccountReportTarget,\n\tscope: AccountReportScope,\n\treason: string,\n\tnextAction?: string,\n): AccountUsageReport {\n\treturn { status: \"unavailable\", target, scope, metrics: [], reason, ...(nextAction ? { nextAction } : {}) };\n}\n\nconst UTC_INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,9})?Z$/;\n\nfunction utcInstantMs(value: unknown): number | undefined {\n\tif (typeof value !== \"string\" || !UTC_INSTANT.test(value)) return undefined;\n\tconst ms = Date.parse(value);\n\treturn Number.isFinite(ms) ? ms : undefined;\n}\n\nfunction validText(value: unknown, minLength: number, maxLength: number): boolean {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length >= minLength &&\n\t\tvalue.length <= maxLength &&\n\t\t!CONTROL_CHARACTERS.test(value)\n\t);\n}\n\nfunction targetProblem(target: AccountReportTarget): string | undefined {\n\tif (!validText(target.providerId, 1, MAX_PROVIDER_ID_LENGTH)) return \"invalid report target\";\n\tif (target.source !== undefined && !validText(target.source, 1, MAX_LABEL_LENGTH)) return \"invalid report target\";\n\tif (!validText(target.accountKey, target.source === undefined ? 1 : 0, MAX_ACCOUNT_KEY_LENGTH)) {\n\t\treturn \"invalid report target\";\n\t}\n\tif (target.region !== undefined && !validText(target.region, 1, MAX_LABEL_LENGTH)) return \"invalid report target\";\n\tconst start = utcInstantMs(target.period?.start);\n\tconst end = utcInstantMs(target.period?.end);\n\tif (start === undefined || end === undefined || start >= end) return \"invalid reporting period\";\n\treturn undefined;\n}\n\n/** A target that failed validation, made safe to echo into a report: no control characters, bounded length. */\nfunction sanitizedTarget(target: AccountReportTarget): AccountReportTarget {\n\tconst clean = (value: unknown, max: number): string =>\n\t\ttypeof value === \"string\" ? value.replace(new RegExp(CONTROL_CHARACTERS, \"g\"), \"?\").slice(0, max) : \"\";\n\treturn {\n\t\tproviderId: clean(target?.providerId, MAX_PROVIDER_ID_LENGTH),\n\t\taccountKey: clean(target?.accountKey, MAX_ACCOUNT_KEY_LENGTH),\n\t\t...(typeof target?.source === \"string\" ? { source: clean(target.source, MAX_LABEL_LENGTH) } : {}),\n\t\t...(typeof target?.region === \"string\" ? { region: clean(target.region, MAX_LABEL_LENGTH) } : {}),\n\t\tperiod: { start: clean(target?.period?.start, 40), end: clean(target?.period?.end, 40) },\n\t};\n}\n\nfunction cacheKey(target: AccountReportTarget): string {\n\treturn JSON.stringify([\n\t\ttarget.providerId,\n\t\ttarget.accountKey,\n\t\ttarget.source ?? null,\n\t\ttarget.region ?? null,\n\t\ttarget.period.start,\n\t\ttarget.period.end,\n\t]);\n}\n\ninterface CacheEntry {\n\treport: AccountUsageReport;\n\tfetchedAt: number;\n}\n\ninterface InFlight {\n\t/** Aborts the shared collection: on supersession, `cancelAll`, or when every attached caller has aborted. */\n\tcontroller: AbortController;\n\tkey: string;\n\tpromise: Promise<AccountUsageReport>;\n\tcallers: number;\n}\n\nexport interface AccountReporterOptions {\n\t/** Collectors by provider ID. Providers without one report \"unsupported\". */\n\tcollectors: Readonly<Record<string, AccountReportCollector>>;\n\t/** Injected clock (epoch ms). Defaults to Date.now. */\n\tnow?: () => number;\n\tdeadlineMs?: number;\n\tcacheTtlMs?: number;\n}\n\n/**\n * Session-bound reporter. Late results of a superseded or cancelled refresh are discarded and never cached; caches are\n * isolated by provider, account/source, region and period.\n */\nexport class AccountReporter {\n\tprivate readonly collectors: Readonly<Record<string, AccountReportCollector>>;\n\tprivate readonly now: () => number;\n\tprivate readonly deadlineMs: number;\n\tprivate readonly ttlMs: number;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\t/** One in-flight refresh per provider and scope (and explicit source): a different target there supersedes it. */\n\tprivate readonly inFlight = new Map<string, InFlight>();\n\n\tconstructor(options: AccountReporterOptions) {\n\t\tthis.collectors = options.collectors;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.deadlineMs = options.deadlineMs ?? ACCOUNT_REPORT_DEADLINE_MS;\n\t\tthis.ttlMs = options.cacheTtlMs ?? ACCOUNT_REPORT_CACHE_TTL_MS;\n\t}\n\n\t/** Cancel every in-flight refresh (session, account or dialog change). Their results are discarded. */\n\tcancelAll(): void {\n\t\tfor (const entry of this.inFlight.values()) entry.controller.abort();\n\t\tthis.inFlight.clear();\n\t}\n\n\trefreshAccountUsage(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport> {\n\t\tconst problem = targetProblem(target);\n\t\tif (problem) return Promise.resolve(unavailableReport(sanitizedTarget(target), \"unsupported\", problem));\n\t\tconst collector = Object.hasOwn(this.collectors, target.providerId)\n\t\t\t? this.collectors[target.providerId]\n\t\t\t: undefined;\n\t\tif (!collector) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tunavailableReport(target, \"unsupported\", `usage reporting is not supported for ${target.providerId}`),\n\t\t\t);\n\t\t}\n\t\tconst key = cacheKey(target);\n\t\tconst useCache = collector.cachesTarget?.(target) !== false;\n\t\tconst cached = useCache ? this.cache.get(key) : undefined;\n\t\tif (cached && this.now() - cached.fetchedAt < this.ttlMs) return Promise.resolve(this.label(cached.report));\n\t\tconst scope = collector.scopeFor(target);\n\t\t// Different scopes of one provider (for example organization reporting and selected-key limits) run independently.\n\t\tconst slot = JSON.stringify([target.providerId, scope, target.source ?? null]);\n\t\tlet running = this.inFlight.get(slot);\n\t\tif (running && (running.key !== key || running.controller.signal.aborted)) {\n\t\t\trunning.controller.abort();\n\t\t\trunning = undefined;\n\t\t}\n\t\tif (!running) {\n\t\t\trunning = this.start(slot, key, useCache, target, scope, collector);\n\t\t\tthis.inFlight.set(slot, running);\n\t\t}\n\t\treturn this.attach(running, signal, target, scope);\n\t}\n\n\tprivate start(\n\t\tslot: string,\n\t\tkey: string,\n\t\tuseCache: boolean,\n\t\ttarget: AccountReportTarget,\n\t\tscope: AccountReportScope,\n\t\tcollector: AccountReportCollector,\n\t): InFlight {\n\t\tconst controller = new AbortController();\n\t\tconst combined = AbortSignal.any([controller.signal, AbortSignal.timeout(this.deadlineMs)]);\n\t\tconst promise = (async (): Promise<AccountUsageReport> => {\n\t\t\tlet report: AccountUsageReport | undefined;\n\t\t\ttry {\n\t\t\t\treport = await collector.collect(target, combined);\n\t\t\t} catch {\n\t\t\t\t// Collector failures can carry URLs or credentials: report only a fixed category.\n\t\t\t\treport = unavailableReport(target, scope, \"the usage lookup failed\");\n\t\t\t}\n\t\t\tif (controller.signal.aborted) return unavailableReport(target, scope, \"the usage refresh was cancelled\");\n\t\t\tif (combined.aborted) {\n\t\t\t\t// Deadline: keep pages already gathered, labelled partial and never cached so the next refresh retries.\n\t\t\t\tif ((report.status === \"ok\" || report.status === \"partial\") && report.metrics.length > 0) {\n\t\t\t\t\treturn this.label({\n\t\t\t\t\t\t...report,\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\tstatus: \"partial\",\n\t\t\t\t\t\treason: \"the usage refresh timed out before all data was retrieved\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn unavailableReport(target, scope, \"the usage refresh timed out\");\n\t\t\t}\n\t\t\treturn this.settle(key, useCache, target, report);\n\t\t})().finally(() => {\n\t\t\tif (this.inFlight.get(slot)?.controller === controller) this.inFlight.delete(slot);\n\t\t});\n\t\treturn { controller, key, promise, callers: 0 };\n\t}\n\n\t/**\n\t * Each caller cancels independently: the shared collection is aborted only once every attached caller has aborted.\n\t * An aborted caller gets its own cancelled report while others still receive the shared result.\n\t */\n\tprivate attach(\n\t\tentry: InFlight,\n\t\tsignal: AbortSignal,\n\t\ttarget: AccountReportTarget,\n\t\tscope: AccountReportScope,\n\t): Promise<AccountUsageReport> {\n\t\tentry.callers++;\n\t\treturn new Promise((resolve) => {\n\t\t\tlet attached = true;\n\t\t\tconst detach = (): void => {\n\t\t\t\tif (!attached) return;\n\t\t\t\tattached = false;\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (!attached) return;\n\t\t\t\tdetach();\n\t\t\t\tif (--entry.callers === 0) entry.controller.abort();\n\t\t\t\tresolve(unavailableReport(target, scope, \"the usage refresh was cancelled\"));\n\t\t\t};\n\t\t\tif (signal.aborted) return onAbort();\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tvoid entry.promise.then((report) => {\n\t\t\t\tif (!attached) return;\n\t\t\t\tdetach();\n\t\t\t\tresolve(report);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate settle(\n\t\tkey: string,\n\t\tuseCache: boolean,\n\t\ttarget: AccountReportTarget,\n\t\treport: AccountUsageReport,\n\t): AccountUsageReport {\n\t\tconst bound: AccountUsageReport = { ...report, target };\n\t\tif (bound.status === \"unavailable\") {\n\t\t\tconst previous = useCache ? this.cache.get(key)?.report : undefined;\n\t\t\tif (previous && previous.status !== \"unavailable\") {\n\t\t\t\t// Keep the last real observation with its own time and label it stale instead of dropping it.\n\t\t\t\treturn {\n\t\t\t\t\t...previous,\n\t\t\t\t\tstale: true,\n\t\t\t\t\treason: `the latest refresh failed: ${bound.reason ?? \"unavailable\"}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn bound;\n\t\t}\n\t\tif (useCache) {\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, { report: bound, fetchedAt: this.now() });\n\t\t\twhile (this.cache.size > MAX_CACHE_ENTRIES) this.cache.delete(this.cache.keys().next().value as string);\n\t\t}\n\t\treturn this.label(bound);\n\t}\n\n\t/** Mark observations older than the cache window stale; never alters the metrics or times. */\n\tprivate label(report: AccountUsageReport): AccountUsageReport {\n\t\tif (report.stale || report.status === \"unavailable\" || report.updatedAt === undefined) return report;\n\t\treturn this.now() - report.updatedAt > this.ttlMs ? { ...report, stale: true } : report;\n\t}\n}\n\nconst SCOPE_LABELS: Record<AccountReportScope, string> = {\n\t\"openai-codex-oauth-usage\": \"OpenAI Codex sign-in usage (weekly window reported by the Codex usage service)\",\n\t\"anthropic-api-rate-limits\":\n\t\t\"Anthropic API rate-limit windows from the last API response (not a Claude subscription allowance)\",\n\t\"anthropic-organization-usage\":\n\t\t\"Anthropic organization usage report (Admin API reporting credentials; not linked to any ordinary API key)\",\n\t\"bedrock-cloudwatch\": \"Amazon Bedrock CloudWatch metrics (AWS/Bedrock; not a billing invoice or remaining quota)\",\n\tunsupported: \"Usage reporting\",\n};\n\nfunction formatNumber(value: number): string {\n\treturn Number.isInteger(value) ? String(value) : String(Number(value.toFixed(4)));\n}\n\n/** Render a report for Advanced. Always names source/scope, account, period, region and update time. */\nexport function formatAccountUsageReport(report: AccountUsageReport, now: number): string[] {\n\tconst { target } = report;\n\tconst lines = [`${SCOPE_LABELS[report.scope]} — account/source [${target.accountKey || target.source}]`];\n\tconst place = [\n\t\t`Period ${target.period.start} to ${target.period.end} (UTC).`,\n\t\ttarget.region ? `Region ${target.region}.` : undefined,\n\t\treport.updatedAt === undefined ? \"Not updated.\" : `Updated ${new Date(report.updatedAt).toISOString()}.`,\n\t].filter(Boolean);\n\tlines.push(place.join(\" \"));\n\tif (report.status === \"unavailable\") {\n\t\tconst detail = report.reason ?? \"no reason was reported\";\n\t\tlines.push(`Account usage is unavailable: ${detail}.${report.nextAction ? ` ${report.nextAction}` : \"\"}`);\n\t\treturn lines;\n\t}\n\tif (report.stale) {\n\t\tconst age =\n\t\t\treport.updatedAt === undefined\n\t\t\t\t? \"\"\n\t\t\t\t: ` ${Math.max(0, Math.round((now - report.updatedAt) / 1000))} seconds ago`;\n\t\tlines.push(`Stale: last observed${age || \" at an unknown time\"}; refresh to update.`);\n\t}\n\tif (report.status === \"empty\") {\n\t\tlines.push(\"No usage was reported for this period. This is not a zero count.\");\n\t} else {\n\t\tif (report.status === \"partial\") {\n\t\t\tlines.push(`Partial results: ${report.reason ?? \"some data was missing\"}. Totals may be incomplete.`);\n\t\t} else if (report.reason) {\n\t\t\tlines.push(`Note: ${report.reason}.`);\n\t\t}\n\t\tfor (const metric of report.metrics) {\n\t\t\tlines.push(\n\t\t\t\t`${metric.name}: ${formatNumber(metric.value)} ${metric.unit}${metric.resetsAt ? ` (resets ${metric.resetsAt})` : \"\"}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst CODEX_REASONS: Record<CodexUsageUnavailableReason, string> = {\n\texpired_credential: \"the Codex sign-in has expired\",\n\tunauthorized: \"the Codex usage service rejected the sign-in\",\n\trate_limited: \"the Codex usage service is rate limiting requests\",\n\thttp_error: \"the Codex usage service returned an error\",\n\ttimeout: \"the Codex usage request timed out\",\n\tnetwork: \"the Codex usage service is unreachable\",\n\tmalformed: \"the Codex usage response was not recognised\",\n\tno_weekly_window: \"the Codex usage service reported no weekly window\",\n};\n\nconst CODEX_NEXT_ACTIONS: Partial<Record<CodexUsageUnavailableReason, string>> = {\n\texpired_credential: \"Sign in to OpenAI Codex again, then refresh usage.\",\n\tunauthorized: \"Sign in to OpenAI Codex again, then refresh usage.\",\n\trate_limited: \"Wait a minute, then refresh usage.\",\n\ttimeout: \"Check the connection, then refresh usage.\",\n\tnetwork: \"Check the connection, then refresh usage.\",\n};\n\nexport interface CodexUsageCollectorDeps {\n\t/** Stored Codex account for a pool key. No OAuth refresh happens here: expired sign-ins are reported as expired. */\n\treadAccount(accountKey: string, signal: AbortSignal): Promise<OAuthAccount | undefined>;\n\tfetch?: typeof fetch;\n\tnow?: () => number;\n}\n\n/**\n * Reuses the existing Codex weekly usage fetcher for one `openai-codex` OAuth account. `openai` API-key accounts are a\n * different provider and have no collector here: their usage is never inferred from Codex sign-ins.\n */\nexport function createCodexUsageCollector(deps: CodexUsageCollectorDeps): AccountReportCollector {\n\tconst scope = \"openai-codex-oauth-usage\" as const;\n\treturn {\n\t\tscopeFor: () => scope,\n\t\tasync collect(target, signal) {\n\t\t\tif (target.providerId !== CODEX_USAGE_PROVIDER_ID) {\n\t\t\t\treturn unavailableReport(target, scope, \"not an OpenAI Codex sign-in\");\n\t\t\t}\n\t\t\tconst account = await deps.readAccount(target.accountKey, signal);\n\t\t\tif (!account) {\n\t\t\t\treturn unavailableReport(target, scope, \"the Codex sign-in is no longer stored\", \"Reconnect OpenAI Codex.\");\n\t\t\t}\n\t\t\tconst now = deps.now?.() ?? Date.now();\n\t\t\tconst result = await fetchCodexWeeklyUsage(account, {\n\t\t\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(ACCOUNT_REPORT_REQUEST_TIMEOUT_MS)]),\n\t\t\t\tfetch: deps.fetch,\n\t\t\t\tnow,\n\t\t\t});\n\t\t\tif (result.status === \"unavailable\") {\n\t\t\t\tif (result.reason === \"no_weekly_window\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"empty\",\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\t\tmetrics: [],\n\t\t\t\t\t\treason: CODEX_REASONS[result.reason],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn unavailableReport(target, scope, CODEX_REASONS[result.reason], CODEX_NEXT_ACTIONS[result.reason]);\n\t\t\t}\n\t\t\tconst metric: AccountUsageMetric = {\n\t\t\t\tname: \"Weekly allowance remaining\",\n\t\t\t\tvalue: result.usage.remainingPercent,\n\t\t\t\tunit: \"%\",\n\t\t\t\t...(result.usage.resetsAt === undefined ? {} : { resetsAt: new Date(result.usage.resetsAt).toISOString() }),\n\t\t\t};\n\t\t\treturn { status: \"ok\", target, scope, updatedAt: now, metrics: [metric] };\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"account-reporting.js","sourceRoot":"","sources":["../../src/core/account-reporting.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,uBAAuB,EAEvB,qBAAqB,EACrB,oBAAoB,GACpB,MAAM,kBAAkB,CAAC;AAG1B;;;;;;GAMG;AAEH,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAC;AACjD,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAClD,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAC7B,MAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,MAAM,sBAAsB,GAAG,GAAG,CAAC;AACnC,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,mHAAmH;AACnH,MAAM,kBAAkB,GAAG,0CAA0C,CAAC;AA+DtE,MAAM,UAAU,iBAAiB,CAChC,MAA2B,EAC3B,KAAyB,EACzB,MAAc,EACd,UAAmB;IAEnB,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AAC7G,CAAC;AAED,MAAM,WAAW,GAAG,oDAAoD,CAAC;AAEzE,SAAS,YAAY,CAAC,KAAc;IACnC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5E,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC7B,OAAO,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,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chCodexWeeklyUsage,\n\tgetCodexAvailability,\n} from \"./codex-usage.ts\";\nimport type { OAuthAccount, OAuthAccountPool } from \"./oauth-account-pool.ts\";\n\n/**\n * Host-owned, consent-bound account reporting. Nothing here runs unless the host calls `refreshAccountUsage` after an\n * explicit \"Refresh usage\" action. Listing accounts or opening Advanced never reaches this module.\n *\n * Reports never fabricate zero: unavailable, empty, partial and stale states keep their own labels, and every report\n * names its scope (source), target (account/source, region, UTC period) and last update time.\n */\n\nexport const ACCOUNT_REPORT_DEADLINE_MS = 30_000;\nexport const ACCOUNT_REPORT_REQUEST_TIMEOUT_MS = 10_000;\nexport const ACCOUNT_REPORT_CACHE_TTL_MS = 60_000;\nconst MAX_CACHE_ENTRIES = 64;\nconst MAX_ACCOUNT_KEY_LENGTH = 256;\nconst MAX_PROVIDER_ID_LENGTH = 128;\nconst MAX_LABEL_LENGTH = 64;\n// C0/C1 controls, DEL and Unicode line/paragraph separators: they would reach the terminal or cache keys verbatim.\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/;\n\nexport interface AccountReportPeriod {\n\t/** UTC, RFC 3339 with a `Z` suffix. */\n\tstart: string;\n\t/** UTC, RFC 3339 with a `Z` suffix. Exclusive. */\n\tend: string;\n}\n\nexport interface AccountReportTarget {\n\tproviderId: string;\n\t/** Opaque account identity. Never a credential. Empty only when `source` names a non-account reporting source. */\n\taccountKey: string;\n\t/** Explicit reporting source that is not an account (for example organization-wide reporting). */\n\tsource?: string;\n\t/** Region for providers whose figures are regional (for example Bedrock). */\n\tregion?: string;\n\tperiod: AccountReportPeriod;\n}\n\nexport type AccountReportStatus = \"ok\" | \"partial\" | \"empty\" | \"unavailable\";\n\n/** What a report measures. Distinct scopes are never merged or linked to each other. */\nexport type AccountReportScope =\n\t| \"openai-codex-oauth-usage\"\n\t| \"anthropic-api-rate-limits\"\n\t| \"anthropic-organization-usage\"\n\t| \"bedrock-cloudwatch\"\n\t| \"unsupported\";\n\nexport interface AccountUsageMetric {\n\tname: string;\n\tvalue: number;\n\tunit: string;\n\t/** UTC RFC 3339 time when the window this metric belongs to resets, when the source reports one. */\n\tresetsAt?: string;\n}\n\nexport interface AccountUsageReport {\n\tstatus: AccountReportStatus;\n\ttarget: AccountReportTarget;\n\tscope: AccountReportScope;\n\t/** Epoch ms of the observation: when the source answered, or when the observed response arrived. */\n\tupdatedAt?: number;\n\t/** Present metrics only. Missing data is never listed as zero. */\n\tmetrics: AccountUsageMetric[];\n\t/** Safe, fixed text. Never raw provider or transport errors. */\n\treason?: string;\n\t/** Specific next action for the user, when one exists. */\n\tnextAction?: string;\n\t/** True when the observation is older than the cache window or a later refresh failed. */\n\tstale?: boolean;\n}\n\nexport interface AccountReportCollector {\n\t/** Scope this collector reports for the target, used to label unavailable states too. */\n\tscopeFor(target: AccountReportTarget): AccountReportScope;\n\t/** Collect one report. Must honour the signal and return only safe reasons. */\n\tcollect(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport>;\n\t/** Return false for targets whose `collect` only reads local state, so every refresh sees the newest observation. */\n\tcachesTarget?(target: AccountReportTarget): boolean;\n}\n\nexport function unavailableReport(\n\ttarget: AccountReportTarget,\n\tscope: AccountReportScope,\n\treason: string,\n\tnextAction?: string,\n): AccountUsageReport {\n\treturn { status: \"unavailable\", target, scope, metrics: [], reason, ...(nextAction ? { nextAction } : {}) };\n}\n\nconst UTC_INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,9})?Z$/;\n\nfunction utcInstantMs(value: unknown): number | undefined {\n\tif (typeof value !== \"string\" || !UTC_INSTANT.test(value)) return undefined;\n\tconst ms = Date.parse(value);\n\treturn Number.isFinite(ms) ? ms : undefined;\n}\n\nfunction validText(value: unknown, minLength: number, maxLength: number): boolean {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length >= minLength &&\n\t\tvalue.length <= maxLength &&\n\t\t!CONTROL_CHARACTERS.test(value)\n\t);\n}\n\nfunction targetProblem(target: AccountReportTarget): string | undefined {\n\tif (!validText(target.providerId, 1, MAX_PROVIDER_ID_LENGTH)) return \"invalid report target\";\n\tif (target.source !== undefined && !validText(target.source, 1, MAX_LABEL_LENGTH)) return \"invalid report target\";\n\tif (!validText(target.accountKey, target.source === undefined ? 1 : 0, MAX_ACCOUNT_KEY_LENGTH)) {\n\t\treturn \"invalid report target\";\n\t}\n\tif (target.region !== undefined && !validText(target.region, 1, MAX_LABEL_LENGTH)) return \"invalid report target\";\n\tconst start = utcInstantMs(target.period?.start);\n\tconst end = utcInstantMs(target.period?.end);\n\tif (start === undefined || end === undefined || start >= end) return \"invalid reporting period\";\n\treturn undefined;\n}\n\n/** A target that failed validation, made safe to echo into a report: no control characters, bounded length. */\nfunction sanitizedTarget(target: AccountReportTarget): AccountReportTarget {\n\tconst clean = (value: unknown, max: number): string =>\n\t\ttypeof value === \"string\" ? value.replace(new RegExp(CONTROL_CHARACTERS, \"g\"), \"?\").slice(0, max) : \"\";\n\treturn {\n\t\tproviderId: clean(target?.providerId, MAX_PROVIDER_ID_LENGTH),\n\t\taccountKey: clean(target?.accountKey, MAX_ACCOUNT_KEY_LENGTH),\n\t\t...(typeof target?.source === \"string\" ? { source: clean(target.source, MAX_LABEL_LENGTH) } : {}),\n\t\t...(typeof target?.region === \"string\" ? { region: clean(target.region, MAX_LABEL_LENGTH) } : {}),\n\t\tperiod: { start: clean(target?.period?.start, 40), end: clean(target?.period?.end, 40) },\n\t};\n}\n\nfunction cacheKey(target: AccountReportTarget): string {\n\treturn JSON.stringify([\n\t\ttarget.providerId,\n\t\ttarget.accountKey,\n\t\ttarget.source ?? null,\n\t\ttarget.region ?? null,\n\t\ttarget.period.start,\n\t\ttarget.period.end,\n\t]);\n}\n\ninterface CacheEntry {\n\treport: AccountUsageReport;\n\tfetchedAt: number;\n}\n\ninterface InFlight {\n\t/** Aborts the shared collection: on supersession, `cancelAll`, or when every attached caller has aborted. */\n\tcontroller: AbortController;\n\tkey: string;\n\tpromise: Promise<AccountUsageReport>;\n\tcallers: number;\n}\n\nexport interface AccountReporterOptions {\n\t/** Collectors by provider ID. Providers without one report \"unsupported\". */\n\tcollectors: Readonly<Record<string, AccountReportCollector>>;\n\t/** Injected clock (epoch ms). Defaults to Date.now. */\n\tnow?: () => number;\n\tdeadlineMs?: number;\n\tcacheTtlMs?: number;\n}\n\n/**\n * Session-bound reporter. Late results of a superseded or cancelled refresh are discarded and never cached; caches are\n * isolated by provider, account/source, region and period.\n */\nexport class AccountReporter {\n\tprivate readonly collectors: Readonly<Record<string, AccountReportCollector>>;\n\tprivate readonly now: () => number;\n\tprivate readonly deadlineMs: number;\n\tprivate readonly ttlMs: number;\n\tprivate readonly cache = new Map<string, CacheEntry>();\n\t/** One in-flight refresh per provider and scope (and explicit source): a different target there supersedes it. */\n\tprivate readonly inFlight = new Map<string, InFlight>();\n\n\tconstructor(options: AccountReporterOptions) {\n\t\tthis.collectors = options.collectors;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.deadlineMs = options.deadlineMs ?? ACCOUNT_REPORT_DEADLINE_MS;\n\t\tthis.ttlMs = options.cacheTtlMs ?? ACCOUNT_REPORT_CACHE_TTL_MS;\n\t}\n\n\t/** Cancel every in-flight refresh (session, account or dialog change). Their results are discarded. */\n\tcancelAll(): void {\n\t\tfor (const entry of this.inFlight.values()) entry.controller.abort();\n\t\tthis.inFlight.clear();\n\t}\n\n\trefreshAccountUsage(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport> {\n\t\tconst problem = targetProblem(target);\n\t\tif (problem) return Promise.resolve(unavailableReport(sanitizedTarget(target), \"unsupported\", problem));\n\t\tconst collector = Object.hasOwn(this.collectors, target.providerId)\n\t\t\t? this.collectors[target.providerId]\n\t\t\t: undefined;\n\t\tif (!collector) {\n\t\t\treturn Promise.resolve(\n\t\t\t\tunavailableReport(target, \"unsupported\", `usage reporting is not supported for ${target.providerId}`),\n\t\t\t);\n\t\t}\n\t\tconst key = cacheKey(target);\n\t\tconst useCache = collector.cachesTarget?.(target) !== false;\n\t\tconst cached = useCache ? this.cache.get(key) : undefined;\n\t\tif (cached && this.now() - cached.fetchedAt < this.ttlMs) return Promise.resolve(this.label(cached.report));\n\t\tconst scope = collector.scopeFor(target);\n\t\t// Different scopes of one provider (for example organization reporting and selected-key limits) run independently.\n\t\tconst slot = JSON.stringify([target.providerId, scope, target.source ?? null]);\n\t\tlet running = this.inFlight.get(slot);\n\t\tif (running && (running.key !== key || running.controller.signal.aborted)) {\n\t\t\trunning.controller.abort();\n\t\t\trunning = undefined;\n\t\t}\n\t\tif (!running) {\n\t\t\trunning = this.start(slot, key, useCache, target, scope, collector);\n\t\t\tthis.inFlight.set(slot, running);\n\t\t}\n\t\treturn this.attach(running, signal, target, scope);\n\t}\n\n\tprivate start(\n\t\tslot: string,\n\t\tkey: string,\n\t\tuseCache: boolean,\n\t\ttarget: AccountReportTarget,\n\t\tscope: AccountReportScope,\n\t\tcollector: AccountReportCollector,\n\t): InFlight {\n\t\tconst controller = new AbortController();\n\t\tconst combined = AbortSignal.any([controller.signal, AbortSignal.timeout(this.deadlineMs)]);\n\t\tconst promise = (async (): Promise<AccountUsageReport> => {\n\t\t\tlet report: AccountUsageReport | undefined;\n\t\t\ttry {\n\t\t\t\treport = await collector.collect(target, combined);\n\t\t\t} catch {\n\t\t\t\t// Collector failures can carry URLs or credentials: report only a fixed category.\n\t\t\t\treport = unavailableReport(target, scope, \"the usage lookup failed\");\n\t\t\t}\n\t\t\tif (controller.signal.aborted) return unavailableReport(target, scope, \"the usage refresh was cancelled\");\n\t\t\tif (combined.aborted) {\n\t\t\t\t// Deadline: keep pages already gathered, labelled partial and never cached so the next refresh retries.\n\t\t\t\tif ((report.status === \"ok\" || report.status === \"partial\") && report.metrics.length > 0) {\n\t\t\t\t\treturn this.label({\n\t\t\t\t\t\t...report,\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\tstatus: \"partial\",\n\t\t\t\t\t\treason: \"the usage refresh timed out before all data was retrieved\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn unavailableReport(target, scope, \"the usage refresh timed out\");\n\t\t\t}\n\t\t\treturn this.settle(key, useCache, target, report);\n\t\t})().finally(() => {\n\t\t\tif (this.inFlight.get(slot)?.controller === controller) this.inFlight.delete(slot);\n\t\t});\n\t\treturn { controller, key, promise, callers: 0 };\n\t}\n\n\t/**\n\t * Each caller cancels independently: the shared collection is aborted only once every attached caller has aborted.\n\t * An aborted caller gets its own cancelled report while others still receive the shared result.\n\t */\n\tprivate attach(\n\t\tentry: InFlight,\n\t\tsignal: AbortSignal,\n\t\ttarget: AccountReportTarget,\n\t\tscope: AccountReportScope,\n\t): Promise<AccountUsageReport> {\n\t\tentry.callers++;\n\t\treturn new Promise((resolve) => {\n\t\t\tlet attached = true;\n\t\t\tconst detach = (): void => {\n\t\t\t\tif (!attached) return;\n\t\t\t\tattached = false;\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tif (!attached) return;\n\t\t\t\tdetach();\n\t\t\t\tif (--entry.callers === 0) entry.controller.abort();\n\t\t\t\tresolve(unavailableReport(target, scope, \"the usage refresh was cancelled\"));\n\t\t\t};\n\t\t\tif (signal.aborted) return onAbort();\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tvoid entry.promise.then((report) => {\n\t\t\t\tif (!attached) return;\n\t\t\t\tdetach();\n\t\t\t\tresolve(report);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate settle(\n\t\tkey: string,\n\t\tuseCache: boolean,\n\t\ttarget: AccountReportTarget,\n\t\treport: AccountUsageReport,\n\t): AccountUsageReport {\n\t\tconst bound: AccountUsageReport = { ...report, target };\n\t\tif (bound.status === \"unavailable\") {\n\t\t\tconst previous = useCache ? this.cache.get(key)?.report : undefined;\n\t\t\tif (previous && previous.status !== \"unavailable\") {\n\t\t\t\t// Keep the last real observation with its own time and label it stale instead of dropping it.\n\t\t\t\treturn {\n\t\t\t\t\t...previous,\n\t\t\t\t\tstale: true,\n\t\t\t\t\treason: `the latest refresh failed: ${bound.reason ?? \"unavailable\"}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn bound;\n\t\t}\n\t\tif (useCache) {\n\t\t\tthis.cache.delete(key);\n\t\t\tthis.cache.set(key, { report: bound, fetchedAt: this.now() });\n\t\t\twhile (this.cache.size > MAX_CACHE_ENTRIES) this.cache.delete(this.cache.keys().next().value as string);\n\t\t}\n\t\treturn this.label(bound);\n\t}\n\n\t/** Mark observations older than the cache window stale; never alters the metrics or times. */\n\tprivate label(report: AccountUsageReport): AccountUsageReport {\n\t\tif (report.stale || report.status === \"unavailable\" || report.updatedAt === undefined) return report;\n\t\treturn this.now() - report.updatedAt > this.ttlMs ? { ...report, stale: true } : report;\n\t}\n}\n\nconst SCOPE_LABELS: Record<AccountReportScope, string> = {\n\t\"openai-codex-oauth-usage\": \"OpenAI Codex sign-in usage (weekly window reported by the Codex usage service)\",\n\t\"anthropic-api-rate-limits\":\n\t\t\"Anthropic API rate-limit windows from the last API response (not a Claude subscription allowance)\",\n\t\"anthropic-organization-usage\":\n\t\t\"Anthropic organization usage report (Admin API reporting credentials; not linked to any ordinary API key)\",\n\t\"bedrock-cloudwatch\": \"Amazon Bedrock CloudWatch metrics (AWS/Bedrock; not a billing invoice or remaining quota)\",\n\tunsupported: \"Usage reporting\",\n};\n\nfunction formatNumber(value: number): string {\n\treturn Number.isInteger(value) ? String(value) : String(Number(value.toFixed(4)));\n}\n\n/** Render a report for Advanced. Always names source/scope, account, period, region and update time. */\nexport function formatAccountUsageReport(report: AccountUsageReport, now: number): string[] {\n\tconst { target } = report;\n\tconst lines = [`${SCOPE_LABELS[report.scope]} — account/source [${target.accountKey || target.source}]`];\n\tconst place = [\n\t\t`Period ${target.period.start} to ${target.period.end} (UTC).`,\n\t\ttarget.region ? `Region ${target.region}.` : undefined,\n\t\treport.updatedAt === undefined ? \"Not updated.\" : `Updated ${new Date(report.updatedAt).toISOString()}.`,\n\t].filter(Boolean);\n\tlines.push(place.join(\" \"));\n\tif (report.status === \"unavailable\") {\n\t\tconst detail = report.reason ?? \"no reason was reported\";\n\t\tlines.push(`Account usage is unavailable: ${detail}.${report.nextAction ? ` ${report.nextAction}` : \"\"}`);\n\t\treturn lines;\n\t}\n\tif (report.stale) {\n\t\tconst age =\n\t\t\treport.updatedAt === undefined\n\t\t\t\t? \"\"\n\t\t\t\t: ` ${Math.max(0, Math.round((now - report.updatedAt) / 1000))} seconds ago`;\n\t\tlines.push(`Stale: last observed${age || \" at an unknown time\"}; refresh to update.`);\n\t}\n\tif (report.status === \"empty\") {\n\t\tlines.push(\"No usage was reported for this period. This is not a zero count.\");\n\t} else {\n\t\tif (report.status === \"partial\") {\n\t\t\tlines.push(`Partial results: ${report.reason ?? \"some data was missing\"}. Totals may be incomplete.`);\n\t\t} else if (report.reason) {\n\t\t\tlines.push(`Note: ${report.reason}.`);\n\t\t}\n\t\tfor (const metric of report.metrics) {\n\t\t\tlines.push(\n\t\t\t\t`${metric.name}: ${formatNumber(metric.value)} ${metric.unit}${metric.resetsAt ? ` (resets ${metric.resetsAt})` : \"\"}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn lines;\n}\n\nconst CODEX_REASONS: Record<CodexUsageUnavailableReason, string> = {\n\texpired_credential: \"the Codex sign-in has expired\",\n\tunauthorized: \"the Codex usage service rejected the sign-in\",\n\trate_limited: \"the Codex usage service is rate limiting requests\",\n\thttp_error: \"the Codex usage service returned an error\",\n\ttimeout: \"the Codex usage request timed out\",\n\tnetwork: \"the Codex usage service is unreachable\",\n\tmalformed: \"the Codex usage response was not recognised\",\n\tno_weekly_window: \"the Codex usage service reported no weekly window\",\n};\n\nconst CODEX_NEXT_ACTIONS: Partial<Record<CodexUsageUnavailableReason, string>> = {\n\texpired_credential: \"Sign in to OpenAI Codex again, then refresh usage.\",\n\tunauthorized: \"Sign in to OpenAI Codex again, then refresh usage.\",\n\trate_limited: \"Wait a minute, then refresh usage.\",\n\ttimeout: \"Check the connection, then refresh usage.\",\n\tnetwork: \"Check the connection, then refresh usage.\",\n};\n\nexport interface CodexUsageCollectorDeps {\n\t/** Stored Codex account for a pool key. No OAuth refresh happens here: expired sign-ins are reported as expired. */\n\treadAccount(accountKey: string, signal: AbortSignal): Promise<OAuthAccount | undefined>;\n\t/** Clear only a matching saved cooldown when fresh provider usage explicitly permits it. */\n\taccountPool?: OAuthAccountPool;\n\tfetch?: typeof fetch;\n\tnow?: () => number;\n}\n\n/**\n * Reuses the existing Codex weekly usage fetcher for one `openai-codex` OAuth account. `openai` API-key accounts are a\n * different provider and have no collector here: their usage is never inferred from Codex sign-ins.\n */\nexport function createCodexUsageCollector(deps: CodexUsageCollectorDeps): AccountReportCollector {\n\tconst scope = \"openai-codex-oauth-usage\" as const;\n\treturn {\n\t\tscopeFor: () => scope,\n\t\tasync collect(target, signal) {\n\t\t\tif (target.providerId !== CODEX_USAGE_PROVIDER_ID) {\n\t\t\t\treturn unavailableReport(target, scope, \"not an OpenAI Codex sign-in\");\n\t\t\t}\n\t\t\tconst account = await deps.readAccount(target.accountKey, signal);\n\t\t\tif (!account) {\n\t\t\t\treturn unavailableReport(target, scope, \"the Codex sign-in is no longer stored\", \"Reconnect OpenAI Codex.\");\n\t\t\t}\n\t\t\tconst now = deps.now?.() ?? Date.now();\n\t\t\tconst result = await fetchCodexWeeklyUsage(account, {\n\t\t\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(ACCOUNT_REPORT_REQUEST_TIMEOUT_MS)]),\n\t\t\t\tfetch: deps.fetch,\n\t\t\t\taccountPool: deps.accountPool,\n\t\t\t\tnow,\n\t\t\t});\n\t\t\tif (result.status === \"unavailable\") {\n\t\t\t\tif (result.reason === \"no_weekly_window\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"empty\",\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\t\tmetrics: [],\n\t\t\t\t\t\treason: CODEX_REASONS[result.reason],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn unavailableReport(target, scope, CODEX_REASONS[result.reason], CODEX_NEXT_ACTIONS[result.reason]);\n\t\t\t}\n\t\t\tconst metric: AccountUsageMetric = {\n\t\t\t\tname: \"Weekly allowance remaining\",\n\t\t\t\tvalue: result.usage.remainingPercent,\n\t\t\t\tunit: \"%\",\n\t\t\t\t...(result.usage.resetsAt === undefined ? {} : { resetsAt: new Date(result.usage.resetsAt).toISOString() }),\n\t\t\t};\n\t\t\tconst notes = [\n\t\t\t\t`Provider availability: ${getCodexAvailability(result.usage)} at ${new Date(now).toISOString()}`,\n\t\t\t\t\"not a check of every model\",\n\t\t\t];\n\t\t\tconst cooldown = new Date(account.exhaustedUntil ?? Number.NaN);\n\t\t\tif (result.cooldownCleared) notes.push(\"cached local cooldown cleared\");\n\t\t\telse if (cooldown.getTime() > now) notes.push(`cached local cooldown until ${cooldown.toISOString()}`);\n\t\t\treturn { status: \"ok\", target, scope, updatedAt: now, metrics: [metric], reason: notes.join(\"; \") };\n\t\t},\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-services.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAGnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAEN,KAAK,4BAA4B,EACjC,KAAK,cAAc,EACnB,KAAK,2BAA2B,EAChC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,KAAK,yBAAyB,EAAE,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H,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,iCAAiC,GACxC,OAAO,CAAC,oBAAoB,CAAC,CAwE/B;AAED;;;;;;GAMG;AACH,wBAAsB,8BAA8B,CACnD,OAAO,EAAE,qCAAqC,GAC5C,OAAO,CAAC,wBAAwB,CAAC,CAiBnC"}
|
|
@@ -71,45 +71,48 @@ export async function createAgentSessionServices(options) {
|
|
|
71
71
|
await resourceLoader.reload(options.resourceLoaderReloadOptions);
|
|
72
72
|
const diagnostics = [];
|
|
73
73
|
const extensionsResult = resourceLoader.getExtensions();
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
74
|
+
// Startup owns the single awaited refresh after all three registration queues drain.
|
|
75
|
+
modelRuntime.registerWithoutRefresh(() => {
|
|
76
|
+
for (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {
|
|
77
|
+
try {
|
|
78
|
+
modelRuntime.registerProvider(name, config);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
82
|
+
diagnostics.push({
|
|
83
|
+
type: "error",
|
|
84
|
+
message: `Extension "${extensionPath}" error: ${message}`,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
77
87
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
88
|
+
extensionsResult.runtime.pendingProviderRegistrations = [];
|
|
89
|
+
for (const { provider, extensionPath } of extensionsResult.runtime.pendingNativeProviderRegistrations) {
|
|
90
|
+
try {
|
|
91
|
+
modelRuntime.registerNativeProvider(provider);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
95
|
+
diagnostics.push({
|
|
96
|
+
type: "error",
|
|
97
|
+
message: `Extension "${extensionPath}" error: ${message}`,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
84
100
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
extensionsResult.runtime.pendingNativeProviderRegistrations = [];
|
|
100
|
-
for (const { definition, extensionPath } of extensionsResult.runtime.pendingVirtualModelRegistrations) {
|
|
101
|
-
try {
|
|
102
|
-
modelRuntime.registerVirtualModel(definition);
|
|
101
|
+
extensionsResult.runtime.pendingNativeProviderRegistrations = [];
|
|
102
|
+
for (const { definition, extensionPath } of extensionsResult.runtime.pendingVirtualModelRegistrations) {
|
|
103
|
+
try {
|
|
104
|
+
modelRuntime.registerVirtualModel(definition);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
108
|
+
diagnostics.push({
|
|
109
|
+
type: "error",
|
|
110
|
+
message: `Extension "${extensionPath}" error: ${message}`,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
103
113
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
diagnostics.push({
|
|
107
|
-
type: "error",
|
|
108
|
-
message: `Extension "${extensionPath}" error: ${message}`,
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
extensionsResult.runtime.pendingVirtualModelRegistrations = [];
|
|
114
|
+
extensionsResult.runtime.pendingVirtualModelRegistrations = [];
|
|
115
|
+
});
|
|
113
116
|
await modelRuntime.refresh({ allowNetwork: false });
|
|
114
117
|
diagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));
|
|
115
118
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,WAAW,EAAE,MA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;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CACnD,OAA8C;IAE9C,OAAO,kBAAkB,CAAC;QACzB,GAAG,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG;QACzB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,QAAQ;QACnC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY;QAC3C,eAAe,EAAE,OAAO,CAAC,QAAQ,CAAC,eAAe;QACjD,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,cAAc;QAC/C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Model } from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { takeTraceIngestCredentials } from \"./trace/config.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\tmodelRuntimeSignal?: AbortSignal;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\ttakeTraceIngestCredentials(process.env);\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t}));\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingProviderRegistrations = [];\n\tfor (const { provider, extensionPath } of extensionsResult.runtime.pendingNativeProviderRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerNativeProvider(provider);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingNativeProviderRegistrations = [];\n\tfor (const { definition, extensionPath } of extensionsResult.runtime.pendingVirtualModelRegistrations) {\n\t\ttry {\n\t\t\tmodelRuntime.registerVirtualModel(definition);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t});\n\t\t}\n\t}\n\textensionsResult.runtime.pendingVirtualModelRegistrations = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EACN,qBAAqB,GAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAiE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE7G,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OA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;QACnC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,YAAY;QAC3C,eAAe,EAAE,OAAO,CAAC,QAAQ,CAAC,eAAe;QACjD,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,cAAc;QAC/C,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Model } from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport type { SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { takeTraceIngestCredentials } from \"./trace/config.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\tmodelRuntimeSignal?: AbortSignal;\n\textensionFlagValues?: Map<string, boolean | string>;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartEvent;\n\tmodel?: Model<any>;\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcustomTools?: ToolDefinition[];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n}\n\nfunction applyExtensionFlagValues(\n\tresourceLoader: ResourceLoader,\n\textensionFlagValues: Map<string, boolean | string> | undefined,\n): AgentSessionRuntimeDiagnostic[] {\n\tif (!extensionFlagValues) {\n\t\treturn [];\n\t}\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\tconst registeredFlags = new Map<string, { type: \"boolean\" | \"string\" }>();\n\tfor (const extension of extensionsResult.extensions) {\n\t\tfor (const [name, flag] of extension.flags) {\n\t\t\tregisteredFlags.set(name, { type: flag.type });\n\t\t}\n\t}\n\n\tconst unknownFlags: string[] = [];\n\tfor (const [name, value] of extensionFlagValues) {\n\t\tconst flag = registeredFlags.get(name);\n\t\tif (!flag) {\n\t\t\tunknownFlags.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (flag.type === \"boolean\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, true);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"string\") {\n\t\t\textensionsResult.runtime.flagValues.set(name, value);\n\t\t\tcontinue;\n\t\t}\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Extension flag \"--${name}\" requires a value`,\n\t\t});\n\t}\n\n\tif (unknownFlags.length > 0) {\n\t\tdiagnostics.push({\n\t\t\ttype: \"error\",\n\t\t\tmessage: `Unknown option${unknownFlags.length === 1 ? \"\" : \"s\"}: ${unknownFlags.map((name) => `--${name}`).join(\", \")}`,\n\t\t});\n\t}\n\n\treturn diagnostics;\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\ttakeTraceIngestCredentials(process.env);\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t}));\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tconst extensionsResult = resourceLoader.getExtensions();\n\t// Startup owns the single awaited refresh after all three registration queues drain.\n\tmodelRuntime.registerWithoutRefresh(() => {\n\t\tfor (const { name, config, extensionPath } of extensionsResult.runtime.pendingProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tmodelRuntime.registerProvider(name, config);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\textensionsResult.runtime.pendingProviderRegistrations = [];\n\t\tfor (const { provider, extensionPath } of extensionsResult.runtime.pendingNativeProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tmodelRuntime.registerNativeProvider(provider);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\textensionsResult.runtime.pendingNativeProviderRegistrations = [];\n\t\tfor (const { definition, extensionPath } of extensionsResult.runtime.pendingVirtualModelRegistrations) {\n\t\t\ttry {\n\t\t\t\tmodelRuntime.registerVirtualModel(definition);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: `Extension \"${extensionPath}\" error: ${message}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\textensionsResult.runtime.pendingVirtualModelRegistrations = [];\n\t});\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tdiagnostics.push(...applyExtensionFlagValues(resourceLoader, options.extensionFlagValues));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n}\n"]}
|
|
@@ -181,8 +181,9 @@ export interface AgentSessionConfig {
|
|
|
181
181
|
/** Initial active built-in tool names. Default: [read, bash, edit, write] */
|
|
182
182
|
initialActiveToolNames?: string[];
|
|
183
183
|
/**
|
|
184
|
-
* Whether the initial tools come from the `defaultTools` setting. When true,
|
|
185
|
-
*
|
|
184
|
+
* Whether the initial tools come from the `defaultTools` setting. When true, a resumed session
|
|
185
|
+
* replaces them with the loadout its transcript records, with `defaultToolModifiers` applied, and
|
|
186
|
+
* reload activates tools newly added to the setting. Tools removed from it stay active.
|
|
186
187
|
*/
|
|
187
188
|
usesDefaultTools?: boolean;
|
|
188
189
|
/**
|
|
@@ -632,6 +633,7 @@ export declare class AgentSession {
|
|
|
632
633
|
* Restore the active tool loadout declared by the session transcript, if it declares one.
|
|
633
634
|
* Tools reachable only from other tools are never declared, but they do not depend on the active
|
|
634
635
|
* set, so the transcript's declarations are the whole loadout.
|
|
636
|
+
* @param modifiers `+name`/`-name` entries applied to the restored loadout.
|
|
635
637
|
*/
|
|
636
638
|
private _restoreToolsFromTranscript;
|
|
637
639
|
/**
|