@humain/humain-code 0.4.15 → 0.4.17
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 +74 -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-JRX7GYW3.js → chunk-4NFYTS4C.js} +8 -8
- package/dist/bundle/chunks/{chunk-MF2NEHP4.js → chunk-4XU7TDAL.js} +939 -560
- package/dist/bundle/chunks/{chunk-LUL775V7.js → chunk-5K5RFXXO.js} +4 -4
- package/dist/bundle/chunks/chunk-65U7MPF4.js +1790 -0
- package/dist/bundle/chunks/{chunk-AIXI6RIE.js → chunk-7PRU6YW3.js} +114 -82
- package/dist/bundle/chunks/{chunk-W5YJZKPF.js → chunk-AOL6QG6L.js} +2231 -2399
- package/dist/bundle/chunks/chunk-AWCJWXGD.js +212 -0
- package/dist/bundle/chunks/{chunk-NNKA2PAP.js → chunk-FHVNUUBF.js} +1 -1
- package/dist/bundle/chunks/chunk-FZUJXM6D.js +816 -0
- package/dist/bundle/chunks/chunk-IJYVMOB4.js +6 -0
- package/dist/bundle/chunks/chunk-LG2PJ6JN.js +131 -0
- package/dist/bundle/chunks/chunk-NCQ6WAQK.js +125 -0
- package/dist/bundle/chunks/{chunk-Z74ZYQPX.js → chunk-OKALNPTJ.js} +80 -210
- package/dist/bundle/chunks/{chunk-OX2IBCCA.js → chunk-PTP2ZHFQ.js} +88 -82
- 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-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-KK3KUUMM.js → chunk-X6OTEVGA.js} +71 -66
- package/dist/bundle/chunks/chunk-Y26OS23T.js +80 -0
- package/dist/bundle/chunks/chunk-YDBNMIA3.js +34 -0
- package/dist/bundle/chunks/{chunk-UHLW4KJ7.js → chunk-ZRGFX6T6.js} +92 -89
- 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-ARQPWKBQ.js} +8 -8
- package/dist/bundle/chunks/{dist-SGQMXO45.js → dist-D7M52E3X.js} +1416 -866
- 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-cjs-AXBW3N4F.js +182 -0
- package/dist/bundle/chunks/{easter-egg-3d-ZJ2JUFOA.js → easter-egg-3d-4SUPLBUF.js} +1 -1
- package/dist/bundle/chunks/{execute-LRTXH4YJ.js → execute-NTO3U76E.js} +10 -9
- package/dist/bundle/chunks/{extract-OZW5JHG6.js → extract-BKBHK4AK.js} +14 -13
- package/dist/bundle/chunks/github-copilot.js +34 -47
- package/dist/bundle/chunks/{google-generative-ai-YXXFSTX7.js → google-generative-ai-SJ4JO2MY.js} +2 -2
- package/dist/bundle/chunks/{google-vertex-3IVWLYJ5.js → google-vertex-KNLNNDET.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-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/{typesafe-system-one-62YHYXZV.js → typesafe-system-one-HCMGHK6A.js} +1 -1
- package/dist/bundle/chunks/{undici-7EW63V4X.js → undici-N4LWJ3S3.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-LP2ULVLW.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-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/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
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
var FifoQueue=class{incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(value){this.incoming.push(value)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},EventStream=class{queue=new FifoQueue;waiting=new FifoQueue;sink;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(isComplete,extractResult){this.isComplete=isComplete,this.extractResult=
|
|
3
|
+
extractResult,this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}push(event){if(this.done)return;if(this.isComplete(event)&&(this.done=!0,this.resolveFinalResult(this.extractResult(event))),this.sink){this.sink(event);return}let waiter=this.waiting.dequeue();waiter?waiter({value:event,done:!1}):this.queue.enqueue(event)}end(result){for(this.done=!0,result!==void 0&&this.resolveFinalResult(result);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.
|
|
4
|
+
asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let result=await new Promise(resolve=>this.waiting.enqueue(resolve));if(result.done)return;yield result.value}}}result(){return this.finalResultPromise}forwardTo(sink){for(;this.queue.length>0;)sink(this.queue.dequeue());this.sink=sink}},AssistantMessageEventStream=class extends EventStream{#startedAt=Date.now();#startedAtMonotonic=performance.now();constructor(){super(event=>event.type==="done"||
|
|
5
|
+
event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type for final result")})}push(event){event.type==="done"?this.#time(event.message):event.type==="error"&&this.#time(event.error),super.push(event)}end(result){result!==void 0&&this.#time(result),super.end(result)}#time(message){this.done||message.durationMs!==void 0||message.timestamp<this.#startedAt||(message.durationMs=Math.max(0,Math.round(performance.
|
|
6
|
+
now()-this.#startedAtMonotonic)))}};function createAssistantMessageEventStream(){return new AssistantMessageEventStream}export{EventStream,AssistantMessageEventStream,createAssistantMessageEventStream};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{Container,Spacer,Text,getCapabilities,getImageDimensions,highlightCode,hyperlink,imageFallback,keyHint,markStableRender,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-ZRGFX6T6.js";import{sanitizeBinaryOutput}from"./chunk-UGXYG7HN.js";import{getDocsPath,resolvePath}from"./chunk-YRCLNWFV.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS}from"./chunk-PY7SOXCA.js";import{typebox_exports}from"./chunk-OKALNPTJ.js";import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join(tmpdir(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path=createOutputFilePath(prefix,extension);return await writeFile(path,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path}
|
|
3
|
+
function createOutputFileStream(prefix,extension){let path=createOutputFilePath(prefix,extension);return{path,stream:createWriteStream(path,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200;function countLines(content){if(content.length===0)return 0;let lines=1;for(let i=content.indexOf(`
|
|
4
|
+
`);i!==-1;i=content.indexOf(`
|
|
5
|
+
`,i+1))lines++;return content.endsWith(`
|
|
6
|
+
`)?lines-1:lines}var NON_ASCII=/[\u0080-\uffff]/g,SURROGATE=/[\ud800-\udfff]/,SURROGATE_PAIRS=/[\ud800-\udbff][\udc00-\udfff]/g;function findNonAscii(content,from){return NON_ASCII.lastIndex=from,NON_ASCII.exec(content)?.index??content.length}function copyString(text){return Buffer.from(text,"utf16le").toString("utf16le")}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){
|
|
7
|
+
let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),totalLines=countLines(content);if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let ascii=totalBytes===content.length,firstNewline=content.indexOf(`
|
|
8
|
+
`),firstLineEnd=firstNewline===-1?content.length:firstNewline;if((ascii?firstLineEnd:Buffer.byteLength(content.slice(0,firstLineEnd),"utf-8"))>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLines=0,outputBytesCount=0,outputEnd=0,truncatedBy="lines",nextNonAscii=ascii?content.length:findNonAscii(content,0);for(let start=0;outputLines<totalLines&&outputLines<maxLines;){
|
|
9
|
+
let newline=content.indexOf(`
|
|
10
|
+
`,start),end=newline===-1?content.length:newline,lineBytes;if(end<=nextNonAscii?lineBytes=end-start:(lineBytes=Buffer.byteLength(content.slice(start,end),"utf-8"),nextNonAscii=findNonAscii(content,end)),outputLines>0&&lineBytes++,outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLines++,outputBytesCount+=lineBytes,outputEnd=end,start=end+1}return outputLines>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines"),{content:copyString(content.slice(0,outputEnd)),truncated:!0,
|
|
11
|
+
truncatedBy,totalLines,totalBytes,outputLines,outputBytes:outputBytesCount,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),totalLines=countLines(content);if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,
|
|
12
|
+
firstLineExceedsLimit:!1,maxLines,maxBytes};let ascii=totalBytes===content.length,contentEnd=content.endsWith(`
|
|
13
|
+
`)?content.length-1:content.length,outputLines=0,outputBytesCount=0,outputStart=contentEnd,partialLine,truncatedBy="lines",end=contentEnd;for(let i=totalLines-1;i>=0&&outputLines<maxLines;i--){let start=i===0?0:content.lastIndexOf(`
|
|
14
|
+
`,end-1)+1,lineBytes=(ascii?end-start:Buffer.byteLength(content.slice(start,end),"utf-8"))+(outputLines>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes",outputLines===0&&(partialLine=truncateStringToBytesFromEnd(content.slice(start,end),maxBytes),outputLines=1,outputBytesCount=Buffer.byteLength(partialLine,"utf-8"));break}outputLines++,outputBytesCount+=lineBytes,outputStart=start,end=start-1}return outputLines>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines"),{content:partialLine??
|
|
15
|
+
copyString(content.slice(outputStart,contentEnd)),truncated:!0,truncatedBy,totalLines,totalBytes,outputLines,outputBytes:outputBytesCount,lastLinePartial:partialLine!==void 0,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str2,maxBytes){let buf=Buffer.from(str2,"utf-8");if(buf.length<=maxBytes)return str2;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){
|
|
16
|
+
return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}function truncateMiddle(content,maxBytes){let buf=Buffer.from(content,"utf-8"),totalLines=countLines(content);if(buf.length<=maxBytes)return{content,truncated:!1,removedChars:0,totalBytes:buf.length,totalLines};let isBoundary=index=>index>=buf.length||(buf[index]&192)!==128,headEnd=Math.floor(maxBytes/2);for(;headEnd>0&&!isBoundary(headEnd);)headEnd--;let tailStart=buf.length-
|
|
17
|
+
(maxBytes-Math.floor(maxBytes/2));for(;tailStart<buf.length&&!isBoundary(tailStart);)tailStart++;let head=buf.subarray(0,headEnd).toString("utf-8"),tail=buf.subarray(tailStart).toString("utf-8"),removed=buf.subarray(headEnd,tailStart).toString("utf-8"),removedChars=removed.length;return SURROGATE.test(removed)&&(removedChars-=removed.match(SURROGATE_PAIRS)?.length??0),{content:`${head}\u2026${removedChars} chars truncated\u2026${tail}`,truncated:!0,removedChars,totalBytes:buf.length,totalLines}}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){usage.usageIncomplete&&(totals.usageIncomplete=!0),totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{...first.usageIncomplete||second.usageIncomplete?{usageIncomplete:!0}:{},input:first.input+second.input,output:first.output+second.
|
|
18
|
+
output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+
|
|
19
|
+
second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total}}}function normalizeUsage(usage){let result={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},...usage?.usageIncomplete?{usageIncomplete:!0}:{}};for(let key of["input","output","cacheRead","cacheWrite"]){let count=usage?.[key];typeof count=="number"&&Number.isSafeInteger(count)&&count>=0?result[key]=count:result.usageIncomplete=
|
|
20
|
+
!0;let cost2=usage?.cost?.[key];typeof cost2=="number"&&Number.isFinite(cost2)&&cost2>=0?result.cost[key]=cost2:result.usageIncomplete=!0}let totalTokens=usage?.totalTokens;(typeof totalTokens!="number"||!Number.isSafeInteger(totalTokens)||totalTokens<0)&&(result.usageIncomplete=!0),result.totalTokens=result.input+result.output+result.cacheRead+result.cacheWrite;let cost=usage?.cost?.total;return typeof cost=="number"&&Number.isFinite(cost)&&cost>=0?result.cost.total=cost:result.usageIncomplete=
|
|
21
|
+
!0,result}function getSummaryUsage(usage,ids,kind,owners){if(ids===void 0||Array.isArray(ids)&&ids.length===0)return usage;let remaining=normalizeUsage(usage),ownerIds=Array.isArray(ids)?[...new Set(ids)]:[],covered=ownerIds.length>0,observed=createUsageTotals();for(let id of ownerIds){let owner=typeof id=="string"&&id.length>0?owners.find(entry=>entry.id===id):void 0;if(!owner||owner.kind!==kind){covered=!1;continue}let value=normalizeUsage(owner.usage);(typeof owner.provider!="string"||owner.provider.
|
|
22
|
+
length===0||typeof owner.model!="string"||owner.model.length===0||value.usageIncomplete)&&(covered=!1),addUsageToTotals(observed,value)}if(covered&&!usage)return;covered&&!usage?.usageIncomplete&&delete remaining.usageIncomplete;let residual=remaining.cost.total-observed.cost,drift=Number.EPSILON*Math.max(remaining.cost.total,observed.cost)*(ownerIds.length+1);remaining.cost.total=residual>drift?residual:0;for(let key of["input","output","cacheRead","cacheWrite"])remaining[key]=Math.max(0,remaining[key]-
|
|
23
|
+
observed[key]);return remaining.totalTokens=remaining.input+remaining.output+remaining.cacheRead+remaining.cacheWrite,(!covered||remaining.cost.total>0||remaining.totalTokens>0)&&(remaining.usageIncomplete=!0),remaining.usageIncomplete||remaining.cost.total>0||remaining.totalTokens>0?remaining:void 0}function getSessionUsage(entries){let owners=entries.filter(entry=>entry.type==="usage"),seen=new Set,summaries=new Map,result=[];for(let entry of entries){let usage;if(entry.type==="usage"){if(seen.
|
|
24
|
+
has(entry.id))continue;seen.add(entry.id),usage=normalizeUsage(entry.usage)}else if(entry.type==="message"&&(entry.message.role==="assistant"||entry.message.role==="toolResult"))usage=entry.message.usage;else if((entry.type==="compaction"||entry.type==="branch_summary")&&(usage=getSummaryUsage(entry.usage,entry.usageEntryIds,entry.type==="compaction"?"compaction":"branchSummary",owners),Array.isArray(entry.usageEntryIds)&&entry.usageEntryIds.length>0)){let key=JSON.stringify([entry.type,[...new Set(
|
|
25
|
+
entry.usageEntryIds)].sort()]),previous=summaries.get(key);usage&&(!previous||usage.cost.total>=previous.usage.cost.total)&&summaries.set(key,{entry,usage});continue}usage&&result.push({entry,usage})}return[...result,...summaries.values()]}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let{entry,usage}of getSessionUsage(entries)){let key;if(entry.type==="message"&&entry.message.role==="assistant"?key=`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`:
|
|
26
|
+
entry.type==="usage"?key=`${entry.provider}/${entry.model}`:key="Tools/summaries",!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,...totals.usageIncomplete?{usageIncomplete:!0}:{},cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.usageIncomplete||entry.cost>0||entry.tokens>0).sort((a,b)=>b.
|
|
27
|
+
cost-a.cost)}function truncateToVisualLines(text,maxVisualLines,width,paddingX=0,keep="end"){if(!text)return{visualLines:[],skippedCount:0};let allVisualLines=new Text(text,paddingX,0).render(width);if(allVisualLines.length<=maxVisualLines)return{visualLines:allVisualLines,skippedCount:0};let truncatedLines=keep==="start"?allVisualLines.slice(0,maxVisualLines):allVisualLines.slice(-maxVisualLines),skippedCount=allVisualLines.length-maxVisualLines;return{visualLines:truncatedLines,skippedCount}}function truncateStyledLinesToVisualEnd(lines,styleLine,maxVisualLines,width){
|
|
28
|
+
if(lines.length===0)return{visualLines:[],skippedCount:0};let contentWidth=Math.max(1,width),visualCount=line=>{let normalized=line.replace(/\t/g," ");return normalized===""||visibleWidth(normalized)<=contentWidth?1:wrapTextWithAnsi(styleLine(normalized),contentWidth).length},start=lines.length,tailVisualLines=0;for(;start>0&&tailVisualLines<maxVisualLines;)start--,tailVisualLines+=visualCount(lines[start]);let headVisualLines=0;for(let i=0;i<start;i++)headVisualLines+=visualCount(lines[i]);let tail=new Text(
|
|
29
|
+
lines.slice(start).map(styleLine).join(`
|
|
30
|
+
`),0,0).render(width),total=headVisualLines+tail.length;return total<=maxVisualLines?{visualLines:tail,skippedCount:0}:{visualLines:tail.slice(-maxVisualLines),skippedCount:total-maxVisualLines}}var VisualLinePreview=class{options;cachedWidth;cachedLines;constructor(options){this.options=options}render(width){if(this.cachedLines===void 0||this.cachedWidth!==width){let options=this.options,{maxVisualLines,keep,formatHint}=options,preview="lines"in options?truncateStyledLinesToVisualEnd(options.lines,
|
|
31
|
+
options.styleLine,maxVisualLines,width):truncateToVisualLines(options.text,maxVisualLines,width,0,keep),lines=preview.visualLines;if(preview.skippedCount>0){let hint=truncateToWidth(formatHint(preview.skippedCount),width,"...");this.cachedLines=keep==="start"?[...lines,hint]:[hint,...lines]}else this.cachedLines=lines;this.cachedWidth=width}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0}};markStableRender(VisualLinePreview);import*as os from"node:os";import{pathToFileURL}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{
|
|
32
|
+
complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(
|
|
33
|
+
ansiRegex,"")}function shortenPath(path){if(typeof path!="string")return"";let home=os.homedir();return path.startsWith(home)?`~${path.slice(home.length)}`:path}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&
|
|
34
|
+
(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text){return text.replace(/\t/g," ")}function normalizeDisplayText(text){return text.replace(
|
|
35
|
+
/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
|
|
36
|
+
`),caps=getCapabilities();if(imageBlocks.length>0&&(!caps.images||!showImages)){let imageIndicators=imageBlocks.map(img=>{let mimeType=img.mimeType??"image/unknown",dims=img.data&&img.mimeType?getImageDimensions(img.data,img.mimeType)??void 0:void 0;return imageFallback(mimeType,dims)}).join(`
|
|
37
|
+
`);output=output?`${output}
|
|
38
|
+
${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;function formatToolCallWithArgs(title,args,theme,expanded){let header=theme.fg("toolTitle",theme.bold(title));if(args==null)return header;let entries=typeof args=="object"&&!Array.isArray(args)?Object.entries(args):[["args",args]];if(entries.length===0)return header;if(expanded){let lines=entries.map(([key,value])=>{let text=typeof value=="string"?value:JSON.stringify(value,null,2)??String(value);return` ${key}: ${replaceTabs(
|
|
39
|
+
text).replace(/\r/g,"").split(`
|
|
40
|
+
`).join(`
|
|
41
|
+
`)}`});return`${header}
|
|
42
|
+
${theme.fg("muted",lines.join(`
|
|
43
|
+
`))}`}let pairs=entries.map(([key,value])=>`${key}=${JSON.stringify(value)??String(value)}`).join(" "),preview=pairs.length>COLLAPSED_ARGS_CHARS?`${pairs.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:pairs;return`${header} ${theme.fg("muted",preview)}`}function formatToolDuration(ms){let seconds=ms/1e3;if(seconds<60)return`${seconds.toFixed(1)}s`;let totalSeconds=Math.floor(seconds),minutes=Math.floor(totalSeconds/60),remainder=totalSeconds%60;return minutes<60?`${minutes}m ${remainder}s`:`${Math.floor(minutes/
|
|
44
|
+
60)}h ${minutes%60}m ${remainder}s`}function startToolTimer(context){let state=context.state;context.executionStarted&&state.startedAt===void 0&&(state.startedAt=Date.now(),state.endedAt=void 0)}function toolTimerText(context,isPartial){let state=context.state;if(state.startedAt!==void 0&&isPartial&&!state.interval&&(state.interval=setInterval(()=>context.invalidate(),1e3)),(!isPartial||context.isError)&&(state.endedAt??=Date.now(),state.interval&&(clearInterval(state.interval),state.interval=void 0)),
|
|
45
|
+
!isPartial&&context.durationMs!==void 0)return`Took ${formatToolDuration(context.durationMs)}`;if(state.startedAt===void 0)return;let endTime=state.endedAt??Date.now();return`${isPartial?"Elapsed":"Took"} ${formatToolDuration(endTime-state.startedAt)}`}function invalidArgText(theme){return theme.fg("error","[invalid arg]")}function renderToolPath(rawPath,theme,cwd,options){if(rawPath===null)return invalidArgText(theme);let value=rawPath||options?.emptyFallback;return value?linkPath(theme.fg("acc\
|
|
46
|
+
ent",shortenPath(value)),value,cwd):theme.fg("toolOutput","...")}function toCodemodeIdentifier(name){let identifier="";for(let char of name){let valid=identifier===""?/^[A-Za-z_$]$/.test(char):/^[A-Za-z0-9_$]$/.test(char);identifier+=valid?char:"_"}return identifier===""?"_":identifier}var IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,INDENT=" ",DEFAULT_INPUT_SCHEMA_MAX_CHARS=16e3,MAX_REF_EXPANSIONS=32,TAG_KEYWORDS=["minimum","exclusiveMinimum","maximum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","minItems","maxItems"],LOWER_BOUNDS=new Set(["minimum","exclusiveMinimum","minLength","minItems"]),UPPER_BOUNDS=new Set(["maximum","exclusiveMaximum","maxLength","maxItems"]),MAX_TAG_CHARS=80,LINE_TERMINATORS=/[\r\n\u2028\u2029]/g;function renderToolSignature(tool,options={}){let input=tool.inputSchema===void 0?"unknown":schemaToType(tool.inputSchema,{maxChars:options.inputMaxChars??DEFAULT_INPUT_SCHEMA_MAX_CHARS});return`${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${renderToolOutputType(tool.outputSchema)}>;`}function renderToolSample(tool,options={}){let declaration=`declare const tools: { ${renderToolSignature(tool,options)} };`;return`${tool.description?.trim()??""}
|
|
47
|
+
|
|
48
|
+
codemode tool declaration:
|
|
49
|
+
\`\`\`ts
|
|
50
|
+
${declaration}
|
|
51
|
+
\`\`\``}function renderToolOutputType(schema){return schema===void 0?"unknown":schemaToType(schema)}function propertyKey(name){return IDENTIFIER.test(name)?name:JSON.stringify(name)}function union(types){let unique=[...new Set(types)];return unique.includes("unknown")?"unknown":unique.length===0?"never":unique.join(" | ")}function schemaToType(schema,options={}){let render=tags=>toType(schema,{root:schema,resolving:new Set,expansions:0,tags}),type=render(!0);if(options.maxChars===void 0||type.length<=options.maxChars)return type;let untagged=render(!1);return untagged.length<=options.maxChars?
|
|
52
|
+
untagged:"unknown"}function resolveRef(ref,root){if(ref!=="#"&&!ref.startsWith("#/"))return;let current=root;for(let segment of ref.slice(2).split("/").filter(Boolean)){let key=decodeURIComponent(segment).replaceAll("~1","/").replaceAll("~0","~");if(typeof current!="object"||current===null||Array.isArray(current)||!(key in current))return;current=current[key]}return typeof current=="boolean"||typeof current=="object"&¤t!==null&&!Array.isArray(current)?current:void 0}function toType(schema,context){
|
|
53
|
+
if(schema===!0)return"unknown";if(schema===!1)return"never";if(typeof schema!="object"||schema===null||Array.isArray(schema))return"unknown";if(typeof schema.$ref=="string"){let ref=schema.$ref;if(context.resolving.has(ref)||context.expansions>=MAX_REF_EXPANSIONS)return"unknown";let target=resolveRef(ref,context.root);if(target===void 0)return"unknown";context.expansions++,context.resolving.add(ref);try{return toType(target,context)}finally{context.resolving.delete(ref)}}if("const"in schema)return JSON.
|
|
54
|
+
stringify(schema.const)??"unknown";if(Array.isArray(schema.enum))return union(schema.enum.map(value=>JSON.stringify(value)??"unknown"));let variants=Array.isArray(schema.anyOf)?schema.anyOf:Array.isArray(schema.oneOf)?schema.oneOf:void 0;if(variants)return union(variants.map(variant=>toType(variant,context)));if(Array.isArray(schema.allOf)){let parts=schema.allOf.map(part=>toType(part,context)).filter(part=>part!=="unknown");return parts.length===0?"unknown":parts.map(part=>part.includes(" | ")?
|
|
55
|
+
`(${part})`:part).join(" & ")}let type=schema.type;if(Array.isArray(type))return union(type.map(entry=>toType({...schema,type:entry},context)));switch(type){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";case"array":return arrayType(schema,context);case"object":return objectType(schema,context);case void 0:return"properties"in schema||"additionalProperties"in schema||"required"in schema?objectType(schema,context):"items"in
|
|
56
|
+
schema||"prefixItems"in schema?arrayType(schema,context):"unknown";default:return"unknown"}}function arrayType(schema,context){if(schema.items!==void 0&&!Array.isArray(schema.items))return`Array<${toType(schema.items,context)}>`;let tuple=Array.isArray(schema.prefixItems)?schema.prefixItems:Array.isArray(schema.items)?schema.items:[];return tuple.length>0?`[${tuple.map(item=>toType(item,context)).join(", ")}]`:"unknown[]"}function descriptionOf(property){let description=property?.description;return typeof description==
|
|
57
|
+
"string"?description.trim():""}function constraintTags(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return"";let property=schema,variants=Array.isArray(property.anyOf)?property.anyOf:property.oneOf,nonNull=Array.isArray(variants)?variants.filter(variant=>variant?.type!=="null"):[],branch=nonNull.length===1?nonNull[0]:void 0,schemas=(typeof branch=="object"&&branch!==null&&!Array.isArray(branch)?[property,branch]:[property]).map(schema2=>({...schema2,...schema2.exclusiveMinimum===
|
|
58
|
+
!0?{minimum:void 0,exclusiveMinimum:schema2.minimum}:{},...schema2.exclusiveMaximum===!0?{maximum:void 0,exclusiveMaximum:schema2.maximum}:{}})),tags=[],isInteger=type=>type==="integer"||Array.isArray(type)&&type.includes("integer");schemas.some(schema2=>isInteger(schema2.type))&&tags.push("@integer");for(let keyword of TAG_KEYWORDS){let values=schemas.map(schema2=>schema2[keyword]);if(LOWER_BOUNDS.has(keyword)||UPPER_BOUNDS.has(keyword)){let numbers=values.filter(value=>typeof value=="number");
|
|
59
|
+
if(numbers.length===0)continue;tags.push(`@${keyword} ${LOWER_BOUNDS.has(keyword)?Math.max(...numbers):Math.min(...numbers)}`);continue}for(let value of new Set(values))(typeof value=="number"||typeof value=="string")&&tags.push(`@${keyword} ${value}`)}return schemas.some(schema2=>schema2.uniqueItems===!0)&&tags.push("@uniqueItems"),property.default!==void 0&&property.default!==null&&tags.push(`@default ${JSON.stringify(property.default)}`),property.deprecated===!0&&tags.push("@deprecated"),tags.
|
|
60
|
+
filter(tag=>tag.length<=MAX_TAG_CHARS).map(tag=>tag.replace(LINE_TERMINATORS,char=>`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`)).join(" ")}function objectType(schema,context){let properties=typeof schema.properties=="object"&&schema.properties!==null&&!Array.isArray(schema.properties)?schema.properties:{},required=new Set(Array.isArray(schema.required)?schema.required:[]),names=Object.keys(properties).sort(),members=names.map(name=>{let optional=required.has(name)?"":"?";return`${propertyKey(
|
|
61
|
+
name)}${optional}: ${toType(properties[name],context)};`}),additional=schema.additionalProperties;if(additional!==void 0&&additional!==!1){let type=additional===!0?"unknown":toType(additional,context);members.push(`[key: string]: ${type};`)}else additional===void 0&&names.length===0&&members.push("[key: string]: unknown;");if(members.length===0)return"{}";let comments=names.map(name=>{let lines2=descriptionOf(properties[name]).split(LINE_TERMINATORS).map(line=>line.trim()).filter(Boolean),tags=context.
|
|
62
|
+
tags?constraintTags(properties[name]):"";return tags?[...lines2,tags]:lines2});if(!comments.some(comment=>comment.length>0))return`{ ${members.join(" ")} }`;let lines=["{"];comments.forEach((comment,index)=>{for(let line of comment)lines.push(`${INDENT}// ${line}`);lines.push(`${INDENT}${members[index].replaceAll(`
|
|
63
|
+
`,`
|
|
64
|
+
${INDENT}`)}`)});for(let member of members.slice(names.length))lines.push(`${INDENT}${member}`);return lines.push("}"),lines.join(`
|
|
65
|
+
`)}var CODEMODE_OPTIONS_PREFIX="// @options:",SUPPORTED_FIELDS=["max_output_tokens","timeout_ms"],SUPPORTED_FIELDS_TEXT="`max_output_tokens` and `timeout_ms`";var CODEMODE_SOURCE_GRAMMAR=String.raw`
|
|
66
|
+
start: options_source | plain_source
|
|
67
|
+
options_source: OPTIONS_LINE NEWLINE SOURCE
|
|
68
|
+
plain_source: SOURCE
|
|
69
|
+
|
|
70
|
+
OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/
|
|
71
|
+
NEWLINE: /\r?\n/
|
|
72
|
+
SOURCE: /[\s\S]+/
|
|
73
|
+
`,CodemodeSourceError=class extends Error{constructor(message){super(message),this.name="CodemodeSourceError"}};function isSafeInteger(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function parseOptions(directive){if(directive==="")throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);let value;try{value=JSON.parse(directive)}catch(error){throw new CodemodeSourceError(`@options must be valid JSON with supporte\
|
|
74
|
+
d fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error?error.message:String(error)}`)}if(typeof value!="object"||value===null||Array.isArray(value))throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);let fields=value;for(let key of Object.keys(fields))if(!SUPPORTED_FIELDS.includes(key))throw new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \`${key}\``);let options={},{max_output_tokens,timeout_ms}=fields;
|
|
75
|
+
if(max_output_tokens!==void 0){if(!isSafeInteger(max_output_tokens))throw new CodemodeSourceError("@options field `max_output_tokens` must be a non-negative safe integer");options.maxOutputTokens=max_output_tokens}if(timeout_ms!==void 0){if(!isSafeInteger(timeout_ms)||timeout_ms===0||timeout_ms>2147483647)throw new CodemodeSourceError("@options field `timeout_ms` must be a positive integer up to 2147483647");options.timeoutMs=timeout_ms}return options}function parseCodemodeSource(input){if(input.
|
|
76
|
+
trim()==="")throw new CodemodeSourceError('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');let lines=input.split(`
|
|
77
|
+
`),misplaced=lines.findIndex((line,index)=>index>0&&line.trimStart().startsWith(CODEMODE_OPTIONS_PREFIX));if(misplaced!==-1)throw new CodemodeSourceError(`The ${CODEMODE_OPTIONS_PREFIX} line must be the first line of the input; found one on line ${misplaced+1}`);let newline=input.indexOf(`
|
|
78
|
+
`),trimmed=lines[0].replace(/\r$/,"").trimStart();if(!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX))return{code:input,options:{}};let code=newline===-1?"":input.slice(newline);if(code.trim()==="")throw new CodemodeSourceError("The @options line must be followed by JavaScript source on subsequent lines");return{code,options:parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim())}}var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}function tokenize(text){return text.replace(/([a-z0-9])([A-Z])/g,
|
|
79
|
+
"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(term=>term.length>0&&!STOP_WORDS.has(term)).map(stem)}function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function schemaText(schema,parts){if(isObject(schema)){if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,parts);schemaText(
|
|
80
|
+
schema.items,parts);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,parts)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.name,tool.name.replaceAll("_"," "),tool.description];return schemaText(tool.parameters,parts),namespace&&parts.push(namespace.name,namespace.description??"",namespace.instructions??""),{name:tool.name,text:parts.filter(part=>part.trim()).join(" ")}}var Bm25Ranker=class{k1;b;constructor(options={}){
|
|
81
|
+
this.k1=options.k1??1.2,this.b=options.b??.75}rank(query,documents,limit){let queryTerms=[...new Set(tokenize(query))];if(queryTerms.length===0||documents.length===0||limit<=0)return[];let termCounts=documents.map(document=>{let counts=new Map;for(let term of tokenize(document.text))counts.set(term,(counts.get(term)??0)+1);return counts}),lengths=termCounts.map(counts=>[...counts.values()].reduce((sum,count)=>sum+count,0)),averageLength=lengths.reduce((sum,length)=>sum+length,0)/documents.length||
|
|
82
|
+
1,idf=new Map(queryTerms.map(term=>{let frequency=termCounts.filter(counts=>counts.has(term)).length;return[term,Math.log(1+(documents.length-frequency+.5)/(frequency+.5))]})),matches=[];return documents.forEach((document,index)=>{let score=0;for(let term of queryTerms){let count=termCounts[index].get(term);if(!count)continue;let norm=this.k1*(1-this.b+this.b*lengths[index]/averageLength);score+=(idf.get(term)??0)*(count*(this.k1+1)/(count+norm))}score>0&&matches.push({name:document.name,score})}),
|
|
83
|
+
matches.sort((a,b)=>b.score-a.score).slice(0,limit)}},toolSearchSchema=typebox_exports.Object({query:typebox_exports.String({description:"Search query for deferred tools."}),limit:typebox_exports.Optional(typebox_exports.Number({description:`Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.`}))});function isSearchable(exposure){return exposure==="codemode"||exposure==="deferred"}function searchAndLoad(tools,query,limit){let active=tools.getActiveTools(),candidates=tools.
|
|
84
|
+
getAllTools().filter(tool=>isSearchable(tool.exposure)&&!active.includes(tool.name)),documents=candidates.map(tool=>createToolSearchDocument(tool,tool.namespace)),matches=new Bm25Ranker().rank(query,documents,limit);return matches.length>0&&tools.setActiveTools([...active,...matches.map(match=>match.name)]),matches.map(match=>({name:match.name,description:candidates.find(tool=>tool.name===match.name)?.description??""}))}var TOOL_SEARCH_DESCRIPTION=`# Tool discovery
|
|
85
|
+
|
|
86
|
+
Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
|
|
87
|
+
|
|
88
|
+
Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,
|
|
89
|
+
exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from\
|
|
90
|
+
your next call:
|
|
91
|
+
${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
|
|
92
|
+
`)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";var SETTINGS_DEFAULTS={transport:"auto",sessionShareDestination:"auto",steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",compaction:{enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},branchSummary:{reserveTokens:16384,skipPrompt:!1},retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:DEFAULT_MAX_AGENT_RETRY_DELAY_MS,provider:{maxRetryDelayMs:6e4}},hideThinkingBlock:!1,showCacheMissNotices:!1,quietStartup:!1,defaultProjectTrust:"ask",collapseChangelog:!1,enableInstallTelemetry:!0,
|
|
93
|
+
enableAnalytics:!1,enableSkillCommands:!0,terminal:{showImages:!0,imageWidthCells:60,clearOnShrink:!1,showTerminalProgress:!1},images:{autoResize:!0,blockImages:!1},doubleEscapeAction:"tree",treeFilterMode:"default",editorPaddingX:0,outputPad:1,autocompleteMaxVisible:5,markdown:{codeBlockIndent:" ",mermaid:"streaming"},warnings:{anthropicExtraUsage:!0},codemode:{mode:"on",inlineBudget:3e3,flowImplementer:"only"},cacheWarming:"streaming",tuiMode:"fullscreen",fullscreenExitOutput:"transcript",fullscreenScrollbar:"\
|
|
94
|
+
auto",fullscreenCopyOnSelect:!0,fullscreenWheelScrollLines:"auto"};function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-NTO3U76E.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(
|
|
95
|
+
2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)}\
|
|
96
|
+
${theme.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
|
|
97
|
+
${theme.fg("error",call.error.split(`
|
|
98
|
+
`).join(`
|
|
99
|
+
`))}`),line}var codemodeRenderers={renderCall(args,theme,context){startToolTimer(context);let code=str(args?.code),title=theme.fg("toolTitle",theme.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let highlighted=highlightCode(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
|
|
100
|
+
`);component.addChild(context.expanded?new Text(highlighted,0,0):new VisualLinePreview({text:highlighted,maxVisualLines:CODE_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}))}return component},renderResult(result,options,theme,context){let timerText=toolTimerText(context,options.isPartial),component=context.lastComponent??new Container;component.clear();let calls=result.details?.calls??[];if(calls.length>0){let shown=options.expanded?calls:calls.slice(-CALL_PREVIEW_COUNT),
|
|
101
|
+
lines=shown.map(call=>formatCall(call,theme,options.expanded));shown.length<calls.length&&lines.unshift(`${theme.fg("muted",`... (${calls.length-shown.length} earlier calls,`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`);let priced=calls.filter(call=>call.cost);if(priced.length>1){let total=priced.reduce((sum,call)=>sum+(call.cost??0),0);lines.push(theme.fg("muted",`Model calls: ${formatCost(total)}`))}component.addChild(new Spacer(1)),component.addChild(new Text(lines.join(
|
|
102
|
+
`
|
|
103
|
+
`),0,0))}let[first,...rest]=result.content,hasHeader=first?.type==="text"&&SCRIPT_HEADER.test(first.text),output=options.isPartial?"":getTextOutput({...result,content:hasHeader?rest:result.content},context.showImages).trim();if(output){let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
|
|
104
|
+
`).map(line=>theme.fg(color,line)).join(`
|
|
105
|
+
`);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme.fg("muted",`Full output: ${fullOutputPath}`),0,0))}}return timerText&&(component.addChild(new Spacer(1)),component.addChild(new Text(theme.
|
|
106
|
+
fg("muted",timerText),0,0))),component}};var CODEMODE_TOOL_NAME="codemode",CODEMODE_STORE_ENTRY_TYPE="codemode-store",TEXT_OUTPUT_SCHEMA={type:"string"},codemodeSchema=typebox_exports.Object({code:typebox_exports.String({description:"Raw JavaScript source."})}),codemodeToolSystemPromptContribution={snippet:"Run JavaScript that calls other tools",guidelines:["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."]},CODEMODE_DOCS_PATH=join2(getDocsPath(),"co\
|
|
107
|
+
demode.md"),DESCRIPTION_INTRO='Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` resolves to a string, or an object if the tool\'s declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; che\
|
|
108
|
+
ck its fields. Calls still running when the script ends are cancelled.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`';function describeGlobals(models){let lines=["Globals:","- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()`\
|
|
109
|
+
also saves the image to a temp file and the result names its path.","- `store(key, value)` and `load(key)` keep JSON values across codemode calls.","- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools."];return models&&lines.push(`- \`models\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`),lines.join(`
|
|
110
|
+
`)}var DEFAULT_CODEMODE_INLINE_BUDGET=SETTINGS_DEFAULTS.codemode.inlineBudget,CHARS_PER_TOKEN=4;function toCodemodeDeclaration(tool,guidelines=[]){let bullets=guidelines.flatMap(guideline=>guideline.trim()?[`- ${guideline.trim()}`]:[]);return{name:tool.name,description:bullets.length>0?`${tool.description.trim()}
|
|
111
|
+
|
|
112
|
+
${bullets.join(`
|
|
113
|
+
`)}`:tool.description,inputSchema:tool.parameters,outputSchema:tool.outputSchema??TEXT_OUTPUT_SCHEMA}}function getCodemodeCallableTools(tools){return tools.filter(tool=>tool.name!==CODEMODE_TOOL_NAME)}function renderToolSection(declaration){let id=toCodemodeIdentifier(declaration.name);return`${id===declaration.name?`### \`${id}\``:`### \`${id}\` (\`${declaration.name}\`)`}
|
|
114
|
+
${renderToolSample(declaration).trim()}`}function selectCatalog(groups,budget){if(budget===void 0)return new Set(groups.flatMap(group=>group.entries.map(entry=>entry.name)));let queues=groups.map(group=>[...group.entries].sort((a,b)=>a.cost-b.cost)),shown=new Set,remaining=budget,active=queues.filter(queue=>queue.length>0);for(;active.length>0;)active=active.filter(queue=>{let next=queue[0];return next.cost>remaining?!1:(remaining-=next.cost,shown.add(next.name),queue.shift(),queue.length>0)});return shown}
|
|
115
|
+
function createCodemodeDescription(tools,options={}){let declarations=getCodemodeCallableTools(tools).filter(tool=>!options.deferred?.has(tool.name)).map(tool=>toCodemodeDeclaration(tool,options.guidelines?.get(tool.name))),groups=new Map([["",{namespace:void 0,entries:[]}]]);for(let declaration of declarations){let namespace=options.namespaces?.get(declaration.name),key=namespace?`ns:${namespace.name}`:"",group=groups.get(key)??{namespace,entries:[]};groups.set(key,group);let section=renderToolSection(
|
|
116
|
+
declaration);group.entries.push({name:declaration.name,section,cost:Math.ceil(section.length/CHARS_PER_TOKEN)})}let ordered=[...groups.values()].sort((a,b)=>a.namespace===void 0?-1:b.namespace===void 0?1:a.namespace.name.localeCompare(b.namespace.name)),shown=selectCatalog(ordered,options.inlineBudget),sections=[DESCRIPTION_INTRO,describeGlobals(options.models===!0)];if(declarations.length===0)return sections.join(`
|
|
117
|
+
|
|
118
|
+
`);let toolSections=["Nested tools:"];for(let{namespace,entries}of ordered){let visible=entries.filter(entry=>shown.has(entry.name));if(namespace){let listing=visible.length===entries.length?"":visible.length===0?" (tools not listed)":" (some tools not listed)",description=namespace.description?.trim();toolSections.push(`## ${namespace.name}${listing}${description?`
|
|
119
|
+
${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}return sections.push(toolSections.join(`
|
|
120
|
+
|
|
121
|
+
`)),sections.join(`
|
|
122
|
+
|
|
123
|
+
`)}function describeFields(schema,depth){if(typeof schema!="object"||schema===null)return;let{type,properties,required}=schema;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field])=>{let nested=depth>0?describeFields(field,depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(schema){
|
|
124
|
+
let type=renderToolOutputType(schema);return type==="string"?"a string":`\`${describeFields(schema,1)??type.replace(/\s+/g," ")}\``}function describeScriptCall(tool){return`${tool.description.trim()}
|
|
125
|
+
|
|
126
|
+
Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&
|
|
127
|
+
(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.
|
|
128
|
+
getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.
|
|
129
|
+
test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),reachesTools:input=>getScriptReach(input.code),
|
|
130
|
+
constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{SETTINGS_DEFAULTS,splitIncompleteAnsiSuffix,stripAnsi,writeOutputFile,createOutputFileStream,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,truncateMiddle,createUsageTotals,addUsageToTotals,combineUsage,getSummaryUsage,getSessionUsage,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,truncateToVisualLines,VisualLinePreview,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,
|
|
131
|
+
startToolTimer,toolTimerText,invalidArgText,renderToolPath,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{ENV_PREFIX,getAgentDir,getPackageDir,isBunBinary,isBunRuntime,isBundledNode}from"./chunk-YRCLNWFV.js";import{Compile}from"./chunk-AWCJWXGD.js";import{typebox_exports}from"./chunk-OKALNPTJ.js";var FLOW_ID_PATTERN="^[a-z0-9][a-z0-9_.:-]{0,127}$",FLOW_MODEL_ID_PATTERN="^(?=.{1,128}$)[a-z0-9][a-z0-9_.:-]*(?:/[a-z0-9][a-z0-9_.:-]*)?$",FLOW_DIGEST_PATTERN="^[a-f0-9]{64}$",FLOW_TS_PATTERN="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)$",FLOW_CONTRACT_ERROR_CODES={profile_invalid:"Invalid flow profile",admission_invalid:"Invalid flow run admission",event_invalid:"Invalid flow event",command_invalid:"\
|
|
3
|
+
Invalid flow control command",receipt_invalid:"Invalid flow control receipt",status_invalid:"Invalid flow status",digest_mismatch:"Flow digest mismatch",digest_unverifiable:"Flow digest cannot be verified",canonical_invalid:"Flow data cannot be canonicalized",receipt_conflict:"Flow receipt conflicts with the first receipt"},FlowContractError=class extends Error{code;constructor(code){super(FLOW_CONTRACT_ERROR_CODES[code]),this.name="FlowContractError",this.code=code}},lit=(...values)=>typebox_exports.
|
|
4
|
+
Union(values.map(value=>typebox_exports.Literal(value))),StrictObject=properties=>typebox_exports.Object(properties,{additionalProperties:!1}),FlowIdSchema=typebox_exports.String({pattern:FLOW_ID_PATTERN}),FlowDigestSchema=typebox_exports.String({pattern:FLOW_DIGEST_PATTERN}),DAYS_IN_MONTH=[31,28,31,30,31,30,31,31,30,31,30,31];function isRealCalendarDate(timestamp){let year=Number(timestamp.slice(0,4)),month=Number(timestamp.slice(5,7)),day=Number(timestamp.slice(8,10)),leap=year%4===0&&year%100!==
|
|
5
|
+
0||year%400===0;return day<=(month===2&&leap?29:DAYS_IN_MONTH[month-1]??0)}var FlowTimestampSchema=typebox_exports.Refine(typebox_exports.String({pattern:FLOW_TS_PATTERN}),isRealCalendarDate),FlowMicrousdSchema=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),FlowCountSchema=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),FlowPositiveIntSchema=typebox_exports.Integer({minimum:1,maximum:Number.MAX_SAFE_INTEGER}),FlowModelRefSchema=StrictObject({provider:FlowIdSchema,
|
|
6
|
+
model:typebox_exports.String({pattern:FLOW_MODEL_ID_PATTERN})}),FLOW_ROLES=["scout","worker","implementer","lead","lead_large","architect","reviewer","security_reviewer","qa","triage"],FlowRoleSchema=typebox_exports.Union([typebox_exports.Literal("scout"),typebox_exports.Literal("worker"),typebox_exports.Literal("implementer"),typebox_exports.Literal("lead"),typebox_exports.Literal("lead_large"),typebox_exports.Literal("architect"),typebox_exports.Literal("reviewer"),typebox_exports.Literal("sec\
|
|
7
|
+
urity_reviewer"),typebox_exports.Literal("qa"),typebox_exports.Literal("triage")]),partialByRole=schema=>StrictObject({scout:typebox_exports.Optional(schema),worker:typebox_exports.Optional(schema),implementer:typebox_exports.Optional(schema),lead:typebox_exports.Optional(schema),lead_large:typebox_exports.Optional(schema),architect:typebox_exports.Optional(schema),reviewer:typebox_exports.Optional(schema),security_reviewer:typebox_exports.Optional(schema),qa:typebox_exports.Optional(schema),triage:typebox_exports.
|
|
8
|
+
Optional(schema)});var FlowSizeSchema=typebox_exports.Union([typebox_exports.Literal("small"),typebox_exports.Literal("medium"),typebox_exports.Literal("large")]);var FlowFailureClassSchema=typebox_exports.Union([typebox_exports.Literal("provider_error"),typebox_exports.Literal("provider_unreachable"),typebox_exports.Literal("rate_limit"),typebox_exports.Literal("timeout"),typebox_exports.Literal("check_failed"),typebox_exports.Literal("review_rejected"),typebox_exports.Literal("qa_failed"),typebox_exports.Literal("budget_stop"),typebox_exports.Literal("cancelled"),typebox_exports.Literal("crash"),typebox_exports.Literal("unsafe_scope"),typebox_exports.Literal(
|
|
9
|
+
"stalled"),typebox_exports.Literal("config_invalid"),typebox_exports.Literal("internal"),typebox_exports.Literal("review_verdict_missing"),typebox_exports.Literal("verification_unavailable"),typebox_exports.Literal("unsupported_configuration"),typebox_exports.Literal("blocked"),typebox_exports.Literal("review_findings")]),FlowReasonClassSchema=typebox_exports.Union([FlowFailureClassSchema,typebox_exports.Literal("size_underestimated")]),FlowProfileRefSchema=StrictObject({id:FlowIdSchema,version:FlowPositiveIntSchema,
|
|
10
|
+
digest:FlowDigestSchema});function verifyFlowDigest(hasher,text,expected){let actual;try{actual=hasher.sha256Hex(text)}catch{throw new FlowContractError("digest_unverifiable")}if(typeof actual!="string")throw new FlowContractError("digest_unverifiable");return actual===expected}var MAX_SNAPSHOT_DEPTH=16,MAX_SNAPSHOT_NODES=1e4,MAX_SNAPSHOT_STRING=65536;function isIndexKey(key,length){let index=Number(key);return Number.isInteger(index)&&index>=0&&index<length&&String(index)===key}function snapshotValue(value,depth,budget){
|
|
11
|
+
if(budget.nodes+=1,depth>MAX_SNAPSHOT_DEPTH||budget.nodes>MAX_SNAPSHOT_NODES)throw new Error("bounds");if(value===null||typeof value=="boolean")return value;if(typeof value=="string"){if(value.length>MAX_SNAPSHOT_STRING||!value.isWellFormed())throw new Error("string");return value}if(typeof value=="number"){if(!Number.isFinite(value))throw new Error("number");return value}if(typeof value!="object")throw new Error("type");if(Array.isArray(value)){let length=value.length;if(length>MAX_SNAPSHOT_NODES)
|
|
12
|
+
throw new Error("bounds");for(let key of Reflect.ownKeys(value))if(typeof key!="string"||key!=="length"&&!isIndexKey(key,length))throw new Error("array");let out2=[];for(let index=0;index<length;index+=1){let descriptor=Object.getOwnPropertyDescriptor(value,String(index));if(descriptor===void 0||!("value"in descriptor))throw new Error("array");out2.push(snapshotValue(descriptor.value,depth+1,budget))}return out2}let proto=Object.getPrototypeOf(value);if(proto!==null&&Object.getPrototypeOf(proto)!==
|
|
13
|
+
null)throw new Error("prototype");let out={};for(let key of Reflect.ownKeys(value)){if(typeof key!="string"||!key.isWellFormed())throw new Error("key");let descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor===void 0||!("value"in descriptor)||descriptor.enumerable!==!0)throw new Error("property");descriptor.value!==void 0&&Object.defineProperty(out,key,{value:snapshotValue(descriptor.value,depth+1,budget),enumerable:!0,writable:!0,configurable:!0})}return out}function snapshotFlowData(input){
|
|
14
|
+
return snapshotValue(input,0,{nodes:0})}function parseFlowData(code,input,validate){let snapshot=trySnapshotFlowData(code,input);if(!validate(snapshot))throw new FlowContractError(code);return snapshot}function trySnapshotFlowData(code,input){try{return snapshotFlowData(input)}catch{throw new FlowContractError(code)}}function compileFlow(schema){return Compile(schema)}function modelKey(ref){return`${ref.provider}\0${ref.model}`}function hasDuplicateModels(refs){return new Set(refs.map(modelKey)).
|
|
15
|
+
size!==refs.length}function canonicalFlowJson(value){if(value===null||typeof value=="boolean")return JSON.stringify(value);if(typeof value=="string"){if(!value.isWellFormed())throw new FlowContractError("canonical_invalid");return JSON.stringify(value)}if(typeof value=="number"){if(!Number.isFinite(value))throw new FlowContractError("canonical_invalid");return JSON.stringify(value)}if(Array.isArray(value))return`[${value.map(canonicalFlowJson).join(",")}]`;if(typeof value!="object")throw new FlowContractError(
|
|
16
|
+
"canonical_invalid");let record=value,parts=[];for(let key of Object.keys(record).sort()){if(!key.isWellFormed())throw new FlowContractError("canonical_invalid");record[key]!==void 0&&parts.push(`${JSON.stringify(key)}:${canonicalFlowJson(record[key])}`)}return`{${parts.join(",")}}`}function canonicalWithout(doc,omit){let copy={...doc};return delete copy[omit],canonicalFlowJson(copy)}var SUBAGENT_WORKER_STATUSES=["queued","waiting","running","completed","failed","cancelled","skipped","unresolved"],SUBAGENT_CANCELLATION_OUTCOMES=["none","not_started","direct_worker_terminated","unconfirmed"],SUBAGENT_FAILURE_KINDS=["spawn_failed","process_error","model_error","merge_failed"],SUBAGENT_RUN_MODES=["single","parallel","chain"];var SUBAGENT_PROGRESS_UUID_PATTERN="^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",SUBAGENT_PROGRESS_IDENTIFIER_PATTERN="^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",SUBAGENT_PROGRESS_MODEL_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$",SUBAGENT_PROGRESS_TOOL_CALL_ID_PATTERN="^[\\x21-\\x7E]{1,256}$",SUBAGENT_PROGRESS_TEXT_PATTERN="^[^\\u0000-\\u001F\\u007F-\\u009F\\u00AD\\u034F\\u061C\\u180E\\u200B-\\u200F\\u2028-\\u202E\\u2060-\\u2069\\uFEFF]+$",UUID_REGEX=new RegExp(SUBAGENT_PROGRESS_UUID_PATTERN),
|
|
17
|
+
IDENTIFIER_REGEX=new RegExp(SUBAGENT_PROGRESS_IDENTIFIER_PATTERN),MODEL_REGEX=new RegExp(SUBAGENT_PROGRESS_MODEL_PATTERN),TOOL_CALL_ID_REGEX=new RegExp(SUBAGENT_PROGRESS_TOOL_CALL_ID_PATTERN);function isCanonicalSubagentProgressUuid(value){return typeof value=="string"&&value.length===36&&UUID_REGEX.test(value)}var progressTextEncoder=new TextEncoder;function measureSubagentProgressJson(value){let text;try{text=JSON.stringify(value)}catch{throw invalidSnapshot()}if(typeof text!="string")throw invalidSnapshot();
|
|
18
|
+
return{utf8Bytes:progressTextEncoder.encode(text).length,codeUnits:text.length}}function isForbiddenTextCodeUnit(unit){return unit<=31||unit>=127&&unit<=159||unit===173||unit===847||unit===1564||unit===6158||unit>=8203&&unit<=8207||unit>=8232&&unit<=8238||unit>=8288&&unit<=8297||unit===65279}function isHighSurrogate(unit){return unit>=55296&&unit<=56319}function isLowSurrogate(unit){return unit>=56320&&unit<=57343}function isSubagentPresentationText(value,max){if(typeof value!="string"||value.length===
|
|
19
|
+
0||value.length>max||value!==value.trim())return!1;for(let i=0;i<value.length;i++){let unit=value.charCodeAt(i);if(isHighSurrogate(unit)){if(!isLowSurrogate(value.charCodeAt(i+1)))return!1;i+=1}else if(isLowSurrogate(unit)||isForbiddenTextCodeUnit(unit))return!1}return!0}var SUBAGENT_PRESENTATION_SCAN_WINDOW_CODE_UNITS=4096,WHITESPACE_UNIT_REGEX=/\s/;function isSeparatorAt(input,index){let unit=input.charCodeAt(index);return isHighSurrogate(unit)?!isLowSurrogate(input.charCodeAt(index+1)):isLowSurrogate(
|
|
20
|
+
unit)||isForbiddenTextCodeUnit(unit)||WHITESPACE_UNIT_REGEX.test(input[index])}function toSubagentPresentationText(input,max){if(typeof input!="string"||max<2)return null;let length=input.length,i=0,skipEnd=Math.min(length,SUBAGENT_PRESENTATION_SCAN_WINDOW_CODE_UNITS);for(;i<skipEnd&&isSeparatorAt(input,i);)i+=1;if(i===length||i===skipEnd)return null;let collectEnd=Math.min(length,i+SUBAGENT_PRESENTATION_SCAN_WINDOW_CODE_UNITS),out="",pendingSpace=!1,truncated=!1;for(;i<collectEnd;){if(isSeparatorAt(
|
|
21
|
+
input,i)){pendingSpace=!0,i+=1;continue}let width=isHighSurrogate(input.charCodeAt(i))?2:1;if(out.length+(pendingSpace?1:0)+width>max){truncated=!0;break}pendingSpace&&(out+=" ",pendingSpace=!1),out+=input.slice(i,i+width),i+=width}if(!truncated&&i<length&&(truncated=!0),!truncated)return out;let end=Math.min(out.length,max-1);return isHighSurrogate(out.charCodeAt(end-1))&&(end-=1),out.charCodeAt(end-1)===32&&(end-=1),`${out.slice(0,end)}\u2026`}function invalidSnapshot(){return new Error("Inval\
|
|
22
|
+
id subagent progress snapshot")}function isTerminalStatus(status){return status!=="queued"&&status!=="waiting"&&status!=="running"}function assertWorkerInvariants(worker,runFinal){let{status,attempt,cancelRequested,cancellationOutcome:outcome}=worker,valid=!0;if(status==="unresolved"&&!runFinal&&(valid=!1),runFinal&&!isTerminalStatus(status)&&(valid=!1),status==="unresolved"&&attempt<1&&(valid=!1),status==="unresolved"&&cancelRequested&&outcome!=="unconfirmed"&&(valid=!1),!isTerminalStatus(status)&&
|
|
23
|
+
cancelRequested&&outcome!=="unconfirmed"&&(valid=!1),!cancelRequested&&outcome!=="none"&&(valid=!1),status==="cancelled"?(!cancelRequested||outcome!=="not_started"&&outcome!=="direct_worker_terminated")&&(valid=!1):(outcome==="not_started"||outcome==="direct_worker_terminated")&&(valid=!1),outcome==="not_started"&&attempt!==0&&(valid=!1),outcome==="direct_worker_terminated"&&attempt<1&&(valid=!1),(status==="running"||status==="completed")&&attempt<1&&(valid=!1),(status==="queued"||status==="wait\
|
|
24
|
+
ing"||status==="skipped")&&attempt!==0&&(valid=!1),worker.failureKind!==null&&status!=="failed"&&(valid=!1),worker.resultPreview!==null&&status!=="completed"&&status!=="failed"&&(valid=!1),worker.startedAt!==null!=attempt>=1&&(valid=!1),worker.endedAt!==null&&(worker.startedAt===null||!isTerminalStatus(status)||worker.endedAt<worker.startedAt)&&(valid=!1),!valid)throw invalidSnapshot()}function assertRunInvariants(run){if(run.endedAt!==null!==run.final||run.endedAt!==null&&run.endedAt<run.startedAt)
|
|
25
|
+
throw invalidSnapshot();let workerIds=new Set;for(let worker of run.workers){if(workerIds.has(worker.workerId))throw invalidSnapshot();workerIds.add(worker.workerId),assertWorkerInvariants(worker,run.final)}let size=measureSubagentProgressJson(run);if(size.utf8Bytes>65536||size.codeUnits>65536)throw invalidSnapshot()}var RUN_KEYS=["runId","seq","final","workers","toolCallId","mode","startedAt","endedAt"],WORKER_KEYS=["workerId","attempt","status","cancelRequested","cancellationOutcome","agent","\
|
|
26
|
+
label","task","model","startedAt","endedAt","turns","toolCalls","failureKind","resultPreview"],ENVELOPE_KEYS=["schemaVersion","runtimeId","sessionEpoch","complete","runs"];function readPlainFields(value,keys){if(value===null||typeof value!="object"||Array.isArray(value))throw invalidSnapshot();let proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null||Reflect.ownKeys(value).length!==keys.length)throw invalidSnapshot();let out={};for(let key of keys){let descriptor=Object.getOwnPropertyDescriptor(
|
|
27
|
+
value,key);if(!descriptor?.enumerable||!("value"in descriptor))throw invalidSnapshot();out[key]=descriptor.value}return out}function readPlainArray(value,maxItems){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)throw invalidSnapshot();let length=Object.getOwnPropertyDescriptor(value,"length")?.value;if(typeof length!="number"||!Number.isInteger(length)||length<0||length>maxItems)throw invalidSnapshot();let own=Reflect.ownKeys(value);if(own.length!==length+1||own[length]!==
|
|
28
|
+
"length")throw invalidSnapshot();let out=[];for(let i=0;i<length;i++){if(own[i]!==String(i))throw invalidSnapshot();let descriptor=Object.getOwnPropertyDescriptor(value,i);if(!descriptor?.enumerable||!("value"in descriptor))throw invalidSnapshot();out.push(descriptor.value)}return out}function readUuid(value){if(!isCanonicalSubagentProgressUuid(value))throw invalidSnapshot();return value}function readBoolean(value){if(typeof value!="boolean")throw invalidSnapshot();return value}function readInteger(value,minimum){
|
|
29
|
+
if(typeof value!="number"||!Number.isSafeInteger(value)||value<minimum)throw invalidSnapshot();return value}function readNullableInteger(value){return value===null?null:readInteger(value,0)}function readMember(value,allowed){let member=allowed.find(candidate=>candidate===value);if(member===void 0)throw invalidSnapshot();return member}function readNullableMember(value,allowed){return value===null?null:readMember(value,allowed)}function readNullablePattern(value,pattern){if(value===null)return null;
|
|
30
|
+
if(typeof value!="string"||!pattern.test(value))throw invalidSnapshot();return value}function readNullableText(value,max){if(value===null)return null;if(!isSubagentPresentationText(value,max))throw invalidSnapshot();return value}function readWorker(value){let f=readPlainFields(value,WORKER_KEYS);return{workerId:readUuid(f.workerId),attempt:readInteger(f.attempt,0),status:readMember(f.status,SUBAGENT_WORKER_STATUSES),cancelRequested:readBoolean(f.cancelRequested),cancellationOutcome:readMember(f.
|
|
31
|
+
cancellationOutcome,SUBAGENT_CANCELLATION_OUTCOMES),agent:readNullablePattern(f.agent,IDENTIFIER_REGEX),label:readNullablePattern(f.label,IDENTIFIER_REGEX),task:readNullableText(f.task,120),model:readNullablePattern(f.model,MODEL_REGEX),startedAt:readNullableInteger(f.startedAt),endedAt:readNullableInteger(f.endedAt),turns:readInteger(f.turns,0),toolCalls:readInteger(f.toolCalls,0),failureKind:readNullableMember(f.failureKind,SUBAGENT_FAILURE_KINDS),resultPreview:readNullableText(f.resultPreview,
|
|
32
|
+
160)}}function readRun(value){let f=readPlainFields(value,RUN_KEYS);return{runId:readUuid(f.runId),seq:readInteger(f.seq,1),final:readBoolean(f.final),workers:readPlainArray(f.workers,32).map(readWorker),toolCallId:readNullablePattern(f.toolCallId,TOOL_CALL_ID_REGEX),mode:readMember(f.mode,SUBAGENT_RUN_MODES),startedAt:readInteger(f.startedAt,0),endedAt:readNullableInteger(f.endedAt)}}function readEnvelope(value){let f=readPlainFields(value,ENVELOPE_KEYS);if(f.schemaVersion!==1)throw invalidSnapshot();
|
|
33
|
+
return{schemaVersion:1,runtimeId:readUuid(f.runtimeId),sessionEpoch:readUuid(f.sessionEpoch),complete:readBoolean(f.complete),runs:readPlainArray(f.runs,64).map(readRun)}}function parseSubagentRunSnapshot(value){try{let run=readRun(value);return assertRunInvariants(run),deepFreeze(run)}catch{throw invalidSnapshot()}}function parseSubagentProgressSnapshot(value){try{let snapshot=readEnvelope(value),runIds=new Set,finalized=0;for(let run of snapshot.runs){if(runIds.has(run.runId))throw invalidSnapshot();
|
|
34
|
+
runIds.add(run.runId),run.final&&(finalized+=1),assertRunInvariants(run)}if(finalized>16)throw invalidSnapshot();let size=measureSubagentProgressJson(snapshot);if(size.utf8Bytes>4259840||size.codeUnits>4259840)throw invalidSnapshot();return deepFreeze(snapshot)}catch{throw invalidSnapshot()}}function deepFreeze(value){if(value===null||typeof value!="object"||Object.isFrozen(value))return value;Object.freeze(value);for(let child of Object.values(value))deepFreeze(child);return value}var StrictObject2=properties=>typebox_exports.Object(properties,{additionalProperties:!1}),PositiveInteger=typebox_exports.Integer({minimum:1,maximum:Number.MAX_SAFE_INTEGER}),NonnegativeInteger=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),Digest=typebox_exports.String({pattern:"^[a-f0-9]{64}$"}),ORCHESTRATION_CONTRACT_VERSION=1,ORCHESTRATION_CAPABILITIES=["architect","technical_lead","implementation_fast","implementation_strong","technical_review","security_review"],ORCHESTRATION_EFFORTS=[
|
|
35
|
+
"low","medium","high"],ORCHESTRATION_RISKS=["low","medium","high","critical"],OrchestrationCapabilitySchema=typebox_exports.Union([typebox_exports.Literal(ORCHESTRATION_CAPABILITIES[0]),typebox_exports.Literal(ORCHESTRATION_CAPABILITIES[1]),typebox_exports.Literal(ORCHESTRATION_CAPABILITIES[2]),typebox_exports.Literal(ORCHESTRATION_CAPABILITIES[3]),typebox_exports.Literal(ORCHESTRATION_CAPABILITIES[4]),typebox_exports.Literal(ORCHESTRATION_CAPABILITIES[5])]),OrchestrationEffortSchema=typebox_exports.
|
|
36
|
+
Union([typebox_exports.Literal(ORCHESTRATION_EFFORTS[0]),typebox_exports.Literal(ORCHESTRATION_EFFORTS[1]),typebox_exports.Literal(ORCHESTRATION_EFFORTS[2])]),OrchestrationRiskSchema=typebox_exports.Union([typebox_exports.Literal(ORCHESTRATION_RISKS[0]),typebox_exports.Literal(ORCHESTRATION_RISKS[1]),typebox_exports.Literal(ORCHESTRATION_RISKS[2]),typebox_exports.Literal(ORCHESTRATION_RISKS[3])]),OrchestrationPackageSchema=StrictObject2({route:typebox_exports.String({minLength:1}),effort:OrchestrationEffortSchema,
|
|
37
|
+
contextBudget:PositiveInteger,model:typebox_exports.String({minLength:1}),independentFrom:typebox_exports.Optional(typebox_exports.Array(OrchestrationCapabilitySchema))}),OrchestrationTopologySchema=StrictObject2({maxDepth:typebox_exports.Integer({minimum:1,maximum:3}),maxWorkers:typebox_exports.Integer({minimum:1,maximum:16}),maxConcurrent:typebox_exports.Integer({minimum:1,maximum:8}),maxWorktrees:typebox_exports.Integer({minimum:0,maximum:8})}),OrchestrationRunClassSchema=StrictObject2({taskClass:typebox_exports.
|
|
38
|
+
String({minLength:1}),complexity:typebox_exports.Integer({minimum:1,maximum:10}),risk:OrchestrationRiskSchema,classificationSource:typebox_exports.Union([typebox_exports.Literal("deterministic"),typebox_exports.Literal("classifier"),typebox_exports.Literal("fallback"),typebox_exports.Literal("architect")])}),OrchestrationFeaturesSchema=StrictObject2({adaptiveRouting:typebox_exports.Union([typebox_exports.Literal("off"),typebox_exports.Literal("observe"),typebox_exports.Literal("recommend"),typebox_exports.
|
|
39
|
+
Literal("enforce")]),exploration:typebox_exports.Boolean(),shadowRouting:typebox_exports.Union([typebox_exports.Literal("off"),typebox_exports.Literal("estimate")]),budget:typebox_exports.Union([typebox_exports.Literal("monitor"),typebox_exports.Literal("warn"),typebox_exports.Literal("enforce")]),budgetMicrocents:NonnegativeInteger,timeBudgetMs:NonnegativeInteger,autoMerge:typebox_exports.Literal(!1),destructiveOps:typebox_exports.Literal("deny"),dependencyChanges:typebox_exports.Union([typebox_exports.
|
|
40
|
+
Literal("deny"),typebox_exports.Literal("ask")])}),OrchestrationDecisionV1Schema=StrictObject2({defaultPackage:typebox_exports.Optional(typebox_exports.Record(typebox_exports.String(),OrchestrationPackageSchema)),recommendedPackage:typebox_exports.Optional(typebox_exports.Record(typebox_exports.String(),OrchestrationPackageSchema)),selected:typebox_exports.Union([typebox_exports.Literal("default"),typebox_exports.Literal("recommended"),typebox_exports.Literal("explored"),typebox_exports.Literal(
|
|
41
|
+
"canary")]),sampleCount:NonnegativeInteger,minSamples:PositiveInteger,explored:typebox_exports.Boolean(),canary:typebox_exports.Boolean(),shadowEstimate:typebox_exports.Optional(StrictObject2({costMicrocents:NonnegativeInteger,durationMs:NonnegativeInteger}))}),OrchestrationPolicyV1Schema=StrictObject2({contractVersion:typebox_exports.Literal(ORCHESTRATION_CONTRACT_VERSION),policyId:Digest,runClass:OrchestrationRunClassSchema,topology:OrchestrationTopologySchema,packages:typebox_exports.Record(typebox_exports.
|
|
42
|
+
String(),OrchestrationPackageSchema),agentCapabilities:typebox_exports.Record(typebox_exports.String(),OrchestrationCapabilitySchema),escalation:typebox_exports.Array(OrchestrationCapabilitySchema),verification:StrictObject2({depth:typebox_exports.Union([typebox_exports.Literal("none"),typebox_exports.Literal("targeted"),typebox_exports.Literal("broad"),typebox_exports.Literal("full")]),review:typebox_exports.Union([typebox_exports.Literal("off"),typebox_exports.Literal("sampled"),typebox_exports.
|
|
43
|
+
Literal("risk_based"),typebox_exports.Literal("always")]),gate:typebox_exports.Union([typebox_exports.Literal("off"),typebox_exports.Literal("on")])}),features:OrchestrationFeaturesSchema,decision:OrchestrationDecisionV1Schema,approvedDependencyChanges:typebox_exports.Optional(typebox_exports.Array(typebox_exports.String({minLength:1})))}),OrchestrationPolicyValidator=Compile(OrchestrationPolicyV1Schema),ORCHESTRATION_CAPABILITY_SET=new Set(ORCHESTRATION_CAPABILITIES);var RunOrchestrationDecisionV1Schema=StrictObject2({schemaVersion:typebox_exports.Literal(1),policyId:typebox_exports.Union([Digest,typebox_exports.Null()]),contractVersion:typebox_exports.Literal(ORCHESTRATION_CONTRACT_VERSION),runClass:typebox_exports.Union([OrchestrationRunClassSchema,typebox_exports.Null()]),topology:typebox_exports.Union([OrchestrationTopologySchema,typebox_exports.Null()]),decision:typebox_exports.Union([OrchestrationDecisionV1Schema,typebox_exports.Null()]),degradationReason:typebox_exports.
|
|
44
|
+
Union([typebox_exports.Literal("orchestration-unsupported"),typebox_exports.Literal("orchestration-disabled"),typebox_exports.Null()])}),SubagentTaskEventSchema=typebox_exports.Union([StrictObject2({type:typebox_exports.Literal("schedule"),taskId:typebox_exports.String(),dependsOn:typebox_exports.Array(typebox_exports.String()),ownerPaths:typebox_exports.Array(typebox_exports.String()),baseRevision:typebox_exports.Optional(typebox_exports.String()),at:NonnegativeInteger}),StrictObject2({type:typebox_exports.
|
|
45
|
+
Literal("wait"),taskId:typebox_exports.String(),reason:typebox_exports.Literal("concurrency"),at:NonnegativeInteger}),StrictObject2({type:typebox_exports.Literal("serialize"),taskId:typebox_exports.String(),after:typebox_exports.Array(typebox_exports.String()),at:NonnegativeInteger}),StrictObject2({type:typebox_exports.Literal("start"),taskId:typebox_exports.String(),attempt:PositiveInteger,at:NonnegativeInteger}),StrictObject2({type:typebox_exports.Literal("complete"),taskId:typebox_exports.String(),
|
|
46
|
+
attempt:PositiveInteger,at:NonnegativeInteger}),StrictObject2({type:typebox_exports.Literal("fail"),taskId:typebox_exports.String(),attempt:PositiveInteger,reason:typebox_exports.String(),at:NonnegativeInteger}),StrictObject2({type:typebox_exports.Literal("escalate"),taskId:typebox_exports.String(),fromAttempt:PositiveInteger,toAttempt:PositiveInteger,model:typebox_exports.Optional(typebox_exports.String()),thinking:typebox_exports.Optional(typebox_exports.String()),at:NonnegativeInteger}),StrictObject2(
|
|
47
|
+
{type:typebox_exports.Literal("skip"),taskId:typebox_exports.String(),failedDependency:typebox_exports.String(),at:NonnegativeInteger})]),SubagentTaskEventValidator=Compile(SubagentTaskEventSchema);var SubagentIdentityEnvelopeSchema=StrictObject2({taskId:typebox_exports.Optional(typebox_exports.String({minLength:1})),parentTaskId:typebox_exports.Optional(typebox_exports.String({minLength:1})),depth:typebox_exports.Optional(typebox_exports.Integer({minimum:1,maximum:3}))}),ProgressUuid=typebox_exports.String({pattern:SUBAGENT_PROGRESS_UUID_PATTERN,minLength:36,maxLength:36}),Nullable=schema=>typebox_exports.Union([schema,typebox_exports.Null()]),ProgressIdentifier=Nullable(typebox_exports.String(
|
|
48
|
+
{pattern:SUBAGENT_PROGRESS_IDENTIFIER_PATTERN,minLength:1,maxLength:64})),ProgressModel=Nullable(typebox_exports.String({pattern:SUBAGENT_PROGRESS_MODEL_PATTERN,minLength:1,maxLength:128})),ProgressToolCallId=Nullable(typebox_exports.String({pattern:SUBAGENT_PROGRESS_TOOL_CALL_ID_PATTERN,minLength:1,maxLength:256})),ProgressText=maxLength=>Nullable(typebox_exports.String({pattern:SUBAGENT_PROGRESS_TEXT_PATTERN,minLength:1,maxLength})),SubagentWorkerStatusSchema=typebox_exports.Union([typebox_exports.
|
|
49
|
+
Literal(SUBAGENT_WORKER_STATUSES[0]),typebox_exports.Literal(SUBAGENT_WORKER_STATUSES[1]),typebox_exports.Literal(SUBAGENT_WORKER_STATUSES[2]),typebox_exports.Literal(SUBAGENT_WORKER_STATUSES[3]),typebox_exports.Literal(SUBAGENT_WORKER_STATUSES[4]),typebox_exports.Literal(SUBAGENT_WORKER_STATUSES[5]),typebox_exports.Literal(SUBAGENT_WORKER_STATUSES[6]),typebox_exports.Literal(SUBAGENT_WORKER_STATUSES[7])]),SubagentCancellationOutcomeSchema=typebox_exports.Union([typebox_exports.Literal(SUBAGENT_CANCELLATION_OUTCOMES[0]),
|
|
50
|
+
typebox_exports.Literal(SUBAGENT_CANCELLATION_OUTCOMES[1]),typebox_exports.Literal(SUBAGENT_CANCELLATION_OUTCOMES[2]),typebox_exports.Literal(SUBAGENT_CANCELLATION_OUTCOMES[3])]),SubagentFailureKindSchema=typebox_exports.Union([typebox_exports.Literal(SUBAGENT_FAILURE_KINDS[0]),typebox_exports.Literal(SUBAGENT_FAILURE_KINDS[1]),typebox_exports.Literal(SUBAGENT_FAILURE_KINDS[2]),typebox_exports.Literal(SUBAGENT_FAILURE_KINDS[3]),typebox_exports.Null()]),SubagentRunModeSchema=typebox_exports.Union(
|
|
51
|
+
[typebox_exports.Literal(SUBAGENT_RUN_MODES[0]),typebox_exports.Literal(SUBAGENT_RUN_MODES[1]),typebox_exports.Literal(SUBAGENT_RUN_MODES[2])]),SubagentWorkerSnapshotSchema=StrictObject2({workerId:ProgressUuid,attempt:NonnegativeInteger,status:SubagentWorkerStatusSchema,cancelRequested:typebox_exports.Boolean(),cancellationOutcome:SubagentCancellationOutcomeSchema,agent:ProgressIdentifier,label:ProgressIdentifier,task:ProgressText(120),model:ProgressModel,startedAt:Nullable(NonnegativeInteger),endedAt:Nullable(
|
|
52
|
+
NonnegativeInteger),turns:NonnegativeInteger,toolCalls:NonnegativeInteger,failureKind:SubagentFailureKindSchema,resultPreview:ProgressText(160)}),SubagentRunSnapshotSchema=StrictObject2({runId:ProgressUuid,seq:PositiveInteger,final:typebox_exports.Boolean(),workers:typebox_exports.Array(SubagentWorkerSnapshotSchema,{maxItems:32}),toolCallId:ProgressToolCallId,mode:SubagentRunModeSchema,startedAt:NonnegativeInteger,endedAt:Nullable(NonnegativeInteger)}),SubagentProgressSnapshotSchema=StrictObject2(
|
|
53
|
+
{schemaVersion:typebox_exports.Literal(1),runtimeId:ProgressUuid,sessionEpoch:ProgressUuid,complete:typebox_exports.Boolean(),runs:typebox_exports.Array(SubagentRunSnapshotSchema,{maxItems:64})});var HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION=1,HUMAIN_AGENT_ARTIFACT_KINDS=["candidate-patch","dependency-output","source-observation","validation-report"],StrictObject3=properties=>typebox_exports.Object(properties,{additionalProperties:!1}),StableIdentifier=typebox_exports.String({minLength:1,maxLength:256}),PositiveInteger2=typebox_exports.Integer({minimum:1,maximum:Number.MAX_SAFE_INTEGER}),NonnegativeInteger2=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),Digest2=typebox_exports.
|
|
54
|
+
String({pattern:"^[a-f0-9]{64}$"}),SafeArtifactReference=typebox_exports.String({minLength:1,maxLength:512,pattern:"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$"}),HumainAgentRouteRefSchema=typebox_exports.Union([typebox_exports.Literal("route:fast"),typebox_exports.Literal("route:balanced"),typebox_exports.Literal("route:thorough")]),HumainAgentArtifactSchema=StrictObject3({id:StableIdentifier,kind:typebox_exports.Union([typebox_exports.Literal(HUMAIN_AGENT_ARTIFACT_KINDS[0]),
|
|
55
|
+
typebox_exports.Literal(HUMAIN_AGENT_ARTIFACT_KINDS[1]),typebox_exports.Literal(HUMAIN_AGENT_ARTIFACT_KINDS[2]),typebox_exports.Literal(HUMAIN_AGENT_ARTIFACT_KINDS[3])]),reference:SafeArtifactReference,digest:Digest2}),HumainAgentExecutionControlsSchema=StrictObject3({maxConcurrency:typebox_exports.Integer({minimum:1,maximum:16}),maxDepth:typebox_exports.Integer({minimum:1,maximum:16}),depth:typebox_exports.Integer({minimum:0,maximum:16}),timeoutMs:typebox_exports.Integer({minimum:1,maximum:864e5})}),
|
|
56
|
+
HumainAgentExecutionClaimSchema=StrictObject3({workUnitId:StableIdentifier,nodeId:StableIdentifier,attemptNumber:PositiveInteger2,attemptFence:PositiveInteger2,segmentFence:PositiveInteger2,routeRef:HumainAgentRouteRefSchema,task:typebox_exports.String({minLength:1,maxLength:1e5}),controls:HumainAgentExecutionControlsSchema,input:StrictObject3({artifacts:typebox_exports.Array(HumainAgentArtifactSchema,{maxItems:16})})}),HumainAgentExecutionRequestSchema=StrictObject3({schemaVersion:typebox_exports.
|
|
57
|
+
Literal(HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION),kind:typebox_exports.Literal("execute"),mode:typebox_exports.Union([typebox_exports.Literal("node"),typebox_exports.Literal("workflow")]),invocationId:StableIdentifier,batchId:typebox_exports.Optional(StableIdentifier),claims:typebox_exports.Array(HumainAgentExecutionClaimSchema,{minItems:1,maxItems:8})}),HumainAgentUsageSchema=typebox_exports.Union([StrictObject3({status:typebox_exports.Literal("unknown")}),StrictObject3({status:typebox_exports.Literal(
|
|
58
|
+
"measured"),totalCalls:typebox_exports.Optional(NonnegativeInteger2),totalTurns:typebox_exports.Optional(NonnegativeInteger2),totalTokens:NonnegativeInteger2,costMicrocents:NonnegativeInteger2})]),HUMAIN_AGENT_EXECUTION_FAILURE_CODES=["adapter_execution_failed","incompatible_adapter_capability","invalid_adapter_result","invalid_execution_request","provider_timeout","provider_unavailable","reused_execution_context","transport_interrupted"],HumainAgentExecutionFailureCodeSchema=typebox_exports.Union(
|
|
59
|
+
[typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[0]),typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[1]),typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[2]),typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[3]),typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[4]),typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[5]),typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[6]),typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_FAILURE_CODES[7])]),
|
|
60
|
+
OutcomeIdentity={workUnitId:StableIdentifier,nodeId:StableIdentifier,attemptNumber:PositiveInteger2,attemptFence:PositiveInteger2,segmentFence:PositiveInteger2},HumainAgentExecutionOutcomeSchema=typebox_exports.Union([StrictObject3({...OutcomeIdentity,kind:typebox_exports.Literal("succeeded"),output:StrictObject3({summary:typebox_exports.String({minLength:1,maxLength:512}),artifacts:typebox_exports.Array(HumainAgentArtifactSchema,{maxItems:16})}),usage:HumainAgentUsageSchema}),StrictObject3({...OutcomeIdentity,
|
|
61
|
+
kind:typebox_exports.Literal("failed"),failureCode:HumainAgentExecutionFailureCodeSchema,usage:HumainAgentUsageSchema}),StrictObject3({...OutcomeIdentity,kind:typebox_exports.Literal("cancelled"),terminationConfirmed:typebox_exports.Boolean(),usage:HumainAgentUsageSchema})]),HumainAgentExecutionResponseSchema=StrictObject3({schemaVersion:typebox_exports.Literal(HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION),kind:typebox_exports.Literal("result"),mode:typebox_exports.Union([typebox_exports.Literal("node"),
|
|
62
|
+
typebox_exports.Literal("workflow")]),invocationId:StableIdentifier,batchId:typebox_exports.Optional(StableIdentifier),termination:typebox_exports.Union([typebox_exports.Literal("not-requested"),typebox_exports.Literal("confirmed"),typebox_exports.Literal("unconfirmed")]),outcomes:typebox_exports.Array(HumainAgentExecutionOutcomeSchema,{minItems:1,maxItems:8})}),RequestValidator=Compile(HumainAgentExecutionRequestSchema),ResponseValidator=Compile(HumainAgentExecutionResponseSchema),ArtifactReferenceValidator=Compile(
|
|
63
|
+
SafeArtifactReference);function isSafeHumainAgentExecutionSummary(value){return typeof value=="string"&&value.length>=1&&value.length<=512&&value===value.trim()&&/^[\p{L}\p{N}][\p{L}\p{N} .,;:!?()&'-]*$/u.test(value)&&!/\b(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}(?::\d{1,5})?\b/u.test(value)&&!/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d{1,5})?\b/u.test(value)&&!/^(?:rm|curl|wget|sh|bash|zsh|fish|pwsh|powershell|cmd|node|bun|deno|npx|npm|pnpm|yarn|python(?:3)?|perl|ruby|git|docker|kubectl|ssh|scp|sudo|cat|ls|cd|mkdir|touch|chmod|chown|env|export|set|eval|exec)\b/iu.
|
|
64
|
+
test(value)&&!/\b(?:api[- ]?key|secret|token|credential|password)\s*:/iu.test(value)&&!/\b(?:claude|gpt|gemini|llama|mistral|zai|glm|qwen|deepseek|grok|nova|o\d+)[-_.:][A-Za-z0-9._:-]+\b/iu.test(value)}function parseHumainAgentExecutionRequest(input){if(!RequestValidator.Check(input))throw new Error("Invalid HUMAIN agent execution request");if(input.mode==="node"&&(input.claims.length!==1||input.batchId!==void 0))throw new Error("Invalid HUMAIN agent execution request: node mode requires one cla\
|
|
65
|
+
im and no batch identity");if(input.mode==="workflow"&&input.batchId===void 0)throw new Error("Invalid HUMAIN agent execution request: workflow mode requires a batch identity");let workUnitIds=new Set(input.claims.map(({workUnitId})=>workUnitId)),nodeIds=new Set(input.claims.map(({nodeId})=>nodeId));if(workUnitIds.size!==input.claims.length||nodeIds.size!==input.claims.length)throw new Error("Invalid HUMAIN agent execution request: claim identities must be unique");if(input.claims.some(({controls})=>controls.
|
|
66
|
+
depth>=controls.maxDepth))throw new Error("Invalid HUMAIN agent execution request: delegation depth limit is exhausted");return deepFreeze2(structuredClone(input))}function parseHumainAgentExecutionResponse(requestInput,responseInput){let request=parseHumainAgentExecutionRequest(requestInput);if(!ResponseValidator.Check(responseInput))throw new Error("Invalid HUMAIN agent execution response");let response=responseInput;if(response.outcomes.some(outcome=>outcome.kind==="succeeded"&&!isSafeHumainAgentExecutionSummary(
|
|
67
|
+
outcome.output.summary)))throw new Error("Invalid HUMAIN agent execution response");if(response.mode!==request.mode||response.invocationId!==request.invocationId||response.batchId!==request.batchId)throw new Error("HUMAIN agent result envelope mismatch");if(response.outcomes.length!==request.claims.length)throw new Error("HUMAIN agent result cardinality mismatch");for(let[index,outcome]of response.outcomes.entries()){let claim=request.claims[index];if(!claim||outcome.workUnitId!==claim.workUnitId||
|
|
68
|
+
outcome.nodeId!==claim.nodeId||outcome.attemptNumber!==claim.attemptNumber||outcome.attemptFence!==claim.attemptFence||outcome.segmentFence!==claim.segmentFence)throw new Error("HUMAIN agent result identity mismatch")}let cancelled=response.outcomes.filter(outcome=>outcome.kind==="cancelled"),expectedTermination=cancelled.length===0?"not-requested":cancelled.every(outcome=>outcome.terminationConfirmed)?"confirmed":"unconfirmed";if(response.termination!==expectedTermination)throw new Error("HUMAI\
|
|
69
|
+
N agent result termination evidence mismatch");return deepFreeze2(structuredClone(response))}function deepFreeze2(value){if(value===null||typeof value!="object"||Object.isFrozen(value))return value;Object.freeze(value);for(let child of Object.values(value))deepFreeze2(child);return value}import{join}from"node:path";import{fileURLToPath}from"node:url";var COORDINATION_BROKER_COMMAND="__humain-coordination-broker",COORDINATION_ROLE_ENV=`${ENV_PREFIX}_INTERNAL_ROLE`,COORDINATION_ROLE="coordination-broker",REPOSITORY_KEY=/^[a-f0-9]{16}$/;function detectLaunchRuntime(){return isBunBinary?"bun-binary":isBundledNode?"bundled-node":isBunRuntime?"bun-source":"node-source"}function getInternalCommandLaunchSpec(runtime,tail,execPath=process.execPath){let cliSource=fileURLToPath(new URL("../../cli.ts",import.meta.url));switch(runtime){case"bun-binary":return{
|
|
70
|
+
command:execPath,args:tail};case"bundled-node":return{command:execPath,args:[join(getPackageDir(),"dist","bundle","cli.js"),...tail]};case"bun-source":return{command:execPath,args:[cliSource,...tail]};case"node-source":return{command:execPath,args:["--import",new URL("../../experimental/source-resolver.ts",import.meta.url).href,cliSource,...tail]}}}function getBrokerLaunchSpec(runtime,repositoryKey,execPath=process.execPath){if(!REPOSITORY_KEY.test(repositoryKey))throw new Error(`Invalid reposit\
|
|
71
|
+
ory key: ${repositoryKey}`);return getInternalCommandLaunchSpec(runtime,[COORDINATION_BROKER_COMMAND,repositoryKey],execPath)}import{createHash as createHash2}from"node:crypto";import{mkdirSync as mkdirSync2,realpathSync as realpathSync2}from"node:fs";import{join as join3}from"node:path";import{createHash}from"node:crypto";import{chmodSync,closeSync,constants,fchmodSync,fstatSync,lstatSync,mkdirSync,openSync,realpathSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";var COORDINATION_DIR_MODE=448,COORDINATION_FILE_MODE=384,COORDINATION_PROTOCOL_NAME="humain-coordination",COORDINATION_PROTOCOL_VERSION=2,MAX_MESSAGE_TEXT_BYTES=65536,MAX_SOCKET_PATH_BYTES=100,REPOSITORY_KEY2=/^[a-f0-9]{16}$/,canonicalTmpDir;function getCanonicalTmpDir(){return canonicalTmpDir??=
|
|
72
|
+
realpathSync("/tmp"),canonicalTmpDir}function assertRepositoryKey(repositoryKey){if(repositoryKey!=="device"&&!REPOSITORY_KEY2.test(repositoryKey))throw new Error(`Invalid repository key: ${repositoryKey}`)}function getCoordinationRuntimePaths(agentDir,repositoryKey,uid=process.getuid?.()??0){assertRepositoryKey(repositoryKey);let runtimeDir=join2(agentDir,"coordination",repositoryKey),defaultSocket=join2(runtimeDir,"broker.sock"),socketPath=Buffer.byteLength(defaultSocket,"utf8")<=MAX_SOCKET_PATH_BYTES?
|
|
73
|
+
defaultSocket:join2(getCanonicalTmpDir(),`humain-coord-${uid}`,`${repositoryKey==="device"?`${createHash("sha256").update(agentDir).digest("hex").slice(0,16)}-device`:repositoryKey}.sock`);return{runtimeDir,socketPath,pidPath:join2(runtimeDir,"broker.pid"),spawnLockPath:join2(runtimeDir,"broker.spawn.lock"),mailboxPath:join2(runtimeDir,"mailbox.json"),pendingAsksDir:join2(runtimeDir,"pending-asks"),artifactsDir:join2(runtimeDir,"artifacts")}}function currentUid(){return process.getuid?.()}function resolveCoordinationRuntimePaths(agentDir,repositoryKey,uid){
|
|
74
|
+
assertRepositoryKey(repositoryKey),mkdirSync(agentDir,{recursive:!0,mode:COORDINATION_DIR_MODE});let canonicalAgentDir=realpathSync(agentDir);return assertSafeAncestors(join2(canonicalAgentDir,"coordination"),uid??currentUid()),getCoordinationRuntimePaths(canonicalAgentDir,repositoryKey,uid)}function assertOwnedByUser(path,stats,uid){if(uid!==void 0&&stats.uid!==uid)throw new Error(`Refusing to use ${path}: it is owned by uid ${stats.uid}, not the current user (uid ${uid})`)}function assertRealDirectory(path,stats,uid){
|
|
75
|
+
if(stats.isSymbolicLink())throw new Error(`Refusing to use ${path}: it is a symbolic link`);if(!stats.isDirectory())throw new Error(`Refusing to use ${path}: it is not a directory`);assertOwnedByUser(path,stats,uid)}var STICKY_BIT=512,GROUP_OTHER_WRITE=18;function assertSafeAncestors(dir,uid=currentUid()){let current=realpathSync(dirname(resolve(dir)));for(;;){let stats=lstatSync(current);if(!stats.isDirectory())throw new Error(`Refusing to use ${dir}: ancestor ${current} is not a directory`);if(uid!==
|
|
76
|
+
void 0&&stats.uid!==uid&&stats.uid!==0)throw new Error(`Refusing to use ${dir}: ancestor ${current} is owned by uid ${stats.uid}, not the current user (uid ${uid}) or root`);if((stats.mode&GROUP_OTHER_WRITE)!==0&&(stats.mode&STICKY_BIT)===0){let mode=(stats.mode&4095).toString(8).padStart(4,"0");throw new Error(`Refusing to use ${dir}: ancestor ${current} is writable by other users (mode ${mode}) without the sticky bit`)}let parent=dirname(current);if(parent===current)return;current=parent}}function assertCanonicalRuntimeDir(runtimeDir){
|
|
77
|
+
if(resolve(runtimeDir)!==runtimeDir)throw new Error(`Refusing to use ${runtimeDir}: it is not canonical (not an absolute, normalized path); derive paths with resolveCoordinationRuntimePaths`);let existing=runtimeDir;for(;;){try{lstatSync(existing);break}catch(error){if(error.code!=="ENOENT")throw error}let parent=dirname(existing);if(parent===existing)break;existing=parent}let canonical=realpathSync(existing);if(canonical!==existing)throw new Error(`Refusing to use ${runtimeDir}: ${existing} is \
|
|
78
|
+
not canonical (it resolves through a symbolic link or is not absolute, to ${canonical}); derive paths with resolveCoordinationRuntimePaths`)}function ensureRuntimeDir(dir,uid=currentUid()){mkdirSync(dir,{recursive:!0,mode:COORDINATION_DIR_MODE}),assertSafeAncestors(dir,uid);let checked=lstatSync(dir);assertRealDirectory(dir,checked,uid);let fd=openSync(dir,constants.O_RDONLY|constants.O_DIRECTORY|constants.O_NOFOLLOW);try{let opened=fstatSync(fd);if(opened.dev!==checked.dev||opened.ino!==checked.
|
|
79
|
+
ino)throw new Error(`Refusing to use ${dir}: it changed while being verified`);if(fchmodSync(fd,COORDINATION_DIR_MODE),(fstatSync(fd).mode&63)!==0)throw new Error(`Refusing to use ${dir}: its permissions could not be restricted to owner-only`)}finally{closeSync(fd)}}function ensureCoordinationRuntimeDir(paths,uid=currentUid()){ensureRuntimeDir(dirname(paths.runtimeDir),uid),ensureRuntimeDir(paths.runtimeDir,uid);let socketDir=dirname(paths.socketPath);socketDir!==paths.runtimeDir&&ensureRuntimeDir(
|
|
80
|
+
socketDir,uid)}function assertPrivateSocket(socketPath,uid=currentUid()){let parent=dirname(socketPath),parentStats=lstatSync(parent);if(assertRealDirectory(parent,parentStats,uid),(parentStats.mode&63)!==0)throw new Error(`Refusing to connect to ${socketPath}: directory ${parent} is accessible to other users`);let socketStats=lstatSync(socketPath);if(!socketStats.isSocket())throw new Error(`Refusing to connect to ${socketPath}: it is not a socket`);assertOwnedByUser(socketPath,socketStats,uid)}
|
|
81
|
+
function restrictRuntimeFile(filePath){chmodSync(filePath,COORDINATION_FILE_MODE)}var AGENT_MONITOR_PROTOCOL={name:"humain-agent-monitor",version:1},AGENT_MONITOR_COMMAND="__humain-agent-monitor",AGENT_MONITOR_ROLE="agent-monitor",MAX_REPORT_FRAME_BYTES=64*1024,MAX_SNAPSHOT_FRAME_BYTES=256*1024,MAX_AGENTS=512,MAX_CHILDREN=32,MAX_TEXT=160,MAX_PATH_TEXT=1024,MAX_ID=256,MAX_SOCKET_PATH_BYTES2=100;function resolveAgentMonitorPaths(agentDir,uid=process.getuid?.()){mkdirSync2(agentDir,{recursive:!0,mode:COORDINATION_DIR_MODE});let runtimeDir=join3(realpathSync2(agentDir),"agent-mon\
|
|
82
|
+
itor","run");assertSafeAncestors(join3(runtimeDir,".."),uid);let defaultSocket=join3(runtimeDir,"monitor.sock"),hash=createHash2("sha256").update(runtimeDir).digest("hex").slice(0,16),socketPath=Buffer.byteLength(defaultSocket,"utf8")<=MAX_SOCKET_PATH_BYTES2?defaultSocket:join3(getCanonicalTmpDir(),`humain-agent-monitor-${uid??0}`,`${hash}.sock`);return{runtimeDir,socketPath,pidPath:join3(runtimeDir,"monitor.pid"),spawnLockPath:join3(runtimeDir,"monitor.spawn.lock")}}function cleanText(value,max=MAX_TEXT){
|
|
83
|
+
return toSubagentPresentationText(value,max)??void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isTime(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function isId(value){return typeof value=="string"&&value.length>0&&value.length<=MAX_ID}function isPid(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>0}var MODES=["tui","print","json","rpc"],TOOLS=["humain","claude","codex"],STATUSES=["\
|
|
84
|
+
attention","working","idle","unknown"];function parseHello(value){if(!(!isRecord(value)||value.type!=="hello")&&!(typeof value.protocol!="string"||typeof value.version!="number"||!isPid(value.pid)))return{type:"hello",protocol:value.protocol,version:value.version,pid:value.pid}}function parseReport(value){if(!isRecord(value)||value.type!=="report"||!isRecord(value.session)||!Array.isArray(value.children)||value.children.length>MAX_CHILDREN||value.truncated!==void 0&&typeof value.truncated!="bool\
|
|
85
|
+
ean")return;let session=value.session,mode=MODES.find(candidate=>candidate===session.mode);if("mode"in session&&!mode||!isId(session.id)||!isTime(session.updatedAt))return;let status=session.status;if(status!=="attention"&&status!=="working"&&status!=="idle")return;let children=[];for(let child of value.children){if(!isRecord(child)||!isId(child.id)||!isTime(child.updatedAt))return;children.push({id:child.id,name:cleanText(child.name)??"subagent",updatedAt:child.updatedAt})}let reason=status==="\
|
|
86
|
+
attention"?cleanText(session.reason):void 0;return{type:"report",session:{id:session.id,...mode!==void 0?{mode}:{},name:cleanText(session.name)??"Unnamed session",cwd:cleanText(session.cwd,MAX_PATH_TEXT)??"",status,...reason!==void 0?{reason}:{},updatedAt:session.updatedAt},children,...value.truncated!==void 0?{truncated:value.truncated}:{}}}function parseRow(value){if(!isRecord(value)||!isId(value.id)||!isPid(value.pid)||!isTime(value.updatedAt))return;let mode=MODES.find(candidate=>candidate===
|
|
87
|
+
value.mode);if("mode"in value&&!mode)return;let tool=TOOLS.find(candidate=>candidate===value.tool),status=STATUSES.find(candidate=>candidate===value.status);if(!tool||!status||value.source!=="native"&&value.source!=="process"||value.parentId!==void 0&&!isId(value.parentId))return;let cwd=cleanText(value.cwd,MAX_PATH_TEXT),reason=cleanText(value.reason);return{id:value.id,...value.parentId!==void 0?{parentId:value.parentId}:{},tool,...mode!==void 0?{mode}:{},name:cleanText(value.name)??"agent",...cwd!==
|
|
88
|
+
void 0?{cwd}:{},pid:value.pid,status,...reason!==void 0?{reason}:{},updatedAt:value.updatedAt,source:value.source}}function parseSnapshot(value){if(!isRecord(value)||value.type!=="snapshot"||!Array.isArray(value.agents)||value.agents.length>MAX_AGENTS||value.coverage!=="complete"&&value.coverage!=="partial")return;let agents=[];for(let candidate of value.agents){let row=parseRow(candidate);if(!row)return;agents.push(row)}let note=cleanText(value.note);return{type:"snapshot",agents,coverage:value.
|
|
89
|
+
coverage,...note!==void 0?{note}:{}}}import{lstatSync as lstatSync2,unlinkSync as unlinkSync2}from"node:fs";import net from"node:net";import{randomBytes}from"node:crypto";import{closeSync as closeSync2,constants as constants2,fchmodSync as fchmodSync2,fstatSync as fstatSync2,fsyncSync,linkSync,openSync as openSync2,readSync,renameSync,unlinkSync,writeSync}from"node:fs";import{dirname as dirname2}from"node:path";var MAX_RUNTIME_TEXT_FILE_BYTES=4096;function fsyncDirectory(dir){let fd;try{fd=openSync2(dir,constants2.O_RDONLY),fsyncSync(fd)}catch{}finally{if(fd!==void 0)try{closeSync2(fd)}catch{}}}function removeQuietly(path){try{unlinkSync(path)}catch{}}function errorCode(error){if(!(typeof error!="object"||error===null||!("code"in error)))return typeof error.code=="string"?error.code:void 0}function writeAll(fd,body){let offset=0;for(;offset<body.length;)offset+=writeSync(fd,body,offset)}function temporaryPathFor(path){
|
|
90
|
+
return`${path}.${randomBytes(6).toString("hex")}.tmp`}function writeBytesAtomic(path,body){let tempPath=temporaryPathFor(path),fd=openSync2(tempPath,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL,COORDINATION_FILE_MODE),fdOpen=!0,renamed=!1;try{writeAll(fd,body),fchmodSync2(fd,COORDINATION_FILE_MODE),fsyncSync(fd),fdOpen=!1,closeSync2(fd),renameSync(tempPath,path),renamed=!0}finally{if(fdOpen)try{closeSync2(fd)}catch{}renamed||removeQuietly(tempPath)}fsyncDirectory(dirname2(path))}function writeJsonAtomic(path,value,maxBytes){
|
|
91
|
+
writeTextAtomic(path,`${JSON.stringify(value)}
|
|
92
|
+
`,maxBytes)}function writeTextAtomic(path,text,maxBytes){let body=Buffer.from(text,"utf8");if(body.length>maxBytes)throw new Error(`Snapshot exceeds ${maxBytes} bytes`);writeBytesAtomic(path,body)}function createFileExclusive(path,content){let body=Buffer.from(content,"utf8"),tempPath=temporaryPathFor(path),fd=openSync2(tempPath,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL,COORDINATION_FILE_MODE);try{try{writeAll(fd,body),fchmodSync2(fd,COORDINATION_FILE_MODE)}finally{closeSync2(fd)}
|
|
93
|
+
return linkSync(tempPath,path),!0}catch(error){if(errorCode(error)==="EEXIST")return!1;throw error}finally{removeQuietly(tempPath)}}function readBoundedTextFile(path,maxBytes){let fd;try{fd=openSync2(path,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK)}catch(error){if(errorCode(error)==="ENOENT")return;throw error}try{let stats=fstatSync2(fd);if(!stats.isFile())throw new Error(`${path} is not a regular file`);if(stats.size>maxBytes)throw new Error(`${path} exceeds ${maxBytes} by\
|
|
94
|
+
tes`);let limit=Math.min(stats.size,maxBytes)+1,buffer=Buffer.allocUnsafe(limit),length=0;for(;length<limit;){let read=readSync(fd,buffer,length,limit-length,null);if(read===0)break;length+=read}if(length>stats.size)throw new Error(`${path} changed while being read`);return{text:buffer.toString("utf8",0,length),dev:stats.dev,ino:stats.ino,mtimeMs:stats.mtimeMs}}finally{closeSync2(fd)}}function readTextFile(path,maxBytes){return readBoundedTextFile(path,maxBytes)?.text}function readJsonFile(path,maxBytes){
|
|
95
|
+
let file=readBoundedTextFile(path,maxBytes);return file===void 0?void 0:JSON.parse(file.text)}function framePayloadBytes(msg){return Buffer.byteLength(JSON.stringify(msg),"utf-8")}var MAX_SOCKET_WRITE_BACKLOG_BYTES=8*1024*1024;function writeMessage(socket,msg){let json=JSON.stringify(msg),payloadLength=Buffer.byteLength(json,"utf-8"),frame=Buffer.allocUnsafeSlow(4+payloadLength);frame.writeUInt32BE(payloadLength,0),frame.write(json,4,payloadLength,"utf-8"),socket.write(frame),socket.writableLength>MAX_SOCKET_WRITE_BACKLOG_BYTES&&socket.destroy()}function createMessageReader(onMessage,onError,maxFrameBytes=1048576){
|
|
96
|
+
let header=Buffer.allocUnsafe(4),headerBytes=0,payload=null,payloadBytes=0,payloadLength=0;function reportMessage(framePayload){let msg;try{msg=JSON.parse(framePayload.toString("utf-8"))}catch(error){let message=error instanceof Error?error.message:String(error);return onError(new Error(`Failed to parse intercom message: ${message}`,{cause:error})),!1}try{return onMessage(msg),!0}catch(error){let message=error instanceof Error?error.message:String(error);return onError(new Error(`Failed to handl\
|
|
97
|
+
e intercom message: ${message}`,{cause:error})),!1}}return data=>{let offset=0;for(;offset<data.length;){if(headerBytes<4){let bytes2=Math.min(4-headerBytes,data.length-offset);if(data.copy(header,headerBytes,offset,offset+bytes2),headerBytes+=bytes2,offset+=bytes2,headerBytes<4)return;if(payloadLength=header.readUInt32BE(0),payloadLength>maxFrameBytes){headerBytes=0,onError(new Error(`Intercom frame length ${payloadLength} exceeds maximum ${maxFrameBytes} bytes`));return}}if(payloadBytes===0&&data.
|
|
98
|
+
length-offset>=payloadLength){let framePayload2=data.subarray(offset,offset+payloadLength);if(offset+=payloadLength,headerBytes=0,payload=null,payloadLength=0,!reportMessage(framePayload2))return;continue}(payload===null||payload.length!==payloadLength)&&(payload=Buffer.allocUnsafe(payloadLength));let bytes=Math.min(payloadLength-payloadBytes,data.length-offset);if(data.copy(payload,payloadBytes,offset,offset+bytes),payloadBytes+=bytes,offset+=bytes,payloadBytes<payloadLength)return;let framePayload=payload;
|
|
99
|
+
if(headerBytes=0,payload=null,payloadBytes=0,payloadLength=0,!reportMessage(framePayload))return}}}import{execFile}from"node:child_process";import{readlink}from"node:fs/promises";import{basename}from"node:path";import{promisify}from"node:util";var execFileAsync=promisify(execFile),PS_TIMEOUT_MS=2e3,PS_MAX_BYTES=8*1024*1024,CWD_TIMEOUT_MS=2e3,UNAVAILABLE_NOTE="Claude Code and Codex discovery is unavailable.",TOOL_NAMES={claude:"Claude Code",codex:"Codex"},NO_TTY=new Set(["?","??","-"]),LINE=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+([A-Z][a-z]{2}\s+[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.*)$/;
|
|
100
|
+
function parsePsOutput(stdout){let entries=[];for(let line of stdout.split(`
|
|
101
|
+
`)){let match=LINE.exec(line);if(!match)continue;let tool=classifyProcess(match[6]??"");entries.push({uid:Number(match[1]),pid:Number(match[2]),ppid:Number(match[3]),tty:match[4]??"",started:match[5]??"",...tool?{tool}:{}})}return entries}function classifyProcess(args){let[first="",second=""]=args.trim().split(/\s+/,2),executable=basename(first);if(executable==="claude")return"claude";if(executable==="codex")return"codex";if(!(executable!=="node"&&executable!=="bun")){if(/[\\/]@anthropic-ai[\\/]claude-code[\\/]cli\.js$/.
|
|
102
|
+
test(second))return"claude";if(/[\\/]@openai[\\/]codex[\\/]bin[\\/]codex\.js$/.test(second))return"codex"}}function findExternalAgents(entries,uid){let candidates=new Map;for(let entry of entries){if(entry.uid!==uid||NO_TTY.has(entry.tty))continue;let{tool}=entry;tool&&candidates.set(entry.pid,{tool,pid:entry.pid,ppid:entry.ppid,started:entry.started})}return[...candidates.values()].filter(candidate=>candidates.get(candidate.ppid)?.tool!==candidate.tool)}async function defaultListProcesses(){let{
|
|
103
|
+
stdout}=await execFileAsync("ps",["-A","-o","uid=,pid=,ppid=,tty=,lstart=,args="],{timeout:PS_TIMEOUT_MS,maxBuffer:PS_MAX_BYTES,env:{PATH:process.env.PATH??"/usr/bin:/bin",LC_ALL:"C"}});return stdout}async function defaultReadCwd(pid){if(process.platform==="linux")return await readlink(`/proc/${pid}/cwd`).catch(()=>{});let{stdout}=await execFileAsync("lsof",["-a","-p",String(pid),"-d","cwd","-Fn"],{timeout:CWD_TIMEOUT_MS,maxBuffer:64*1024,env:{PATH:process.env.PATH??"/usr/bin:/bin:/usr/sbin",LC_ALL:"\
|
|
104
|
+
C"}});return/^n(.+)$/m.exec(stdout)?.[1]}var ExternalDiscovery=class{deps;known=new Map;constructor(deps={}){this.deps={listProcesses:deps.listProcesses??defaultListProcesses,readCwd:deps.readCwd??defaultReadCwd,uid:deps.uid??process.getuid?.()??-1,now:deps.now??Date.now}}async scan(){let entries;try{entries=parsePsOutput(await this.deps.listProcesses())}catch{return this.known.clear(),{agents:[],coverage:"partial",note:UNAVAILABLE_NOTE}}let candidates=findExternalAgents(entries,this.deps.uid).map(
|
|
105
|
+
candidate=>({...candidate,id:`${candidate.tool}:${candidate.pid}:${candidate.started}`}));await Promise.all(candidates.filter(candidate=>!this.known.has(candidate.id)).map(async candidate=>{this.known.set(candidate.id,{cwd:await this.deps.readCwd(candidate.pid).catch(()=>{}),firstSeen:this.deps.now()})}));let next=new Map,agents=[];for(let candidate of candidates){let{id}=candidate,info=this.known.get(id);next.set(id,info),agents.push({id,tool:candidate.tool,name:TOOL_NAMES[candidate.tool],...info.
|
|
106
|
+
cwd!==void 0?{cwd:info.cwd}:{},pid:candidate.pid,status:"unknown",updatedAt:info.firstSeen,source:"process"})}return this.known=next,{agents,coverage:"complete"}}};var MAX_CONNECTIONS=128,HELLO_TIMEOUT_MS=5e3,TRUNCATED_NOTE="Too many agents to show; the list is incomplete.",TRUNCATED_CHILDREN_NOTE="Too many subagents to show; the list is incomplete.",NON_TUI_VISIBILITY_DELAY_MS=5e3,MonitorAlreadyRunningError=class extends Error{constructor(socketPath){super(`Agent monitor already running (socket ${socketPath} is in use); not starting another`),this.name="MonitorAlreadyRunningError"}};function errorCode2(error){return error?.code}function isListening(socketPath){
|
|
107
|
+
return new Promise(resolve2=>{let socket=net.connect(socketPath),settle=live=>{clearTimeout(timer),socket.destroy(),resolve2(live)},timer=setTimeout(()=>settle(!0),1e3);socket.once("connect",()=>settle(!0)),socket.once("error",error=>{let code=errorCode2(error);settle(code!=="ECONNREFUSED"&&code!=="ENOENT")})})}function unlinkQuietly(path){try{unlinkSync2(path)}catch{}}function fitFrame(agents){let budget=MAX_SNAPSHOT_FRAME_BYTES-4096,kept=[];for(let agent of agents.slice(0,MAX_AGENTS)){if(budget-=
|
|
108
|
+
Buffer.byteLength(JSON.stringify(agent),"utf8")+1,budget<0)break;kept.push(agent)}return{agents:kept,truncated:kept.length<agents.length}}var AgentMonitorServer=class{paths;discover;scanIntervalMs;idleShutdownMs;pushDelayMs;now;visibilityDelayMs;onExit;server;connections=new Set;consumers=new Map;external={agents:[],coverage:"complete"};scanTimer;pushTimer;idleTimer;scanning=!1;serving=!1;stopped=!1;constructor(options){this.paths=options.paths,this.discover=options.discover??(()=>{let discovery=new ExternalDiscovery;
|
|
109
|
+
return()=>discovery.scan()})(),this.scanIntervalMs=options.scanIntervalMs??2e3,this.idleShutdownMs=options.idleShutdownMs??5e3,this.pushDelayMs=options.pushDelayMs??100,this.now=options.now??Date.now,this.visibilityDelayMs=options.visibilityDelayMs??NON_TUI_VISIBILITY_DELAY_MS,this.onExit=options.onExit??(code=>process.exit(code)),ensureCoordinationRuntimeDir(this.paths),this.server=net.createServer(socket=>this.accept(socket))}async start(){await this.claimSocket(),this.server.on("error",()=>this.
|
|
110
|
+
shutdown()),this.serving=!0,restrictRuntimeFile(this.paths.socketPath),writeTextAtomic(this.paths.pidPath,String(process.pid),MAX_RUNTIME_TEXT_FILE_BYTES),this.armIdle()}listen(){return new Promise((resolve2,reject)=>{let onError=error=>{this.server.off("listening",onListening),reject(error)},onListening=()=>{this.server.off("error",onError),resolve2()};this.server.once("error",onError),this.server.once("listening",onListening),this.server.listen(this.paths.socketPath)})}async claimSocket(){try{
|
|
111
|
+
await this.listen();return}catch(error){if(errorCode2(error)!=="EADDRINUSE")throw error}if(await isListening(this.paths.socketPath))throw new MonitorAlreadyRunningError(this.paths.socketPath);if(!lstatSync2(this.paths.socketPath).isSocket())throw new Error(`Refusing to remove ${this.paths.socketPath}: it is not a socket`);unlinkSync2(this.paths.socketPath);try{await this.listen()}catch(error){throw errorCode2(error)==="EADDRINUSE"?new MonitorAlreadyRunningError(this.paths.socketPath):error}}accept(socket){
|
|
112
|
+
if(this.stopped||this.connections.size>=MAX_CONNECTIONS){socket.destroy();return}this.connections.add(socket);let helloTimer=setTimeout(()=>{this.consumers.has(socket)||socket.destroy()},HELLO_TIMEOUT_MS);socket.on("data",createMessageReader(message=>this.handle(socket,message),()=>socket.destroy(),MAX_REPORT_FRAME_BYTES)),socket.on("error",()=>{}),socket.on("close",()=>{clearTimeout(helloTimer),this.connections.delete(socket);let consumer=this.consumers.get(socket);consumer&&(clearTimeout(consumer.
|
|
113
|
+
revealTimer),this.consumers.delete(socket),this.schedulePush(),this.updateIdle())})}hasViewer(){for(let consumer of this.consumers.values()){let mode=consumer.report?.session.mode;if(mode===void 0||mode==="tui")return!0}return!1}updateIdle(){this.hasViewer()?(this.cancelIdle(),this.startScanning()):(this.stopScanning(),this.armIdle())}handle(socket,message){if(typeof message!="object"||message===null||!("type"in message))throw new Error("Invalid message");let typed=message;if(typed.type==="healt\
|
|
114
|
+
h"&&typeof typed.requestId=="string"){writeMessage(socket,{type:"health_ok",requestId:typed.requestId,protocol:AGENT_MONITOR_PROTOCOL.name,version:AGENT_MONITOR_PROTOCOL.version});return}if(typed.type==="hello"){let hello=parseHello(message);if(!hello)throw new Error("Invalid hello");if(hello.protocol!==AGENT_MONITOR_PROTOCOL.name||hello.version!==AGENT_MONITOR_PROTOCOL.version){writeMessage(socket,{type:"incompatible",version:AGENT_MONITOR_PROTOCOL.version}),socket.end();return}if(this.consumers.
|
|
115
|
+
has(socket))throw new Error("Duplicate hello");let consumer2={pid:hello.pid,connectedAt:this.now(),revealed:!1,revealTimer:setTimeout(()=>{consumer2.revealed=!0,this.schedulePush()},this.visibilityDelayMs)};consumer2.revealTimer.unref(),this.consumers.set(socket,consumer2),writeMessage(socket,{type:"welcome"}),this.updateIdle(),this.schedulePush();return}let consumer=this.consumers.get(socket);if(!consumer)throw new Error("Message before hello");if(typed.type!=="report")throw new Error("Unknown \
|
|
116
|
+
message");let report=parseReport(message);if(!report)throw new Error("Invalid report");consumer.report=report,this.updateIdle(),this.schedulePush()}startScanning(){this.scanTimer||(this.scan(),this.scanTimer=setInterval(()=>{this.scan()},this.scanIntervalMs))}stopScanning(){this.scanTimer&&clearInterval(this.scanTimer),this.scanTimer=void 0}async scan(){if(!(this.scanning||this.stopped)){this.scanning=!0;try{this.external=await this.discover()}catch{this.external={agents:[],coverage:"partial",note:UNAVAILABLE_NOTE}}finally{
|
|
117
|
+
this.scanning=!1}this.schedulePush()}}snapshot(){let all=[],childrenTruncated=!1;for(let consumer of this.consumers.values()){let report=consumer.report;if(!report||report.session.mode!==void 0&&report.session.mode!=="tui"&&!consumer.revealed&&this.now()-consumer.connectedAt<this.visibilityDelayMs)continue;report.truncated&&(childrenTruncated=!0);let id=`humain:${consumer.pid}:${report.session.id}`,{session}=report;all.push({id,tool:"humain",...session.mode!==void 0?{mode:session.mode}:{},name:session.
|
|
118
|
+
name,...session.cwd?{cwd:session.cwd}:{},pid:consumer.pid,status:session.status,...session.reason!==void 0?{reason:session.reason}:{},updatedAt:session.updatedAt,source:"native"});for(let child of report.children)all.push({id:`${id}/${child.id}`,parentId:id,tool:"humain",...session.mode!==void 0?{mode:session.mode}:{},name:child.name,...session.cwd?{cwd:session.cwd}:{},pid:consumer.pid,status:"working",updatedAt:child.updatedAt,source:"native"})}all.push(...this.external.agents);let{agents,truncated}=fitFrame(
|
|
119
|
+
all),note=[truncated?TRUNCATED_NOTE:void 0,childrenTruncated?TRUNCATED_CHILDREN_NOTE:void 0,this.external.note].filter(note2=>note2!==void 0).join(" ");return{type:"snapshot",agents,coverage:truncated||childrenTruncated||this.external.coverage==="partial"?"partial":"complete",...note?{note}:{}}}schedulePush(){this.pushTimer||this.stopped||(this.pushTimer=setTimeout(()=>{this.pushTimer=void 0,this.push()},this.pushDelayMs))}push(){let snapshot=this.snapshot(),payload=JSON.stringify(snapshot);for(let[
|
|
120
|
+
socket,consumer]of this.consumers)consumer.lastSent!==payload&&(consumer.lastSent=payload,writeMessage(socket,snapshot))}armIdle(){this.idleTimer||this.stopped||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.hasViewer()||this.shutdown()},this.idleShutdownMs))}cancelIdle(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=void 0}shutdown(){if(!this.stopped){this.stopped=!0,this.cancelIdle(),this.stopScanning(),this.pushTimer&&clearTimeout(this.pushTimer);for(let consumer of this.
|
|
121
|
+
consumers.values())clearTimeout(consumer.revealTimer);for(let socket of this.connections)socket.destroy();this.serving&&(unlinkQuietly(this.paths.socketPath),unlinkQuietly(this.paths.pidPath)),this.server.close(),this.onExit(0)}}};async function runAgentMonitorCommand(env){let role=env[COORDINATION_ROLE_ENV];if(delete env[COORDINATION_ROLE_ENV],role!==AGENT_MONITOR_ROLE)return console.error("This command is internal to HUMAIN Code CLI."),2;process.stderr.on("error",()=>{}),process.stdout.on("error",()=>{});let server;try{server=new AgentMonitorServer({paths:resolveAgentMonitorPaths(getAgentDir())}),await server.start()}catch(error){return console.error(error instanceof MonitorAlreadyRunningError?error.message:`Agent monit\
|
|
122
|
+
or failed to start: ${error instanceof Error?error.message:String(error)}`),1}let stop=()=>server.shutdown();return process.on("SIGTERM",stop),process.on("SIGINT",stop),process.on("SIGHUP",stop),await new Promise(()=>{})}export{COORDINATION_BROKER_COMMAND,COORDINATION_ROLE_ENV,COORDINATION_ROLE,detectLaunchRuntime,getInternalCommandLaunchSpec,getBrokerLaunchSpec,FLOW_ID_PATTERN,FLOW_MODEL_ID_PATTERN,FLOW_DIGEST_PATTERN,FlowContractError,lit,StrictObject,FlowIdSchema,FlowDigestSchema,FlowTimestampSchema,FlowMicrousdSchema,FlowCountSchema,FlowPositiveIntSchema,FlowModelRefSchema,FLOW_ROLES,FlowRoleSchema,partialByRole,FlowSizeSchema,FlowFailureClassSchema,FlowReasonClassSchema,FlowProfileRefSchema,verifyFlowDigest,
|
|
123
|
+
parseFlowData,compileFlow,hasDuplicateModels,canonicalFlowJson,canonicalWithout,SUBAGENT_FAILURE_KINDS,SUBAGENT_RUN_MODES,SUBAGENT_PROGRESS_IDENTIFIER_PATTERN,SUBAGENT_PROGRESS_MODEL_PATTERN,SUBAGENT_PROGRESS_TOOL_CALL_ID_PATTERN,isCanonicalSubagentProgressUuid,toSubagentPresentationText,parseSubagentRunSnapshot,parseSubagentProgressSnapshot,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentRouteRefSchema,HumainAgentArtifactSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionClaimSchema,
|
|
124
|
+
HumainAgentExecutionRequestSchema,HumainAgentUsageSchema,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionResponseSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,COORDINATION_FILE_MODE,COORDINATION_PROTOCOL_NAME,COORDINATION_PROTOCOL_VERSION,MAX_MESSAGE_TEXT_BYTES,getCoordinationRuntimePaths,resolveCoordinationRuntimePaths,assertSafeAncestors,assertCanonicalRuntimeDir,ensureRuntimeDir,ensureCoordinationRuntimeDir,assertPrivateSocket,
|
|
125
|
+
restrictRuntimeFile,AGENT_MONITOR_PROTOCOL,AGENT_MONITOR_COMMAND,AGENT_MONITOR_ROLE,MAX_SNAPSHOT_FRAME_BYTES,MAX_CHILDREN,MAX_ID,resolveAgentMonitorPaths,parseSnapshot,MAX_RUNTIME_TEXT_FILE_BYTES,fsyncDirectory,writeJsonAtomic,writeTextAtomic,createFileExclusive,readBoundedTextFile,readTextFile,readJsonFile,framePayloadBytes,writeMessage,createMessageReader,runAgentMonitorCommand};
|