@humain/humain-code 0.6.2 → 0.7.0
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 +119 -0
- package/README.md +23 -6
- package/dist/agent-monitor/entry.lazy.d.ts +3 -0
- package/dist/agent-monitor/entry.lazy.d.ts.map +1 -0
- package/dist/agent-monitor/entry.lazy.js +3 -0
- package/dist/agent-monitor/entry.lazy.js.map +1 -0
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/adaptive-peer-worker-X2ZNZE3S.js +8 -0
- package/dist/bundle/chunks/adaptive-session-host-7KDSQV5I.js +162 -0
- package/dist/bundle/chunks/anthropic-messages-TQK3FUV3.js +68 -0
- package/dist/bundle/chunks/anthropic.js +13 -10
- package/dist/bundle/chunks/{azure-openai-responses-IV74M5OR.js → azure-openai-responses-JY7OSLH2.js} +6 -6
- package/dist/bundle/chunks/bedrock-converse-stream.js +79 -74
- package/dist/bundle/chunks/chunk-2FYYW6FY.js +2 -0
- package/dist/bundle/chunks/{chunk-A2VPLMF2.js → chunk-2G7YVAVF.js} +1 -1
- package/dist/bundle/chunks/chunk-32QLLD2P.js +1114 -0
- package/dist/bundle/chunks/{chunk-3LP543EX.js → chunk-3EDMWQ35.js} +17 -16
- package/dist/bundle/chunks/chunk-3HVHETMU.js +18 -0
- package/dist/bundle/chunks/{chunk-XMZGB3H4.js → chunk-4HTVBBJD.js} +11 -6
- package/dist/bundle/chunks/chunk-4JRER4XK.js +175 -0
- package/dist/bundle/chunks/{chunk-FHLLDO7U.js → chunk-4PRNKB6V.js} +5 -5
- package/dist/bundle/chunks/chunk-4QAXV5T6.js +49 -0
- package/dist/bundle/chunks/{chunk-JCTQQ3DX.js → chunk-4V5VL2BO.js} +1 -1
- package/dist/bundle/chunks/chunk-5B25YXF7.js +24 -0
- package/dist/bundle/chunks/chunk-5L4PBYC7.js +11 -0
- package/dist/bundle/chunks/chunk-66FZJO75.js +5146 -0
- package/dist/bundle/chunks/chunk-6P6GJPYB.js +4 -0
- package/dist/bundle/chunks/chunk-6PNQYO6A.js +10 -0
- package/dist/bundle/chunks/chunk-7NKUVTBL.js +76 -0
- package/dist/bundle/chunks/chunk-AEWYICBL.js +89 -0
- package/dist/bundle/chunks/chunk-AQ4EXORZ.js +14 -0
- package/dist/bundle/chunks/chunk-AZXVJN6E.js +19 -0
- package/dist/bundle/chunks/chunk-CRN54O4D.js +24 -0
- package/dist/bundle/chunks/chunk-CTU2ECLD.js +7 -0
- package/dist/bundle/chunks/{chunk-BQ3TMEWD.js → chunk-EIC7CQX3.js} +4 -3
- package/dist/bundle/chunks/chunk-F6ZAYLU2.js +59 -0
- package/dist/bundle/chunks/chunk-G4QPSFBF.js +493 -0
- package/dist/bundle/chunks/chunk-GME4AWDG.js +23 -0
- package/dist/bundle/chunks/{chunk-SFMDIVZ4.js → chunk-GRJUKEE3.js} +43 -30
- package/dist/bundle/chunks/chunk-GTILMMUF.js +12 -0
- package/dist/bundle/chunks/chunk-GUHNFZ2Q.js +51 -0
- package/dist/bundle/chunks/chunk-GY663MNP.js +11 -0
- package/dist/bundle/chunks/chunk-HTA325LJ.js +56 -0
- package/dist/bundle/chunks/{chunk-5L4JG6PO.js → chunk-I3NDOUHE.js} +8 -7
- package/dist/bundle/chunks/chunk-I5E7RQ5V.js +21 -0
- package/dist/bundle/chunks/chunk-IWZQ25I3.js +5 -0
- package/dist/bundle/chunks/chunk-IYGHKVUG.js +2 -0
- package/dist/bundle/chunks/chunk-J57HOSWD.js +21 -0
- package/dist/bundle/chunks/chunk-JF7FYXAI.js +288 -0
- package/dist/bundle/chunks/chunk-JSZBTGI6.js +10 -0
- package/dist/bundle/chunks/chunk-JYWUOKOI.js +1061 -0
- package/dist/bundle/chunks/{chunk-DLCBSLHW.js → chunk-KRCX3ZBA.js} +1 -1
- package/dist/bundle/chunks/chunk-KTSJYIYC.js +30 -0
- package/dist/bundle/chunks/{chunk-K7SDY3VJ.js → chunk-LB4CIS4F.js} +40 -165
- package/dist/bundle/chunks/{chunk-NN53K2QQ.js → chunk-LYZ37DJP.js} +2 -14
- package/dist/bundle/chunks/chunk-MD7K7RPN.js +20 -0
- package/dist/bundle/chunks/chunk-MX4Q4W6H.js +214 -0
- package/dist/bundle/chunks/{chunk-6PD3T2EF.js → chunk-N2SNMUD3.js} +1 -1
- package/dist/bundle/chunks/chunk-NXA6NEHE.js +54 -0
- package/dist/bundle/chunks/chunk-OB332KMV.js +300 -0
- package/dist/bundle/chunks/chunk-P6AXBESH.js +1883 -0
- package/dist/bundle/chunks/chunk-PPBDDQHP.js +11 -0
- package/dist/bundle/chunks/chunk-PWUDFU5V.js +51 -0
- package/dist/bundle/chunks/chunk-Q5RKNQ2T.js +73 -0
- package/dist/bundle/chunks/chunk-QT6ZHDMP.js +12 -0
- package/dist/bundle/chunks/chunk-R5OOX7RW.js +16 -0
- package/dist/bundle/chunks/chunk-R6YQR7TZ.js +25 -0
- package/dist/bundle/chunks/{chunk-4ZBGTJJM.js → chunk-RNBZBCH2.js} +1 -1
- package/dist/bundle/chunks/chunk-RQU722SY.js +1 -0
- package/dist/bundle/chunks/{chunk-RGUZULEE.js → chunk-RS6PZK35.js} +71 -72
- package/dist/bundle/chunks/{jiti-loader-6P33XTLC.js → chunk-RW7GT7L3.js} +1 -1
- package/dist/bundle/chunks/{chunk-PCTLFSQG.js → chunk-SCINMV4X.js} +1 -1
- package/dist/bundle/chunks/{chunk-NCC2FAJN.js → chunk-SSRCVJZK.js} +28 -28
- package/dist/bundle/chunks/chunk-T5A6T24H.js +93 -0
- package/dist/bundle/chunks/chunk-T7BXP46S.js +3367 -0
- package/dist/bundle/chunks/chunk-TGDPZCSW.js +9 -0
- package/dist/bundle/chunks/{chunk-4J6BGNX2.js → chunk-TWAHPPXN.js} +434 -429
- package/dist/bundle/chunks/chunk-UEW6TUSP.js +36 -0
- package/dist/bundle/chunks/chunk-UZNIPOGS.js +323 -0
- package/dist/bundle/chunks/{chunk-KM4GQ2BU.js → chunk-VFLVWPLZ.js} +5 -6
- package/dist/bundle/chunks/chunk-WAPZN4KP.js +74 -0
- package/dist/bundle/chunks/chunk-WCFHG6NO.js +16 -0
- package/dist/bundle/chunks/chunk-WQ7EJQIT.js +839 -0
- package/dist/bundle/chunks/chunk-WQOOJP7U.js +4 -0
- package/dist/bundle/chunks/chunk-XHDVDJM7.js +17 -0
- package/dist/bundle/chunks/chunk-YPZPCHNV.js +3 -0
- package/dist/bundle/chunks/chunk-Z5YLKK3S.js +41 -0
- package/dist/bundle/chunks/chunk-ZJUU6WOV.js +2052 -0
- package/dist/bundle/chunks/{cli-N7KOVPLB.js → cli-H4LJNE2V.js} +2 -2
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KRMHG2L3.js → cloudflare-workers-ai-system-one-T5R2RVFQ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +2 -0
- package/dist/bundle/chunks/compat-ZK2DIW3P.js +15 -0
- package/dist/bundle/chunks/dist-EY7YKQHB.js +11 -0
- package/dist/bundle/chunks/dist-FMWWM4H7.js +268 -0
- package/dist/bundle/chunks/dist-NHQTBDHT.js +1107 -0
- package/dist/bundle/chunks/{easter-egg-3d-O2GG2XIG.js → easter-egg-3d-BUEOC3NO.js} +1 -1
- package/dist/bundle/chunks/entry-A2CSLKHC.js +323 -0
- package/dist/bundle/chunks/entry-AL54ZGYO.js +2 -0
- package/dist/bundle/chunks/{execute-LMBACTKA.js → execute-MY5JSEPV.js} +18 -15
- package/dist/bundle/chunks/{extract-CXXLVFC5.js → extract-PTGACPGP.js} +3 -3
- package/dist/bundle/chunks/flow-implementer-APJFY4YI.js +21 -0
- package/dist/bundle/chunks/github-copilot.js +66 -62
- package/dist/bundle/chunks/{google-generative-ai-SBL77OXO.js → google-generative-ai-UL7YEQ6J.js} +2 -3
- package/dist/bundle/chunks/{google-vertex-NZBNNXMK.js → google-vertex-OTMSPUYH.js} +3 -3
- package/dist/bundle/chunks/host-75YAHLDR.js +3 -0
- package/dist/bundle/chunks/index.bundle-THL4EUSU.js +390 -0
- package/dist/bundle/chunks/inprocess-5NP5VJHZ.js +32 -0
- package/dist/bundle/chunks/interactive-mode-IW4PIVAQ.js +5 -0
- package/dist/bundle/chunks/jiti-bun-loader-VSLLRCSD.js +3459 -0
- package/dist/bundle/chunks/jiti-loader-TMJL6S2D.js +2 -0
- package/dist/bundle/chunks/{llama-cpp-classify-PP63BYDF.js → llama-cpp-classify-GJAXULWL.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-DX4YKJSO.js → mistral-conversations-E72Y6OC3.js} +2 -2
- package/dist/bundle/chunks/{node-UGQUSQE6.js → node-ZFIIS5IM.js} +32 -32
- package/dist/bundle/chunks/openai-codex-responses-S7CMCAOY.js +101 -0
- package/dist/bundle/chunks/openai-completions-2Z57N7PC.js +87 -0
- package/dist/bundle/chunks/{openai-decisions-ALJROWBE.js → openai-decisions-JIOJDB4C.js} +1 -1
- package/dist/bundle/chunks/openai-responses-5VBZSTHL.js +27 -0
- package/dist/bundle/chunks/{openrouter-images-FCJT7C7I.js → openrouter-images-S6O7DBEJ.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-NHTQQOPW.js → pi-messages-SMLN5J2W.js} +10 -7
- package/dist/bundle/chunks/runtime-OYTWXIUM.js +2 -0
- package/dist/bundle/chunks/session-picker-DM6S37IF.js +4 -0
- package/dist/bundle/chunks/startup-ui-4GGLWNSU.js +3 -0
- package/dist/bundle/chunks/trace-command-YLDYCL55.js +254 -0
- package/dist/bundle/chunks/typesafe-system-one-7BEL3H5N.js +3 -0
- package/dist/bundle/chunks/virtual-modules-TI3W24YL.js +28 -0
- package/dist/bundle/cli-runtime.js +5 -3
- package/dist/bundle/flow/agents/orch-implementation-fast.md +4 -4
- package/dist/bundle/flow/agents/orch-implementation-strong.md +5 -5
- package/dist/bundle/flow/package.json +35 -3
- package/dist/bundle/index.js +20 -17
- package/dist/bundle/orchestrate/README.md +37 -0
- package/dist/bundle/{flow → orchestrate}/agents/orch-qa-agent.md +1 -1
- package/dist/bundle/{flow → orchestrate}/agents/orch-worker.md +1 -1
- package/dist/bundle/{flow → orchestrate}/agents/orchestrator-lead.md +1 -1
- package/dist/bundle/orchestrate/package.json +29 -0
- package/dist/bundle/rpc-entry.js +5 -3
- package/dist/cli/args.d.ts +6 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +69 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-check.d.ts +3 -2
- package/dist/cli/auth-check.d.ts.map +1 -1
- package/dist/cli/auth-check.js +4 -3
- package/dist/cli/auth-check.js.map +1 -1
- package/dist/cli/config-selector.d.ts.map +1 -1
- package/dist/cli/config-selector.js +3 -1
- package/dist/cli/config-selector.js.map +1 -1
- package/dist/cli/file-processor.d.ts +2 -0
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js +6 -6
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/cli/metadata-disclosure.d.ts +4 -0
- package/dist/cli/metadata-disclosure.d.ts.map +1 -0
- package/dist/cli/metadata-disclosure.js +23 -0
- package/dist/cli/metadata-disclosure.js.map +1 -0
- package/dist/cli/project-trust.d.ts.map +1 -1
- package/dist/cli/project-trust.js +4 -1
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/cli/session-picker.lazy.d.ts +3 -0
- package/dist/cli/session-picker.lazy.d.ts.map +1 -0
- package/dist/cli/session-picker.lazy.js +3 -0
- package/dist/cli/session-picker.lazy.js.map +1 -0
- package/dist/cli/startup-ui.d.ts +4 -4
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +38 -14
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/cli/startup-ui.lazy.d.ts +3 -0
- package/dist/cli/startup-ui.lazy.d.ts.map +1 -0
- package/dist/cli/startup-ui.lazy.js +3 -0
- package/dist/cli/startup-ui.lazy.js.map +1 -0
- package/dist/cli/trace-command.lazy.d.ts +3 -0
- package/dist/cli/trace-command.lazy.d.ts.map +1 -0
- package/dist/cli/trace-command.lazy.js +3 -0
- package/dist/cli/trace-command.lazy.js.map +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/coordination/broker/entry.lazy.d.ts +3 -0
- package/dist/coordination/broker/entry.lazy.d.ts.map +1 -0
- package/dist/coordination/broker/entry.lazy.js +3 -0
- package/dist/coordination/broker/entry.lazy.js.map +1 -0
- package/dist/core/acceptance-command.d.ts +15 -0
- package/dist/core/acceptance-command.d.ts.map +1 -0
- package/dist/core/acceptance-command.js +150 -0
- package/dist/core/acceptance-command.js.map +1 -0
- package/dist/core/acceptance-ledger.d.ts +52 -0
- package/dist/core/acceptance-ledger.d.ts.map +1 -0
- package/dist/core/acceptance-ledger.js +341 -0
- package/dist/core/acceptance-ledger.js.map +1 -0
- package/dist/core/admission-types.d.ts +69 -0
- package/dist/core/admission-types.js +2 -0
- package/dist/core/admission-types.js.map +1 -0
- package/dist/core/agent-session-runtime.d.ts +7 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +43 -9
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +8 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +13 -1
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +127 -10
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1390 -145
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/anthropic-subscription-usage.d.ts +1 -1
- package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
- package/dist/core/anthropic-subscription-usage.js +31 -3
- package/dist/core/anthropic-subscription-usage.js.map +1 -1
- package/dist/core/auth-storage.d.ts +2 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +13 -10
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/auto-session-namer.d.ts.map +1 -1
- package/dist/core/auto-session-namer.js +3 -1
- package/dist/core/auto-session-namer.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +3 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/bug-report-redaction.d.ts +4 -0
- package/dist/core/bug-report-redaction.d.ts.map +1 -0
- package/dist/core/bug-report-redaction.js +209 -0
- package/dist/core/bug-report-redaction.js.map +1 -0
- package/dist/core/bug-report.d.ts +26 -6
- package/dist/core/bug-report.d.ts.map +1 -1
- package/dist/core/bug-report.js +82 -9
- package/dist/core/bug-report.js.map +1 -1
- package/dist/core/cache-warmer.d.ts.map +1 -1
- package/dist/core/cache-warmer.js +5 -0
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +6 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +103 -71
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +2 -1
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/extensions/jiti-bun-babel.d.ts +4 -0
- package/dist/core/extensions/jiti-bun-babel.d.ts.map +1 -0
- package/dist/core/extensions/jiti-bun-babel.js +4 -0
- package/dist/core/extensions/jiti-bun-babel.js.map +1 -0
- package/dist/core/extensions/jiti-bun-loader.d.ts +4 -0
- package/dist/core/extensions/jiti-bun-loader.d.ts.map +1 -0
- package/dist/core/extensions/jiti-bun-loader.js +13 -0
- package/dist/core/extensions/jiti-bun-loader.js.map +1 -0
- package/dist/core/extensions/jiti-bun-loader.lazy.d.ts +3 -0
- package/dist/core/extensions/jiti-bun-loader.lazy.d.ts.map +1 -0
- package/dist/core/extensions/jiti-bun-loader.lazy.js +3 -0
- package/dist/core/extensions/jiti-bun-loader.lazy.js.map +1 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +9 -3
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +4 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +3 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/flow-implementer.d.ts +25 -0
- package/dist/core/flow-implementer.d.ts.map +1 -0
- package/dist/core/flow-implementer.js +301 -0
- package/dist/core/flow-implementer.js.map +1 -0
- package/dist/core/internal-process.d.ts +23 -0
- package/dist/core/internal-process.d.ts.map +1 -0
- package/dist/core/internal-process.js +88 -0
- package/dist/core/internal-process.js.map +1 -0
- package/dist/core/keybindings.d.ts +2 -2
- package/dist/core/keybindings.js +1 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-config.d.ts +52 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +4 -4
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-registry.d.ts +4 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +8 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-request-admission.d.ts +51 -0
- package/dist/core/model-request-admission.d.ts.map +1 -0
- package/dist/core/model-request-admission.js +103 -0
- package/dist/core/model-request-admission.js.map +1 -0
- package/dist/core/model-resolver.d.ts +4 -0
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +109 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +56 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +482 -40
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/model-selection-intent.d.ts +14 -0
- package/dist/core/model-selection-intent.d.ts.map +1 -0
- package/dist/core/model-selection-intent.js +15 -0
- package/dist/core/model-selection-intent.js.map +1 -0
- package/dist/core/oauth-account-pool.d.ts +4 -1
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +251 -228
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/core/os-secret-store.d.ts +25 -0
- package/dist/core/os-secret-store.d.ts.map +1 -0
- package/dist/core/os-secret-store.js +290 -0
- package/dist/core/os-secret-store.js.map +1 -0
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js +62 -2
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +4 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -1
- package/dist/core/private-windows-path.d.ts +4 -0
- package/dist/core/private-windows-path.d.ts.map +1 -0
- package/dist/core/private-windows-path.js +44 -0
- package/dist/core/private-windows-path.js.map +1 -0
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +18 -2
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +1 -1
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +6 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-outcome.d.ts +40 -0
- package/dist/core/run-outcome.d.ts.map +1 -0
- package/dist/core/run-outcome.js +91 -0
- package/dist/core/run-outcome.js.map +1 -0
- package/dist/core/run-preflight.d.ts +5 -0
- package/dist/core/run-preflight.d.ts.map +1 -0
- package/dist/core/run-preflight.js +96 -0
- package/dist/core/run-preflight.js.map +1 -0
- package/dist/core/runtime-credentials.d.ts +18 -2
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js +65 -9
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sdk.d.ts +19 -3
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +115 -20
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +2 -1
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +2 -1
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +15 -4
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +114 -22
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +7 -2
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +12 -5
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +11 -0
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt.d.ts +3 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +10 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash-jobs.d.ts +109 -0
- package/dist/core/tools/bash-jobs.d.ts.map +1 -0
- package/dist/core/tools/bash-jobs.js +563 -0
- package/dist/core/tools/bash-jobs.js.map +1 -0
- package/dist/core/tools/bash.d.ts +68 -6
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +350 -37
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +11 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +89 -20
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +15 -7
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/file-mutation-custody.d.ts +29 -0
- package/dist/core/tools/file-mutation-custody.d.ts.map +1 -0
- package/dist/core/tools/file-mutation-custody.js +173 -0
- package/dist/core/tools/file-mutation-custody.js.map +1 -0
- package/dist/core/tools/find.d.ts +6 -0
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +84 -38
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +8 -2
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +121 -77
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +3 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +12 -0
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/jobs.d.ts +24 -0
- package/dist/core/tools/jobs.d.ts.map +1 -0
- package/dist/core/tools/jobs.js +86 -0
- package/dist/core/tools/jobs.js.map +1 -0
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +2 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +12 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +88 -8
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/output-cleanup.d.ts +40 -0
- package/dist/core/tools/output-cleanup.d.ts.map +1 -0
- package/dist/core/tools/output-cleanup.js +273 -0
- package/dist/core/tools/output-cleanup.js.map +1 -0
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/powershell.js +15 -2
- package/dist/core/tools/powershell.js.map +1 -1
- package/dist/core/tools/read.d.ts +21 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +162 -29
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts.map +1 -1
- package/dist/core/tools/renderers/bash.js +3 -1
- package/dist/core/tools/renderers/bash.js.map +1 -1
- package/dist/core/tools/renderers/index.d.ts.map +1 -1
- package/dist/core/tools/renderers/index.js +1 -0
- package/dist/core/tools/renderers/index.js.map +1 -1
- package/dist/core/tools/subagent.d.ts +5 -1
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +76 -19
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/tools/truncate.d.ts +4 -0
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +24 -1
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +6 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trace/config.js +3 -3
- package/dist/core/trace/config.js.map +1 -1
- package/dist/core/trace/redaction.d.ts.map +1 -1
- package/dist/core/trace/redaction.js +12 -9
- package/dist/core/trace/redaction.js.map +1 -1
- package/dist/core/trace-client/credential-store.d.ts +1 -1
- package/dist/core/trace-client/credential-store.d.ts.map +1 -1
- package/dist/core/trace-client/credential-store.js +20 -3
- package/dist/core/trace-client/credential-store.js.map +1 -1
- package/dist/core/usage-ledger.d.ts +35 -0
- package/dist/core/usage-ledger.d.ts.map +1 -0
- package/dist/core/usage-ledger.js +140 -0
- package/dist/core/usage-ledger.js.map +1 -0
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +24 -15
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/index.d.ts +4 -2
- package/dist/extensions/codemode/index.d.ts.map +1 -1
- package/dist/extensions/codemode/index.js +8 -4
- package/dist/extensions/codemode/index.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +4 -2
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +34 -12
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/client.d.ts +2 -0
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +23 -2
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +15 -3
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +3 -2
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +18 -6
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/extensions/usage/hcode-overview.d.ts +23 -0
- package/dist/extensions/usage/hcode-overview.d.ts.map +1 -0
- package/dist/extensions/usage/hcode-overview.js +109 -0
- package/dist/extensions/usage/hcode-overview.js.map +1 -0
- package/dist/extensions/usage/index.d.ts +5 -0
- package/dist/extensions/usage/index.d.ts.map +1 -1
- package/dist/extensions/usage/index.js +194 -12
- package/dist/extensions/usage/index.js.map +1 -1
- package/dist/extensions/usage/overview.d.ts +5 -0
- package/dist/extensions/usage/overview.d.ts.map +1 -1
- package/dist/extensions/usage/overview.js +21 -1
- package/dist/extensions/usage/overview.js.map +1 -1
- package/dist/extensions/usage/popup.d.ts +14 -3
- package/dist/extensions/usage/popup.d.ts.map +1 -1
- package/dist/extensions/usage/popup.js +199 -25
- package/dist/extensions/usage/popup.js.map +1 -1
- package/dist/humain/adaptive-execution.d.ts +51 -0
- package/dist/humain/adaptive-execution.d.ts.map +1 -0
- package/dist/humain/adaptive-execution.js +100 -0
- package/dist/humain/adaptive-execution.js.map +1 -0
- package/dist/humain/adaptive-peer-process.d.ts +44 -0
- package/dist/humain/adaptive-peer-process.d.ts.map +1 -0
- package/dist/humain/adaptive-peer-process.js +159 -0
- package/dist/humain/adaptive-peer-process.js.map +1 -0
- package/dist/humain/adaptive-peer-worker.d.ts +3 -0
- package/dist/humain/adaptive-peer-worker.d.ts.map +1 -0
- package/dist/humain/adaptive-peer-worker.js +122 -0
- package/dist/humain/adaptive-peer-worker.js.map +1 -0
- package/dist/humain/adaptive-runtime-types.d.ts +621 -0
- package/dist/humain/adaptive-runtime-types.d.ts.map +1 -0
- package/dist/humain/adaptive-runtime-types.js +3 -0
- package/dist/humain/adaptive-runtime-types.js.map +1 -0
- package/dist/humain/adaptive-session-host.d.ts +113 -0
- package/dist/humain/adaptive-session-host.d.ts.map +1 -0
- package/dist/humain/adaptive-session-host.js +1838 -0
- package/dist/humain/adaptive-session-host.js.map +1 -0
- package/dist/humain/adhd/index.d.ts +2 -2
- package/dist/humain/adhd/index.d.ts.map +1 -1
- package/dist/humain/adhd/index.js +22 -13
- package/dist/humain/adhd/index.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +162 -49
- package/dist/humain/caveman/index.d.ts +1 -1
- package/dist/humain/caveman/index.d.ts.map +1 -1
- package/dist/humain/caveman/index.js +21 -12
- package/dist/humain/caveman/index.js.map +1 -1
- package/dist/humain/classify-tool.d.ts +4 -0
- package/dist/humain/classify-tool.d.ts.map +1 -0
- package/dist/humain/classify-tool.js +50 -0
- package/dist/humain/classify-tool.js.map +1 -0
- package/dist/humain/flow-command.d.ts +1 -1
- package/dist/humain/flow-command.d.ts.map +1 -1
- package/dist/humain/flow-command.js +21 -3
- package/dist/humain/flow-command.js.map +1 -1
- package/dist/humain/flow-loader.d.ts +15 -10
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +72 -18
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/humain/fuse-provider.d.ts +5 -0
- package/dist/humain/fuse-provider.d.ts.map +1 -0
- package/dist/humain/fuse-provider.js +302 -0
- package/dist/humain/fuse-provider.js.map +1 -0
- package/dist/humain/gateway/provider.d.ts.map +1 -1
- package/dist/humain/gateway/provider.js +2 -0
- package/dist/humain/gateway/provider.js.map +1 -1
- package/dist/humain/gateway/secret-store.d.ts +3 -7
- package/dist/humain/gateway/secret-store.d.ts.map +1 -1
- package/dist/humain/gateway/secret-store.js +21 -249
- package/dist/humain/gateway/secret-store.js.map +1 -1
- package/dist/humain/hcode/account-store.d.ts +92 -0
- package/dist/humain/hcode/account-store.d.ts.map +1 -0
- package/dist/humain/hcode/account-store.js +720 -0
- package/dist/humain/hcode/account-store.js.map +1 -0
- package/dist/humain/hcode/account.d.ts +42 -0
- package/dist/humain/hcode/account.d.ts.map +1 -0
- package/dist/humain/hcode/account.js +552 -0
- package/dist/humain/hcode/account.js.map +1 -0
- package/dist/humain/hcode/catalog.d.ts +6 -0
- package/dist/humain/hcode/catalog.d.ts.map +1 -0
- package/dist/humain/hcode/catalog.js +47 -0
- package/dist/humain/hcode/catalog.js.map +1 -0
- package/dist/humain/hcode/contracts.d.ts +389 -0
- package/dist/humain/hcode/contracts.d.ts.map +1 -0
- package/dist/humain/hcode/contracts.js +1243 -0
- package/dist/humain/hcode/contracts.js.map +1 -0
- package/dist/humain/hcode/environment.d.ts +9 -0
- package/dist/humain/hcode/environment.d.ts.map +1 -0
- package/dist/humain/hcode/environment.js +24 -0
- package/dist/humain/hcode/environment.js.map +1 -0
- package/dist/humain/hcode/facade.d.ts +54 -0
- package/dist/humain/hcode/facade.d.ts.map +1 -0
- package/dist/humain/hcode/facade.js +326 -0
- package/dist/humain/hcode/facade.js.map +1 -0
- package/dist/humain/hcode/http.d.ts +10 -0
- package/dist/humain/hcode/http.d.ts.map +1 -0
- package/dist/humain/hcode/http.js +119 -0
- package/dist/humain/hcode/http.js.map +1 -0
- package/dist/humain/hcode/notices.d.ts +15 -0
- package/dist/humain/hcode/notices.d.ts.map +1 -0
- package/dist/humain/hcode/notices.js +69 -0
- package/dist/humain/hcode/notices.js.map +1 -0
- package/dist/humain/hcode/ports.d.ts +34 -0
- package/dist/humain/hcode/ports.d.ts.map +1 -0
- package/dist/humain/hcode/ports.js +2 -0
- package/dist/humain/hcode/ports.js.map +1 -0
- package/dist/humain/hcode/provider.d.ts +15 -0
- package/dist/humain/hcode/provider.d.ts.map +1 -0
- package/dist/humain/hcode/provider.js +200 -0
- package/dist/humain/hcode/provider.js.map +1 -0
- package/dist/humain/hcode/selection.d.ts +16 -0
- package/dist/humain/hcode/selection.d.ts.map +1 -0
- package/dist/humain/hcode/selection.js +37 -0
- package/dist/humain/hcode/selection.js.map +1 -0
- package/dist/humain/hcode/transport.d.ts +22 -0
- package/dist/humain/hcode/transport.d.ts.map +1 -0
- package/dist/humain/hcode/transport.js +368 -0
- package/dist/humain/hcode/transport.js.map +1 -0
- package/dist/humain/hcode/usage.d.ts +5 -0
- package/dist/humain/hcode/usage.d.ts.map +1 -0
- package/dist/humain/hcode/usage.js +66 -0
- package/dist/humain/hcode/usage.js.map +1 -0
- package/dist/humain/hcode/wire.d.ts +16 -0
- package/dist/humain/hcode/wire.d.ts.map +1 -0
- package/dist/humain/hcode/wire.js +104 -0
- package/dist/humain/hcode/wire.js.map +1 -0
- package/dist/humain/index.d.ts +1 -3
- package/dist/humain/index.d.ts.map +1 -1
- package/dist/humain/index.js +8 -60
- package/dist/humain/index.js.map +1 -1
- package/dist/humain/login-menu.d.ts.map +1 -1
- package/dist/humain/login-menu.js +8 -1
- package/dist/humain/login-menu.js.map +1 -1
- package/dist/humain/metadata/contracts.d.ts +82 -0
- package/dist/humain/metadata/contracts.d.ts.map +1 -0
- package/dist/humain/metadata/contracts.js +214 -0
- package/dist/humain/metadata/contracts.js.map +1 -0
- package/dist/humain/metadata/identity.d.ts +10 -0
- package/dist/humain/metadata/identity.d.ts.map +1 -0
- package/dist/humain/metadata/identity.js +209 -0
- package/dist/humain/metadata/identity.js.map +1 -0
- package/dist/humain/metadata/index.d.ts +41 -0
- package/dist/humain/metadata/index.d.ts.map +1 -0
- package/dist/humain/metadata/index.js +100 -0
- package/dist/humain/metadata/index.js.map +1 -0
- package/dist/humain/metadata/sender.d.ts +20 -0
- package/dist/humain/metadata/sender.d.ts.map +1 -0
- package/dist/humain/metadata/sender.js +302 -0
- package/dist/humain/metadata/sender.js.map +1 -0
- package/dist/humain/metadata/version.d.ts +8 -0
- package/dist/humain/metadata/version.d.ts.map +1 -0
- package/dist/humain/metadata/version.js +38 -0
- package/dist/humain/metadata/version.js.map +1 -0
- package/dist/humain/node-http.d.ts +2 -0
- package/dist/humain/node-http.d.ts.map +1 -1
- package/dist/humain/node-http.js +9 -4
- package/dist/humain/node-http.js.map +1 -1
- package/dist/humain/node-provider.d.ts +2 -0
- package/dist/humain/node-provider.d.ts.map +1 -1
- package/dist/humain/node-provider.js +39 -8
- package/dist/humain/node-provider.js.map +1 -1
- package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts +1 -1
- package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts.map +1 -1
- package/dist/humain/ponytail/vendor/hooks/ponytail-config.js +4 -4
- package/dist/humain/ponytail/vendor/hooks/ponytail-config.js.map +1 -1
- package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.d.ts.map +1 -1
- package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js +7 -0
- package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js.map +1 -1
- package/dist/humain/ponytail/vendor/pi-extension/index.d.ts.map +1 -1
- package/dist/humain/ponytail/vendor/pi-extension/index.js +12 -1
- package/dist/humain/ponytail/vendor/pi-extension/index.js.map +1 -1
- package/dist/humain/systemone.d.ts +23 -0
- package/dist/humain/systemone.d.ts.map +1 -0
- package/dist/humain/systemone.js +101 -0
- package/dist/humain/systemone.js.map +1 -0
- package/dist/humain/trace-capture/flow-producer.d.ts.map +1 -1
- package/dist/humain/trace-capture/flow-producer.js +3 -3
- package/dist/humain/trace-capture/flow-producer.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +1 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +292 -183
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/bug-report.d.ts.map +1 -1
- package/dist/modes/interactive/bug-report.js +82 -36
- package/dist/modes/interactive/bug-report.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +8 -5
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.js +11 -5
- package/dist/modes/interactive/components/diff.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +9 -1
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +10 -5
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js +55 -29
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +16 -2
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +164 -19
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +3 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +19 -2
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +17 -0
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-indicator.js +78 -1
- package/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +19 -10
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +4 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +353 -65
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.lazy.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-mode.lazy.js +3 -0
- package/dist/modes/interactive/interactive-mode.lazy.js.map +1 -0
- package/dist/modes/interactive/model-catalog-refresh.d.ts +2 -0
- package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
- package/dist/modes/interactive/model-catalog-refresh.js +12 -0
- package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
- package/dist/modes/interactive/theme/theme-controller.d.ts +2 -3
- package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-controller.js +4 -5
- package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.js +4 -4
- package/dist/modes/interactive/theme/theme-schema.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +2 -0
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +8 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/json-event.d.ts +2 -1
- package/dist/modes/json-event.d.ts.map +1 -1
- package/dist/modes/json-event.js.map +1 -1
- package/dist/modes/print-mode.d.ts +4 -0
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +57 -11
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +68 -16
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +2 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/utils/changelog.d.ts +1 -1
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/changelog.js +7 -5
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +3 -1
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/lazy-validator.d.ts +5 -0
- package/dist/utils/lazy-validator.d.ts.map +1 -0
- package/dist/utils/lazy-validator.js +7 -0
- package/dist/utils/lazy-validator.js.map +1 -0
- package/dist/utils/shell.d.ts +3 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +9 -4
- package/dist/utils/shell.js.map +1 -1
- package/docs/cli.md +23 -5
- package/docs/codemode.md +21 -1
- package/docs/development.md +18 -0
- package/docs/docs.json +4 -0
- package/docs/extensions.md +4 -0
- package/docs/flow.md +115 -16
- package/docs/headless-modes.md +61 -0
- package/docs/humain-code-forge-architecture.md +65 -13
- package/docs/humain-code-forge-component-scorecard.md +10 -1
- package/docs/humain-code-forge-flow-walkthrough.md +54 -55
- package/docs/humain-code.md +22 -19
- package/docs/index.md +1 -0
- package/docs/keybindings.md +1 -1
- package/docs/models-configuration.md +6 -1
- package/docs/models.md +1 -1
- package/docs/prompt-templates.md +1 -1
- package/docs/providers.md +67 -15
- package/docs/run-preflight.md +47 -0
- package/docs/sdk.md +39 -1
- package/docs/security.md +1 -1
- package/docs/settings.md +12 -5
- package/docs/skills.md +2 -0
- package/docs/slash-commands.md +5 -3
- package/docs/usage.md +29 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/tsconfig.json +13 -0
- package/npm-shrinkwrap.json +67 -67
- package/package.json +25 -19
- package/schemas/models.schema.json +30 -0
- package/schemas/settings.schema.json +28 -9
- package/src/humain/caveman/UPSTREAM.md +19 -3
- package/src/humain/caveman/upstream.json +2 -2
- package/src/humain/ponytail/UPSTREAM.md +16 -1
- package/src/humain/web-access/UPSTREAM.md +10 -0
- package/src/humain/web-access/upstream.json +1 -0
- package/dist/bundle/chunks/anthropic-messages-MNISFDZA.js +0 -66
- package/dist/bundle/chunks/chunk-2HZ2V3HS.js +0 -1985
- package/dist/bundle/chunks/chunk-2PZ46FSM.js +0 -6
- package/dist/bundle/chunks/chunk-4SQUP6IR.js +0 -88
- package/dist/bundle/chunks/chunk-5JSLXC2A.js +0 -3
- package/dist/bundle/chunks/chunk-75CQYZ63.js +0 -1336
- package/dist/bundle/chunks/chunk-DCPACGLH.js +0 -12267
- package/dist/bundle/chunks/chunk-FLVBQ6GS.js +0 -24
- package/dist/bundle/chunks/chunk-H7Y4QY7K.js +0 -11
- package/dist/bundle/chunks/chunk-JEAM6N22.js +0 -139
- package/dist/bundle/chunks/chunk-PS2FJ7M4.js +0 -23
- package/dist/bundle/chunks/chunk-TEOMXMW6.js +0 -23
- package/dist/bundle/chunks/chunk-WEFEQEIQ.js +0 -28
- package/dist/bundle/chunks/chunk-WW4SILXG.js +0 -249
- package/dist/bundle/chunks/compat-MXAZPYDN.js +0 -13
- package/dist/bundle/chunks/dist-3V7ZSLER.js +0 -3166
- package/dist/bundle/chunks/dist-66CW64M2.js +0 -8
- package/dist/bundle/chunks/host-SCZ4IKWR.js +0 -2
- package/dist/bundle/chunks/openai-codex-responses-LZWBQYVP.js +0 -101
- package/dist/bundle/chunks/openai-completions-7NWH423P.js +0 -82
- package/dist/bundle/chunks/openai-responses-5YOLHMCF.js +0 -27
- package/dist/bundle/chunks/runtime-UVPDE4CX.js +0 -2
- package/dist/bundle/chunks/typesafe-system-one-BHJYAZ6E.js +0 -3
- package/dist/bundle/chunks/virtual-modules-YQPK57CW.js +0 -23
- package/dist/humain/legacy-workflow-tiers.d.ts +0 -3
- package/dist/humain/legacy-workflow-tiers.d.ts.map +0 -1
- package/dist/humain/legacy-workflow-tiers.js +0 -46
- package/dist/humain/legacy-workflow-tiers.js.map +0 -1
- /package/dist/bundle/{flow → orchestrate}/agents/orch-architect.md +0 -0
- /package/dist/bundle/{flow → orchestrate}/agents/orch-scout.md +0 -0
- /package/dist/bundle/{flow → orchestrate}/agents/orch-security-review.md +0 -0
- /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-lead.md +0 -0
- /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-review.md +0 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{FirstTimeSetupComponent,getDefaultThemeName}from"./chunk-AZXVJN6E.js";import{ExtensionInputComponent,ExtensionSelectorComponent,requestTerminalColors}from"./chunk-I5E7RQ5V.js";import{KeybindingsManager,areExperimentalFeaturesEnabled}from"./chunk-J57HOSWD.js";import{DefaultPackageManager,SettingsManager,resolveHcodeEnvironment}from"./chunk-G4QPSFBF.js";import{DEFAULT_THEME_NAME,getTerminalTheme,initTheme,loadThemeFromPath,markTerminalColorsPending,resolveThemeSetting,
|
|
3
|
+
setRegisteredThemes,setTerminalColors,setTheme}from"./chunk-JF7FYXAI.js";import{ProcessTerminal,TuiMainScreen,setCapabilityOverrides,setKeybindings}from"./chunk-JYWUOKOI.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,FIRST_TIME_SETUP_ENABLED,PACKAGE_NAME,getAgentDir,getSettingsPath,stripBom}from"./chunk-VFLVWPLZ.js";import{existsSync,readFileSync}from"fs";var OFFICIAL_PACKAGE_NAME="@humain/humain-code",OFFICIAL_APP_NAME="humain-terminal",OFFICIAL_CONFIG_DIR_NAME=".humain-terminal";function isOfficialDistribution({packageName,appName,configDirName}){return packageName===OFFICIAL_PACKAGE_NAME&&appName===OFFICIAL_APP_NAME&&configDirName===OFFICIAL_CONFIG_DIR_NAME}function loadThemes(resources){let themes=[],seen=new Set;for(let resource of resources)if(resource.enabled)try{let loadedTheme=loadThemeFromPath(resource.path);if(loadedTheme.name){if(seen.
|
|
4
|
+
has(loadedTheme.name))continue;seen.add(loadedTheme.name)}themes.push(loadedTheme)}catch{}return themes}async function loadStartupThemes(settingsManager){let globalSettingsManager=SettingsManager.inMemory(settingsManager.getGlobalSettings(),{projectTrusted:!1}),resolvedPaths=await new DefaultPackageManager({cwd:process.cwd(),agentDir:getAgentDir(),settingsManager:globalSettingsManager}).resolve(async()=>"skip");return loadThemes(resolvedPaths.themes)}async function createStartupTui(settingsManager){
|
|
5
|
+
setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),setRegisteredThemes(await loadStartupThemes(settingsManager)),markTerminalColorsPending(),initTheme(resolveThemeSetting(settingsManager.getThemeSetting(),getTerminalTheme())??DEFAULT_THEME_NAME),setKeybindings(KeybindingsManager.create());let ui=new TuiMainScreen(new ProcessTerminal,settingsManager.getShowHardwareCursor(),getAgentDir());return ui.setClearOnShrink(settingsManager.getClearOnShrink()),ui}function startStartupTui(ui,settingsManager){
|
|
6
|
+
ui.start();let themeSetting=settingsManager.getThemeSetting();queryStartupTerminalColors(ui,()=>{setTheme(resolveThemeSetting(themeSetting,getTerminalTheme())??DEFAULT_THEME_NAME)})}function queryStartupTerminalColors(ui,onColors){requestTerminalColors(ui,colors=>{setTerminalColors(colors),onColors(),ui.invalidate(),ui.requestRender()})}async function clearStartupTui(ui){ui.clear(),ui.requestRender(),await new Promise(resolve=>setTimeout(resolve,25))}function shouldRunFirstTimeSetupForDistribution(metadata){
|
|
7
|
+
return FIRST_TIME_SETUP_ENABLED||isOfficialDistribution(metadata)&&areExperimentalFeaturesEnabled()}function shouldRunFirstTimeSetup(settingsPath=getSettingsPath()){if(!shouldRunFirstTimeSetupForDistribution({packageName:PACKAGE_NAME,appName:APP_NAME,configDirName:CONFIG_DIR_NAME})||process.env[ENV_AGENT_DIR])return!1;try{let settings=JSON.parse(stripBom(readFileSync(settingsPath,"utf-8")));return!(typeof settings=="object"&&settings!==null&&"hcodeMetadataDisclosureVersion"in settings&&settings.
|
|
8
|
+
hcodeMetadataDisclosureVersion===1)}catch{return!0}}async function showStartupSelector(settingsManager,title,options){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let settled=!1,finish=async result=>{settled||(settled=!0,await clearStartupTui(ui),ui.stop(),resolve(result))},selector=new ExtensionSelectorComponent(title,options.map(option=>option.label),option=>{finish(options.find(entry=>entry.label===option)?.value)},()=>{finish(void 0)},{tui:ui});ui.addChild(selector),
|
|
9
|
+
ui.setFocus(selector),startStartupTui(ui,settingsManager)})}async function showFirstTimeSetup(settingsManager,origin=resolveHcodeEnvironment().origin){let initialStep=existsSync(getSettingsPath())?"disclosure":"theme",ui=await createStartupTui(settingsManager);return new Promise((resolve,reject)=>{let settled=!1,finish=async result=>{if(!settled){settled=!0;try{result&&await settingsManager.acknowledgeHcodeMetadataDisclosure(result.theme),await clearStartupTui(ui),resolve()}catch(error){reject(error)}finally{
|
|
10
|
+
ui.stop()}}};ui.start();let previewTheme=initialStep==="theme"?getDefaultThemeName():resolveThemeSetting(settingsManager.getThemeSetting(),getTerminalTheme())??DEFAULT_THEME_NAME;setTheme(previewTheme);let component=new FirstTimeSetupComponent({origin,initialStep,tui:ui,onThemePreview:themeName=>{previewTheme=themeName,setTheme(themeName),ui.requestRender()},onSubmit:result=>{finish(result)},onCancel:()=>{finish(void 0)}});ui.addChild(component),ui.setFocus(component),ui.requestRender(),queryStartupTerminalColors(
|
|
11
|
+
ui,()=>setTheme(previewTheme))})}async function showStartupInput(settingsManager,title,placeholder){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let settled=!1,finish=async result=>{settled||(settled=!0,input.dispose(),await clearStartupTui(ui),ui.stop(),resolve(result))},input=new ExtensionInputComponent(title,placeholder,value=>{finish(value)},()=>{finish(void 0)},{tui:ui});ui.addChild(input),ui.setFocus(input),startStartupTui(ui,settingsManager)})}export{createStartupTui,startStartupTui,shouldRunFirstTimeSetupForDistribution,shouldRunFirstTimeSetup,showStartupSelector,showFirstTimeSetup,showStartupInput};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{require_proper_lockfile}from"./chunk-F6ZAYLU2.js";import{getShellConfig}from"./chunk-CRN54O4D.js";import{getAgentDir,getFileRevision,normalizePath,stripBom}from"./chunk-VFLVWPLZ.js";import{__toESM}from"./chunk-JXWJOIH4.js";function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal?signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||
|
|
3
|
+
(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()}):operation}import{execSync,spawnSync}from"child_process";var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(
|
|
4
|
+
index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+
|
|
5
|
+
1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){return env?.[name]||process.env[name]||void 0}function getTemplateEnvVarNames(parts){
|
|
6
|
+
let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0)return;resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return getMissingConfigValueEnvVarNames(
|
|
7
|
+
config,env).length===0}function resolveConfigValue(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommand(reference.config):resolveTemplate(reference.parts,env)}function executeWithConfiguredShell(command){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin",result=spawnSync(shell,commandFromStdin?args:[...args,command],{encoding:"utf-8",input:commandFromStdin?command:void 0,timeout:1e4,stdio:[commandFromStdin?
|
|
8
|
+
"pipe":"ignore","pipe","ignore"],shell:!1,windowsHide:!0});return result.error?result.error.code==="ENOENT"?{executed:!1,value:void 0}:{executed:!0,value:void 0}:result.status!==0?{executed:!0,value:void 0}:{executed:!0,value:(result.stdout??"").trim()||void 0}}catch{return{executed:!1,value:void 0}}}function executeWithDefaultShell(command){try{return execSync(command,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function executeCommandUncached(commandConfig){
|
|
9
|
+
let command=commandConfig.slice(1);return process.platform==="win32"?(()=>{let configuredResult=executeWithConfiguredShell(command);return configuredResult.executed?configuredResult.value:executeWithDefaultShell(command)})():executeWithDefaultShell(command)}function executeCommand(commandConfig){if(commandResultCache.has(commandConfig))return commandResultCache.get(commandConfig);let result=executeCommandUncached(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env){
|
|
10
|
+
let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommandUncached(reference.config):resolveTemplate(reference.parts,env)}function resolveConfigValueOrThrow(config,description,env){let resolvedValue=resolveConfigValueUncached(config,env);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);
|
|
11
|
+
if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}function resolveHeadersOrThrow(headers,description,env){if(!headers)return;let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomBytes}from"crypto";import{closeSync,existsSync,fchmodSync,fchownSync,fstatSync,fsyncSync,mkdirSync,openSync,readFileSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"fs";import{dirname,join}from"path";import{setTimeout as sleep}from"timers/promises";var MAX_EPERM_RETRIES=5;function getRetryableLockErrorCode(error){let code=error instanceof Error&&"code"in error?error.code:void 0;if(code==="ELOCKED"||code==="EPERM"&&process.platform==="win32")return code}var AccountSourceReplacementError=class extends Error{constructor(){super("Stored configuration reference cannot be replaced by account selection or login. Explicit replacement consent is required."),this.name="AccountSourceReplacementError"}},AUTH_FILE_WRITE_OPTIONS={encoding:"utf-8",mode:384};
|
|
12
|
+
function writeFileAtomic(path,content){let target=path,existing;existsSync(path)&&(target=realpathSync(path),existing=statSync(target));let temp=`${target}.${randomBytes(6).toString("hex")}.tmp`,fd=openSync(temp,"wx",AUTH_FILE_WRITE_OPTIONS.mode);try{try{let created=fstatSync(fd);if(existing&&(created.uid!==existing.uid||created.gid!==existing.gid))try{fchownSync(fd,existing.uid,existing.gid)}catch(error){let code=error.code;throw code!=="EPERM"&&code!=="EACCES"?error:new Error("Cannot preserve \
|
|
13
|
+
credential file owner and group; refusing to write in place",{cause:error})}writeFileSync(fd,content,AUTH_FILE_WRITE_OPTIONS.encoding),fchmodSync(fd,existing?existing.mode&4095:AUTH_FILE_WRITE_OPTIONS.mode),fsyncSync(fd)}finally{closeSync(fd)}renameSync(temp,target)}catch(error){throw rmSync(temp,{force:!0}),error}}var sharedAuthFileReadState,FileAuthStorageBackend=class{authPath;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}makePrivate(){let fd=openSync(
|
|
14
|
+
this.authPath,"r");try{fchmodSync(fd,384),fsyncSync(fd)}finally{closeSync(fd)}}ensureParentDir(){let dir=dirname(this.authPath);existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}ensureFileExists(){existsSync(this.authPath)||writeFileSync(this.authPath,"{}",AUTH_FILE_WRITE_OPTIONS)}acquireLockSyncWithRetry(path){for(let attempt=1;;attempt++)try{return import_proper_lockfile.default.lockSync(path)}catch(error){if(!getRetryableLockErrorCode(error)||attempt===10)throw error;let start=Date.now();
|
|
15
|
+
for(;Date.now()-start<20;);}}withLock(fn){this.ensureParentDir(),this.ensureFileExists();let release;try{release=this.acquireLockSyncWithRetry(this.authPath);let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=fn(current);return next!==void 0&&writeFileAtomic(this.authPath,next),result}finally{release&&release()}}async acquireLockAsync(signal,onCompromised){let deadline=Date.now()+3e4,retry=0,epermRetries=0;for(;;){signal?.throwIfAborted();let release;try{
|
|
16
|
+
release=await import_proper_lockfile.default.lock(this.authPath,{retries:0,stale:3e4,onCompromised})}catch(error){signal?.throwIfAborted();let code=getRetryableLockErrorCode(error),remainingMs=deadline-Date.now();if(!code||remainingMs<=0||code==="EPERM"&&++epermRetries>MAX_EPERM_RETRIES)throw error;let baseDelayMs=Math.min(10*2**retry,2e3/2);retry++;let delayMs=Math.min(Math.round(baseDelayMs*(1+Math.random())),remainingMs);signal?await sleep(delayMs,void 0,{signal}):await sleep(delayMs);continue}
|
|
17
|
+
return signal?.aborted&&(await release(),signal.throwIfAborted()),release}}async withLockAsync(fn,options){options?.signal?.throwIfAborted(),this.ensureParentDir(),this.ensureFileExists();let release,lockCompromised=!1,lockCompromisedError,throwIfCompromised=()=>{if(lockCompromised)throw lockCompromisedError??new Error("Auth storage lock was compromised")};try{release=await this.acquireLockAsync(options?.signal,error=>{lockCompromised=!0,lockCompromisedError=error}),throwIfCompromised(),options?.
|
|
18
|
+
signal?.throwIfAborted();let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=await fn(current,checkpoint=>{throwIfCompromised(),options?.signal?.throwIfAborted(),writeFileAtomic(this.authPath,checkpoint),throwIfCompromised()});return throwIfCompromised(),options?.signal?.throwIfAborted(),next!==void 0&&writeFileAtomic(this.authPath,next),throwIfCompromised(),result}finally{if(release)try{await release()}catch{}}}},ReadOnlyAuthStorage=class{authPath;data;constructor(authPath=join(
|
|
19
|
+
getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}load(){if(this.data)return this.data;let parsed;try{parsed=JSON.parse(stripBom(readFileSync(this.authPath,"utf-8")))}catch(error){if(error.code==="ENOENT")return this.data={},this.data;throw new Error(`Failed to read auth.json: ${error instanceof Error?error.message:String(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Invalid auth.json: expected an object");for(let[providerId,credential]of Object.
|
|
20
|
+
entries(parsed)){if(typeof credential!="object"||credential===null||Array.isArray(credential))throw new Error(`Invalid auth.json credential for provider "${providerId}"`);let value=credential;if(value.type==="api_key"){let validKey=value.key===void 0||typeof value.key=="string",validEnv=value.env===void 0||typeof value.env=="object"&&value.env!==null&&!Array.isArray(value.env)&&Object.values(value.env).every(entry=>typeof entry=="string");if(validKey&&validEnv)continue}else if(value.type==="oaut\
|
|
21
|
+
h"&&typeof value.access=="string"&&typeof value.refresh=="string"&&typeof value.expires=="number"&&Number.isFinite(value.expires))continue;throw new Error(`Invalid auth.json credential for provider "${providerId}"`)}return this.data=parsed,this.data}async readRaw(providerId,options){options?.signal?.throwIfAborted();let credential=this.load()[providerId];return options?.signal?.throwIfAborted(),credential?structuredClone(credential):void 0}async read(providerId,options){let credential=await this.
|
|
22
|
+
readRaw(providerId,options);if(credential)return credential.type!=="api_key"||!credential.key||isCommandConfigValue(credential.key)?structuredClone(credential):{...credential,key:resolveConfigValue(credential.key,credential.env)}}async list(options){options?.signal?.throwIfAborted();let credentials=Object.entries(this.load()).map(([providerId,credential])=>({providerId,type:credential.type}));return options?.signal?.throwIfAborted(),credentials}async modify(_providerId,_fn,_options){throw new Error(
|
|
23
|
+
"Read-only credential storage cannot modify auth.json")}async delete(_providerId,_options){throw new Error("Read-only credential storage cannot modify auth.json")}},InMemoryAuthStorageBackend=class{value;asyncChain=Promise.resolve();withLock(fn){let{result,next}=fn(this.value);return next!==void 0&&(this.value=next),result}withLockAsync(fn,options){let previous=this.asyncChain,operation=(async()=>{await previous.catch(()=>{}),options?.signal?.throwIfAborted();let{result,next}=await fn(this.value,
|
|
24
|
+
checkpoint=>{options?.signal?.throwIfAborted(),this.value=checkpoint});return options?.signal?.throwIfAborted(),next!==void 0&&(this.value=next),result})();return this.asyncChain=operation.catch(()=>{}),raceWithAbortSignal(operation,options?.signal)}},AuthStorage=class _AuthStorage{storage;authPath;readState;constructor(storage,authPath){if(this.storage=storage,this.authPath=authPath,this.readState=authPath&&sharedAuthFileReadState?.authPath===authPath?sharedAuthFileReadState.readState:{data:{}},
|
|
25
|
+
authPath&&!sharedAuthFileReadState&&(sharedAuthFileReadState={authPath,readState:this.readState}),authPath){let revision=getFileRevision(authPath);if(revision!==void 0&&revision===this.readState.revision)return}this.reload()}static create(authPath=join(getAgentDir(),"auth.json")){let normalizedAuthPath=normalizePath(authPath);return new _AuthStorage(new FileAuthStorageBackend(normalizedAuthPath),normalizedAuthPath)}static fromStorage(storage){return new _AuthStorage(storage)}static inMemory(data={}){
|
|
26
|
+
let storage=new InMemoryAuthStorageBackend;return storage.withLock(()=>({result:void 0,next:JSON.stringify(data,null,2)})),_AuthStorage.fromStorage(storage)}parseStorageData(content){return content?JSON.parse(stripBom(content)):{}}updateReadState(data,revision){this.readState.data=data,this.readState.revision=revision}reload(){let content,revision;try{this.storage.withLock(current=>(content=current,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:void 0})),this.updateReadState(
|
|
27
|
+
this.parseStorageData(content),revision)}catch{}}async reloadFromStorageAsync(options){return this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),revision=this.authPath?getFileRevision(this.authPath):void 0;return this.updateReadState(currentData,revision),{result:currentData}},options)}async readLatestData(options){if(options?.signal?.throwIfAborted(),!this.authPath){let reload2=this.reloadFromStorageAsync(options);return options?.signal?reload2:reload2.catch(
|
|
28
|
+
()=>this.readState.data)}let revision=getFileRevision(this.authPath);if(revision!==void 0&&revision===this.readState.revision)return this.readState.data;if(!this.readState.reload){let controller=new AbortController,reload2={controller,promise:this.reloadFromStorageAsync({signal:controller.signal}),readers:0};this.readState.reload=reload2,reload2.promise.then(()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)},()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)})}
|
|
29
|
+
let reload=this.readState.reload;reload.readers++;try{let result=raceWithAbortSignal(reload.promise,options?.signal);return options?.signal?await result:await result.catch(()=>this.readState.data)}finally{reload.readers--,reload.readers===0&&this.readState.reload===reload&&(this.readState.reload=void 0,reload.controller.abort())}}async readRaw(provider,options){let credential=(await this.readLatestData(options))[provider];return options?.signal?.throwIfAborted(),credential?structuredClone(credential):
|
|
30
|
+
void 0}async read(provider,options){let credential=await this.readRaw(provider,options);return options?.signal?.throwIfAborted(),credential?.type!=="api_key"||credential.key===void 0?credential:{...credential,key:resolveConfigValue(credential.key,credential.env)}}async modify(provider,fn,options){let latestData=this.readState.data,revision,result=await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),next=await fn(currentData[provider]);if(next===void 0)return latestData=
|
|
31
|
+
currentData,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:currentData[provider]};let merged={...currentData,[provider]:next};return latestData=merged,{result:next,next:JSON.stringify(merged,null,2)}},options);return this.updateReadState(latestData,revision),result}async delete(provider,options){let latestData=this.readState.data;await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content);return latestData=currentData,options?.ifCurrent&&
|
|
32
|
+
!options.ifCurrent(currentData[provider])?{result:void 0}:(delete currentData[provider],{result:void 0,next:JSON.stringify(currentData,null,2)})},options),this.updateReadState(latestData)}async list(options){let entries=Object.entries(await this.readLatestData(options));return options?.signal?.throwIfAborted(),entries.map(([providerId,credential])=>({providerId,type:credential.type}))}},accountCredentialStores=new WeakMap;function getAccountCredentialStore(store,ifCurrent,trackWrite){let previous=accountCredentialStores.
|
|
33
|
+
get(store),rawStore=previous?.store??store,track=trackWrite??previous?.track,trackOperation=track??(operation=>operation),configAware=rawStore instanceof AuthStorage||rawStore instanceof ReadOnlyAuthStorage,poolable=credential=>{if(credential?.type!=="api_key")return credential;if(credential.key?.trim()){if(!configAware)return credential;if(!(isCommandConfigValue(credential.key)||getConfigValueEnvVarNames(credential.key).length>0))return{...credential,key:resolveConfigValue(credential.key,credential.
|
|
34
|
+
env)}}},view={read:async(providerId,options)=>{let current=await(configAware?rawStore.readRaw(providerId,options):rawStore.read(providerId,options));return!ifCurrent||ifCurrent(current)?poolable(current):void 0},list:options=>rawStore.list(options),modify:(providerId,fn,options)=>trackOperation(rawStore.modify(providerId,async current=>{if(ifCurrent&&!ifCurrent(current))return;let eligible=poolable(current),next=await fn(eligible);if(current!==void 0&&eligible===void 0&&next!==void 0)throw new AccountSourceReplacementError;
|
|
35
|
+
return configAware&&next?.type==="api_key"&&next.key!==void 0?{...next,key:next.key.replaceAll("$","$$$$").replace(/^!/,"$!")}:next},options).then(poolable)),delete:(providerId,options)=>trackOperation(rawStore.delete(providerId,ifCurrent||options?.ifCurrent?{...options,ifCurrent:current=>(!ifCurrent||ifCurrent(current))&&(!options?.ifCurrent||options.ifCurrent(poolable(current)))}:options))};return accountCredentialStores.set(view,{store:rawStore,track}),view}function readStoredCredential(providerId,authPath=join(
|
|
36
|
+
getAgentDir(),"auth.json")){try{return JSON.parse(stripBom(readFileSync(normalizePath(authPath),"utf-8")))[providerId]}catch{return}}function toolPatternRegExp(pattern){let source=pattern.split("*").map(part=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`)}function createToolNameMatcher(entries){let names=new Set(entries.filter(entry=>!entry.includes("*"))),patterns=entries.filter(entry=>entry.includes("*")).map(toolPatternRegExp);return name=>names.has(name)||patterns.some(pattern=>pattern.test(name))}var LIST_MCP_RESOURCES_TOOL="list_mcp_resources",LIST_MCP_RESOURCE_TEMPLATES_TOOL="lis\
|
|
37
|
+
t_mcp_resource_templates",READ_MCP_RESOURCE_TOOL="read_mcp_resource",MCP_RESOURCE_TOOLS=new Set([LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,READ_MCP_RESOURCE_TOOL]);function isMcpToolName(name){return name.startsWith("mcp__")||MCP_RESOURCE_TOOLS.has(name)}var MCP_EXPOSURES=["codemode","deferred","direct","hidden"],MCP_EXPOSURE_ALIASES={"codemode-deferred":"codemode"},LOOPBACK_HOSTS=["localhost","127.0.0.1","[::1]"];function isLoopbackRedirectUri(value){if(!URL.canParse(value))return!1;
|
|
38
|
+
let url=new URL(value);return url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)&&url.search===""&&url.hash===""}function isClientMetadataDocumentCallback(callbackUrl){if(callbackUrl===void 0)return!0;let url=new URL(callbackUrl);return url.hostname!=="[::1]"&&url.pathname==="/callback"}var SERVER_NAME=/^[A-Za-z0-9_-]+$/;function mcpNamespace(server){return`mcp__${server.replace(/-/g,"_")}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringRecord(value){
|
|
39
|
+
return isRecord(value)&&Object.values(value).every(entry=>typeof entry=="string")}function validateOAuth(value){if(value===void 0)return;if(!isRecord(value))return"oauth must be an object";if(value.clientId!==void 0&&typeof value.clientId!="string")return"oauth.clientId must be a string";if(value.clientSecret!==void 0&&typeof value.clientSecret!="string")return"oauth.clientSecret must be a string";let port=value.callbackPort;if(port!==void 0&&(typeof port!="number"||!Number.isInteger(port)||port<
|
|
40
|
+
1||port>65535))return"oauth.callbackPort must be a port number";if(value.callbackUrl!==void 0){if(typeof value.callbackUrl!="string"||!isLoopbackRedirectUri(value.callbackUrl))return"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";let urlPort=new URL(value.callbackUrl).port;if(urlPort&&port!==void 0&&Number(urlPort)!==port)return"oauth.callbackUrl and oauth.callbackPort name different ports"}if(value.scope!==void 0&&typeof value.scope!="string")
|
|
41
|
+
return"oauth.scope must be a string";if(value.clientName!==void 0&&(typeof value.clientName!="string"||!value.clientName.trim()))return"oauth.clientName must be a non-empty string";let registration=value.clientRegistration;if(registration!==void 0&®istration!=="auto"&®istration!=="dcr"){if(registration!=="cimd")return'oauth.clientRegistration must be "auto", "dcr", or "cimd"';if(value.clientId!==void 0||value.clientName!==void 0)return'oauth.clientRegistration "cimd" cannot be combined wit\
|
|
42
|
+
h oauth.clientId or oauth.clientName';if(!isClientMetadataDocumentCallback(typeof value.callbackUrl=="string"?value.callbackUrl:void 0))return'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback'}let metadataUrl=value.authServerMetadataUrl;if(metadataUrl!==void 0){let url=typeof metadataUrl=="string"&&URL.canParse(metadataUrl)?new URL(metadataUrl):void 0;if(!url||!(url.protocol==="https:"||url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)))
|
|
43
|
+
return"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]"}}function isExposure(value){return typeof value=="string"&&MCP_EXPOSURES.includes(value)}function resolveExposureAlias(value){return typeof value=="string"?MCP_EXPOSURE_ALIASES[value]??value:value}function resolveExposureAliases(value){let{exposure,toolExposure}=value,resolved={...value};return exposure!==void 0&&(resolved.exposure=resolveExposureAlias(exposure)),isRecord(toolExposure)&&(resolved.
|
|
44
|
+
toolExposure=Object.fromEntries(Object.entries(toolExposure).map(([tool,entry])=>[tool,resolveExposureAlias(entry)]))),resolved}function getMcpToolExposure(config,toolName){let overrides=config.toolExposure??{},exact=overrides[toolName];if(exact!==void 0)return exact;for(let[pattern,exposure]of Object.entries(overrides))if(pattern.includes("*")&&toolPatternRegExp(pattern).test(toolName))return exposure;return config.exposure??"codemode"}function validateMcpServerConfig(name,raw){if(!SERVER_NAME.
|
|
45
|
+
test(name))return`invalid server name "${name}" (use letters, digits, "_" and "-")`;if(!isRecord(raw))return`server "${name}" must be an object`;let value=resolveExposureAliases(raw),{type,exposure,enabled,timeout,toolExposure,description}=value,exposures=MCP_EXPOSURES.map(value2=>`"${value2}"`).join(", ");if(exposure!==void 0&&!isExposure(exposure))return`server "${name}": exposure must be one of ${exposures}`;if(toolExposure!==void 0){if(!isRecord(toolExposure))return`server "${name}": toolExp\
|
|
46
|
+
osure must map tool names to exposures`;for(let[tool,value2]of Object.entries(toolExposure))if(!isExposure(value2))return`server "${name}": toolExposure "${tool}" must be one of ${exposures}`}if(enabled!==void 0&&typeof enabled!="boolean")return`server "${name}": enabled must be a boolean`;if(description!==void 0&&typeof description!="string")return`server "${name}": description must be a string`;if(timeout!==void 0&&(typeof timeout!="number"||!(timeout>0)))return`server "${name}": timeout must \
|
|
47
|
+
be a positive number of seconds`;if(type==="sse")return`server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof value.url=="string"&&(type===void 0||type==="http"||type==="streamable-http")){if(!URL.canParse(value.url)||!/^https?:$/.test(new URL(value.url).protocol))return`server "${name}": url must be an http or https URL`;if(value.headers!==void 0&&!isStringRecord(value.headers))return`server "${name}": headers must map names to strings`;let oauthError=validateOAuth(
|
|
48
|
+
value.oauth);if(oauthError)return`server "${name}": ${oauthError}`;if(value.auth!==void 0){if(!isRecord(value.auth)||typeof value.auth.provider!="string"||!value.auth.provider)return`server "${name}": auth.provider must be a provider name`;let url=new URL(value.url);if(url.protocol!=="https:"&&!LOOPBACK_HOSTS.includes(url.hostname))return`server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`}return value}return typeof value.command=="string"&&(type===void 0||type===
|
|
49
|
+
"stdio")?value.args!==void 0&&!(Array.isArray(value.args)&&value.args.every(arg=>typeof arg=="string"))?`server "${name}": args must be an array of strings`:value.env!==void 0&&!isStringRecord(value.env)?`server "${name}": env must map names to strings`:value.cwd!==void 0&&typeof value.cwd!="string"?`server "${name}": cwd must be a string`:value:`server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`}var McpServerRegistry=class{servers=new Map;changeListener;register(server){
|
|
50
|
+
this.servers.set(server.name,server),this.changeListener?.()}unregister(name,extensionPath){this.servers.get(name)?.extensionPath===extensionPath&&(this.servers.delete(name),this.changeListener?.())}get(name){return this.servers.get(name)}list(){return[...this.servers.values()].map(server=>({...server,config:structuredClone(server.config)}))}setChangeListener(listener){this.changeListener=listener}};export{operationSignal,raceWithAbortSignal,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,AccountSourceReplacementError,FileAuthStorageBackend,ReadOnlyAuthStorage,InMemoryAuthStorageBackend,AuthStorage,getAccountCredentialStore,readStoredCredential,createToolNameMatcher,LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,READ_MCP_RESOURCE_TOOL,isMcpToolName,mcpNamespace,getMcpToolExposure,validateMcpServerConfig,
|
|
51
|
+
McpServerRegistry};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{require_cross_spawn,require_readShebang,require_resolveCommand}from"./chunk-VFLVWPLZ.js";import{__toESM}from"./chunk-JXWJOIH4.js";var JSON_RPC_ERROR_CODES={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603},McpError=class extends Error{code;data;constructor(code,message,data){super(message),this.name="McpError",this.code=code,this.data=data}},McpConnectionClosedError=class extends Error{constructor(message="MCP connection closed"){super(message),this.name="McpConnectionClosedError"}},McpTimeoutError=class extends Error{timeoutMs;constructor(timeoutMs){super(`MCP request\
|
|
3
|
+
timed out after ${timeoutMs}ms`),this.name="McpTimeoutError",this.timeoutMs=timeoutMs}},McpAbortError=class extends Error{constructor(message="MCP request aborted"){super(message),this.name="AbortError"}};function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function toError(value){return value instanceof Error?value:new Error(String(value))}function isJsonRpcId(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)}function isJsonRpcRequest(message){
|
|
4
|
+
return isObject(message)&&message.jsonrpc==="2.0"&&isJsonRpcId(message.id)&&typeof message.method=="string"}function isJsonRpcNotification(message){return isObject(message)&&message.jsonrpc==="2.0"&&!("id"in message)&&typeof message.method=="string"}function isJsonRpcResponse(message){return!isObject(message)||message.jsonrpc!=="2.0"||!isJsonRpcId(message.id)?!1:"result"in message?!("error"in message):!("error"in message)||!isObject(message.error)?!1:typeof message.error.code=="number"&&typeof message.
|
|
5
|
+
error.message=="string"}function parseJsonRpcMessage(value){if(isJsonRpcRequest(value)||isJsonRpcNotification(value)||isJsonRpcResponse(value))return value;throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid JSON-RPC message")}var LATEST_PROTOCOL_VERSION="2025-11-25",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05"];var DEFAULT_REQUEST_TIMEOUT_MS=3e4,MAX_LIST_PAGES=1e3;function validateInitializeResult(value){if(!isObject(value)||typeof value.protocolVersion!="string"||!isObject(value.capabilities)||!isObject(value.serverInfo)||typeof value.serverInfo.name!="string"||typeof value.serverInfo.version!="string"||value.instructions!==void 0&&typeof value.instructions!="string")throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP initialize result");return value}function invalid(message){return new McpError(
|
|
6
|
+
JSON_RPC_ERROR_CODES.invalidRequest,message)}function validateListPage(method,key,value,isItem){let items=isObject(value)?value[key]:void 0;if(!isObject(value)||!Array.isArray(items))throw invalid(`Invalid MCP ${method} result`);for(let item of items)if(!isObject(item)||!isItem(item))throw invalid(`Invalid entry in MCP ${method} result`);let nextCursor=value.nextCursor===null||value.nextCursor===""?void 0:value.nextCursor;if(nextCursor!==void 0&&typeof nextCursor!="string")throw invalid(`Invalid\
|
|
7
|
+
MCP ${method} cursor`);return{items,...nextCursor===void 0?{}:{nextCursor}}}var isTool=tool=>typeof tool.name=="string"&&isObject(tool.inputSchema),isResource=resource=>typeof resource.uri=="string"&&(resource.name===void 0||typeof resource.name=="string"),isResourceTemplate=template=>typeof template.uriTemplate=="string"&&(template.name===void 0||typeof template.name=="string");function toResource(item){return{...item,name:item.name??item.uri}}function toResourceTemplate(item){return{...item,name:item.
|
|
8
|
+
name??item.uriTemplate}}function pageCursor(page){return page.nextCursor===void 0?{}:{nextCursor:page.nextCursor}}function validateReadResourceResult(value){if(!isObject(value)||!Array.isArray(value.contents))throw invalid("Invalid MCP resources/read result");for(let contents of value.contents)if(!isObject(contents)||typeof contents.uri!="string"||typeof contents.text!="string"&&typeof contents.blob!="string")throw invalid("Invalid contents in MCP resources/read result");return value}function validateCallToolResult(value){
|
|
9
|
+
if(!isObject(value)||value.content!==void 0&&!Array.isArray(value.content))throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP tools/call result");return value.content===void 0?{...value,content:[]}:value}var McpClient=class{options;state="idle";transport;nextRequestId=1;serverInfoValue;serverCapabilitiesValue;instructionsValue;protocolVersionValue;pending=new Map;progressRequests=new Map;incoming=new Map;requestHandlers=new Map;notificationListeners=new Map;errorListeners=new Set;closeListeners=new Set;disposers=[];constructor(options){
|
|
10
|
+
this.options=Object.freeze({...options}),this.requestHandlers.set("ping",()=>({}));let roots=options.roots;roots&&this.requestHandlers.set("roots/list",async()=>({roots:[...typeof roots=="function"?await roots():roots]}))}get connectionState(){return this.state}get serverInfo(){return this.serverInfoValue}get serverCapabilities(){return this.serverCapabilitiesValue}get instructions(){return this.instructionsValue}get protocolVersion(){return this.protocolVersionValue}async connect(transport){if(this.
|
|
11
|
+
state!=="idle")throw new Error(`Cannot connect MCP client in ${this.state} state`);this.state="connecting",this.transport=transport,this.disposers=[transport.onMessage(message=>this.handleMessage(message)),transport.onError(error=>this.emitError(error)),transport.onClose(()=>this.handleTransportClose())];try{await transport.start();let capabilities={...this.options.capabilities};this.options.roots&&capabilities.roots===void 0&&(capabilities.roots={});let result=validateInitializeResult(await this.
|
|
12
|
+
requestInternal("initialize",{protocolVersion:this.options.protocolVersion??LATEST_PROTOCOL_VERSION,capabilities,clientInfo:{name:this.options.name,version:this.options.version,...this.options.title===void 0?{}:{title:this.options.title}}},{},!0));if(!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion))throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);return this.protocolVersionValue=result.protocolVersion,this.serverInfoValue=result.serverInfo,
|
|
13
|
+
this.serverCapabilitiesValue=result.capabilities,this.instructionsValue=result.instructions,transport.setProtocolVersion?.(result.protocolVersion),await this.notifyInternal("notifications/initialized",void 0,!0),this.state="connected",result}catch(error){throw await this.close().catch(()=>{}),error}}request(method,params,options={}){return this.requestInternal(method,params,options,!1)}notify(method,params){return this.notifyInternal(method,params,!1)}setRequestHandler(method,handler){return this.
|
|
14
|
+
requestHandlers.set(method,handler),()=>{this.requestHandlers.get(method)===handler&&this.requestHandlers.delete(method)}}onNotification(method,listener){let listeners=this.notificationListeners.get(method)??new Set;return this.notificationListeners.set(method,listeners),listeners.add(listener),()=>{listeners.delete(listener),listeners.size===0&&this.notificationListeners.delete(method)}}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){
|
|
15
|
+
return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}async ping(options={}){await this.request("ping",void 0,options)}async listTools(options={}){return await this.listAll("tools/list","tools",isTool,options)}async listResources(options={}){return(await this.listAll("resources/list","resources",isResource,options)).map(toResource)}async listResourcesPage(cursor,options={}){let page=await this.listPage("resources/list","resources",isResource,cursor,options);return{resources:page.
|
|
16
|
+
items.map(toResource),...pageCursor(page)}}async listResourceTemplates(options={}){return(await this.listAll("resources/templates/list","resourceTemplates",isResourceTemplate,options)).map(toResourceTemplate)}async listResourceTemplatesPage(cursor,options={}){let page=await this.listPage("resources/templates/list","resourceTemplates",isResourceTemplate,cursor,options);return{resourceTemplates:page.items.map(toResourceTemplate),...pageCursor(page)}}async readResource(uri,options={}){return validateReadResourceResult(
|
|
17
|
+
await this.request("resources/read",{uri},options))}async listPage(method,key,isItem,cursor,options){return validateListPage(method,key,await this.request(method,cursor===void 0?void 0:{cursor},options),isItem)}async listAll(method,key,isItem,options){let items=[],cursors=new Set,cursor;for(let pageNumber=0;pageNumber<MAX_LIST_PAGES;pageNumber++){let page=await this.listPage(method,key,isItem,cursor,options);if(items.push(...page.items),page.nextCursor===void 0)return items;if(cursors.has(page.nextCursor))
|
|
18
|
+
throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);cursors.add(page.nextCursor),cursor=page.nextCursor}throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`)}async callTool(name,args,options={}){return validateCallToolResult(await this.request("tools/call",{name,...args===void 0?{}:{arguments:args}},options))}async close(){let transport=this.transport;this.transport=void 0,this.disposeTransportListeners(),this.markClosed(new McpConnectionClosedError),await transport?.
|
|
19
|
+
close()}async requestInternal(method,params,options,allowConnecting){let transport=this.requireTransport(allowConnecting);if(options.signal?.aborted)throw new McpAbortError;let id=this.nextRequestId++,progressToken=options.onProgress?id:void 0,requestParams=progressToken===void 0?params:{...params,_meta:{...isObject(params?._meta)?params._meta:{},progressToken}},message={jsonrpc:"2.0",id,method,...requestParams===void 0?{}:{params:requestParams}};return new Promise((resolve2,reject)=>{let entry={
|
|
20
|
+
resolve:resolve2,reject,timeoutMs:options.timeoutMs??this.options.requestTimeoutMs??DEFAULT_REQUEST_TIMEOUT_MS,timer:void 0,signal:options.signal,onAbort:()=>this.cancelPending(id,new McpAbortError,method!=="initialize",String(options.signal?.reason??"Aborted")),sendController:new AbortController,cancellable:method!=="initialize",onProgress:options.onProgress,progressToken};this.pending.set(id,entry),progressToken!==void 0&&this.progressRequests.set(progressToken,id),options.signal?.addEventListener(
|
|
21
|
+
"abort",entry.onAbort,{once:!0}),this.armTimeout(id,entry),transport.send(message,{signal:entry.sendController.signal}).catch(error=>this.cancelPending(id,error,!1))})}async notifyInternal(method,params,allowConnecting){await this.requireTransport(allowConnecting).send({jsonrpc:"2.0",method,...params===void 0?{}:{params}})}requireTransport(allowConnecting){if(this.transport&&(this.state==="connected"||allowConnecting&&this.state==="connecting"))return this.transport;throw new McpConnectionClosedError(
|
|
22
|
+
`MCP client is ${this.state}`)}handleMessage(message){if(isJsonRpcResponse(message)){this.handleResponse(message);return}if(isJsonRpcRequest(message)){this.handleRequest(message);return}if(isJsonRpcNotification(message)){this.handleNotification(message.method,message.params);return}this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Received invalid JSON-RPC message"))}handleResponse(message){let entry=this.pending.get(message.id);if(!entry){this.emitError(new Error(`Received respon\
|
|
23
|
+
se for unknown MCP request ${String(message.id)}`));return}this.removePending(message.id,entry),"error"in message?entry.reject(new McpError(message.error.code,message.error.message,message.error.data)):entry.resolve(message.result)}async handleRequest(message){let transport=this.transport;if(!transport)return;let handler=this.requestHandlers.get(message.method);if(!handler){await transport.send({jsonrpc:"2.0",id:message.id,error:{code:JSON_RPC_ERROR_CODES.methodNotFound,message:`Method not found\
|
|
24
|
+
: ${message.method}`}}).catch(error=>this.emitError(error));return}let controller=new AbortController;this.incoming.set(message.id,controller);try{let result=await handler(message.params,{signal:controller.signal});await transport.send({jsonrpc:"2.0",id:message.id,result:result??{}})}catch(error){let responseError=error instanceof McpError?{code:error.code,message:error.message,data:error.data}:{code:JSON_RPC_ERROR_CODES.internalError,message:toError(error).message};await transport.send({jsonrpc:"\
|
|
25
|
+
2.0",id:message.id,error:responseError}).catch(sendError=>this.emitError(sendError))}finally{this.incoming.delete(message.id)}}handleNotification(method,params){method==="notifications/progress"?this.handleProgress(params):method==="notifications/cancelled"&&this.handleCancelled(params);for(let listener of this.notificationListeners.get(method)??[])try{listener(params)}catch(error){this.emitError(error)}}handleProgress(params){if(!isObject(params)||!isJsonRpcId(params.progressToken)||typeof params.
|
|
26
|
+
progress!="number")return;let requestId=this.progressRequests.get(params.progressToken),entry=requestId===void 0?void 0:this.pending.get(requestId);if(!(requestId===void 0||!entry)){this.armTimeout(requestId,entry);try{entry.onProgress?.(params)}catch(error){this.emitError(error)}}}handleCancelled(params){isObject(params)&&isJsonRpcId(params.requestId)&&this.incoming.get(params.requestId)?.abort(params.reason)}armTimeout(id,entry){entry.timer&&clearTimeout(entry.timer),!(!Number.isFinite(entry.timeoutMs)||
|
|
27
|
+
entry.timeoutMs<=0)&&(entry.timer=setTimeout(()=>{this.cancelPending(id,new McpTimeoutError(entry.timeoutMs),entry.cancellable,"Request timed out")},entry.timeoutMs))}cancelPending(id,error,notifyServer,reason){let entry=this.pending.get(id);entry&&(this.removePending(id,entry),entry.reject(error),notifyServer&&this.transport&&this.transport.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:id,...reason?{reason}:{}}}).catch(sendError=>this.emitError(sendError)))}removePending(id,entry){
|
|
28
|
+
this.pending.delete(id),entry.timer&&clearTimeout(entry.timer),entry.progressToken!==void 0&&this.progressRequests.delete(entry.progressToken),entry.signal?.removeEventListener("abort",entry.onAbort),entry.sendController.abort()}rejectPending(error){for(let[id,entry]of this.pending)this.removePending(id,entry),entry.reject(error)}handleTransportClose(){this.markClosed(new McpConnectionClosedError)}markClosed(error){let wasClosed=this.state==="closed";this.state="closed",this.rejectPending(error);
|
|
29
|
+
for(let controller of this.incoming.values())controller.abort(error);if(this.incoming.clear(),!wasClosed)for(let listener of[...this.closeListeners])try{listener()}catch(listenerError){this.emitError(listenerError)}}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}disposeTransportListeners(){for(let dispose of this.disposers.splice(0))dispose()}};var import_cross_spawn=__toESM(require_cross_spawn(),1),import_readShebang=__toESM(require_readShebang(),1),import_resolveCommand=__toESM(require_resolveCommand(),1);import{spawn}from"node:child_process";import{lstatSync,statSync}from"node:fs";import{delimiter,isAbsolute,join,resolve}from"node:path";import process from"node:process";var DEFAULT_MAX_MESSAGE_BYTES=16*1024*1024,TransportEvents=class{messageListeners=new Set;errorListeners=new Set;closeListeners=new Set;closeEmitted=!1;onMessage(listener){return this.messageListeners.add(listener),()=>this.messageListeners.delete(listener)}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}emitMessage(message){for(let listener of this.
|
|
30
|
+
messageListeners)listener(message)}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let listener of this.closeListeners)listener()}}};var DEFAULT_MAX_STDERR_BYTES=64*1024,JsonRpcLineReader=class{options;stdoutChunks=[];stdoutPendingBytes=0;discardingStdoutLine=!1;stderrBuffer=Buffer.alloc(0);constructor(options){this.options=options}get stderr(){return this.stderrBuffer.toString("utf8")}readStdout(chunk){let data=Buffer.from(chunk.buffer,chunk.byteOffset,chunk.byteLength),maxMessageBytes=this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES,start=0;for(;;){let newline=data.indexOf(10,start);if(this.discardingStdoutLine){if(newline<
|
|
31
|
+
0)return;this.discardingStdoutLine=!1,start=newline+1;continue}let lineBytes=(newline<0?data.length:newline)-start;if(this.stdoutPendingBytes+lineBytes>maxMessageBytes){if(this.stdoutChunks=[],this.stdoutPendingBytes=0,this.discardingStdoutLine=newline<0,this.options.onError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`)),newline<0)return;start=newline+1;continue}if(newline<0){start<data.length&&(this.stdoutChunks.push(Buffer.from(data.subarray(start))),this.stdoutPendingBytes+=
|
|
32
|
+
lineBytes);return}let line=data.subarray(start,newline);this.stdoutChunks.length>0&&(this.stdoutChunks.push(line),line=Buffer.concat(this.stdoutChunks,this.stdoutPendingBytes+line.length),this.stdoutChunks=[],this.stdoutPendingBytes=0),start=newline+1;let text=line.toString("utf8").replace(/\r$/,"");if(text.trim())try{this.options.onMessage(parseJsonRpcMessage(JSON.parse(text)))}catch(error){this.options.onError(error)}}}readStderr(chunk){let maxStderrBytes=this.options.maxStderrBytes??DEFAULT_MAX_STDERR_BYTES;
|
|
33
|
+
this.stderrBuffer=Buffer.concat([this.stderrBuffer,chunk]),this.stderrBuffer.length>maxStderrBytes&&(this.stderrBuffer=this.stderrBuffer.subarray(-maxStderrBytes)),this.options.onStderr?.(Buffer.from(chunk.buffer,chunk.byteOffset,chunk.byteLength).toString("utf8"))}end(){Buffer.concat(this.stdoutChunks).toString("utf8").trim()&&this.options.onError(new Error("MCP stdio server closed with an incomplete JSON-RPC message")),this.stdoutChunks=[],this.stdoutPendingBytes=0,this.discardingStdoutLine=!1}};var DEFAULT_CLOSE_TIMEOUT_MS=2e3,STDIN_CLOSE_GRACE_MS=500,USE_PROCESS_GROUPS=process.platform!=="win32",liveProcessGroups=new Map,exitHookInstalled=!1,custodyMonitor;function processGroupAlive(child){let pid=child.pid;if(pid===void 0||liveProcessGroups.get(pid)!==child)return!1;try{return process.kill(-pid,0),!0}catch(error){return error.code!=="ESRCH"?!0:(liveProcessGroups.delete(pid),liveProcessGroups.size===0&&custodyMonitor&&(clearInterval(custodyMonitor),custodyMonitor=void 0),!1)}}function isProgramFile(file){
|
|
34
|
+
try{let stats=statSync(file,{throwIfNoEntry:!1});if(stats)return stats.isFile()}catch{}try{let link=lstatSync(file,{throwIfNoEntry:!1});return link!==void 0&&!link.isDirectory()}catch{return!1}}function resolveWindowsServerCommand(command,env){if(/[\\/]/.test(command))return command;let pathKey="PATH"in env?"PATH":Object.keys(env).find(key=>key.toLowerCase()==="path"),dirs=(pathKey?env[pathKey]??"":"").split(delimiter).map(dir=>dir.trim().replace(/^"(.*)"$/,"$1")).filter(dir=>dir&&isAbsolute(dir)),
|
|
35
|
+
pathExtensions=(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean),extensions=command.includes(".")?["",...pathExtensions]:pathExtensions;for(let dir of dirs)for(let extension of extensions){let file=join(dir,command+extension);if(isProgramFile(file))return file}return join(process.env.SystemRoot??"C:\\Windows","humain-code-no-such-command",`${command}.exe`)}function killProcessTree(child,signal){let pid=child.pid;if(process.platform==="win32"&&pid!==void 0){if(child.exitCode!==null)
|
|
36
|
+
return;let taskkill=join(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe");spawn(taskkill,["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>{});return}if(USE_PROCESS_GROUPS&&pid!==void 0&&processGroupAlive(child)){try{process.kill(-pid,signal)}catch{}return}if(!(child.exitCode!==null||child.signalCode!==null))try{child.kill(signal)}catch{}}function installExitHook(){exitHookInstalled||(exitHookInstalled=!0,process.once("exit",()=>{for(let child of liveProcessGroups.
|
|
37
|
+
values())if(!(child.pid===void 0||!processGroupAlive(child)))try{process.kill(-child.pid,"SIGKILL")}catch{}}))}var StdioTransport=class extends TransportEvents{options;child;ownedChild;closing;lines;started=!1;closed=!1;constructor(options){super(),this.options=Object.freeze({...options,args:options.args?[...options.args]:void 0}),this.lines=new JsonRpcLineReader({maxMessageBytes:this.options.maxMessageBytes,maxStderrBytes:this.options.maxStderrBytes,onStderr:this.options.onStderr,onMessage:message=>this.
|
|
38
|
+
emitMessage(message),onError:error=>this.emitError(error)})}get pid(){return this.child?.pid}get stderr(){return this.lines.stderr}async start(){if(this.started)throw new Error("MCP stdio transport already started");if(this.closed)throw new McpConnectionClosedError;this.started=!0;let env=this.options.inheritEnv===!1?{...this.options.env}:{...process.env,...this.options.env},command=this.options.command,args=this.options.args??[];if(process.platform==="win32"){let visited=new Set;for(;;){command=
|
|
39
|
+
resolve(this.options.cwd??"",resolveWindowsServerCommand(command,env)),command=(0,import_resolveCommand.default)({command,options:{env}})??command;let key=command.toLowerCase();if(visited.has(key)||visited.size===32){command=resolveWindowsServerCommand("shebang-chain",{PATH:""});break}visited.add(key);let interpreter=(0,import_readShebang.default)(command);if(!interpreter)break;args=[command,...args],command=interpreter}}let child=(0,import_cross_spawn.default)(command,args,{cwd:this.options.cwd,
|
|
40
|
+
env,stdio:["pipe","pipe",this.options.stderr==="inherit"?"inherit":"pipe"],windowsHide:!0,detached:USE_PROCESS_GROUPS});this.child=child,this.ownedChild=child;let pid=child.pid;USE_PROCESS_GROUPS&&pid!==void 0&&(installExitHook(),liveProcessGroups.set(pid,child),custodyMonitor??=setInterval(()=>{for(let owned of liveProcessGroups.values())processGroupAlive(owned)},250).unref()),child.stdout?.on("data",chunk=>this.lines.readStdout(chunk)),child.stdout?.on("error",error=>this.emitError(error)),child.
|
|
41
|
+
stdin?.on("error",error=>{this.closed||this.emitError(error)}),child.stderr?.on("data",chunk=>this.lines.readStderr(chunk)),child.stderr?.on("error",error=>this.emitError(error)),child.on("close",()=>{this.child=void 0,this.close(),this.lines.end(),this.emitClose()}),await new Promise((resolve2,reject)=>{let onSpawn=()=>{child.off("error",onError),resolve2()},onError=error=>{child.off("spawn",onSpawn),reject(error)};child.once("spawn",onSpawn),child.once("error",onError)}),child.on("error",error=>{
|
|
42
|
+
this.closed||this.emitError(error)})}async send(message){let stdin=this.child?.stdin;if(!this.started||this.closed||!stdin?.writable)throw new McpConnectionClosedError;let payload=`${JSON.stringify(message)}
|
|
43
|
+
`;await new Promise((resolve2,reject)=>{stdin.write(payload,error=>error?reject(error):resolve2())})}async close(){if(this.closing)return this.closing;if(this.closed)return;this.closed=!0;let child=this.ownedChild;if(!child){this.emitClose();return}if(!USE_PROCESS_GROUPS&&(child.exitCode!==null||child.signalCode!==null)){child.stdin?.end();return}let closeTimeoutMs=this.options.closeTimeoutMs??DEFAULT_CLOSE_TIMEOUT_MS;this.closing=new Promise(resolve2=>{let timers=[],escalated=!1,groupAlive=()=>USE_PROCESS_GROUPS&&
|
|
44
|
+
processGroupAlive(child),finish=()=>{for(let timer of timers)clearTimeout(timer);child.off("close",onClose),groupAlive()||(this.ownedChild=void 0),resolve2()},onClose=()=>{(escalated||!groupAlive())&&finish()};child.once("close",onClose);let grace=Math.min(STDIN_CLOSE_GRACE_MS,closeTimeoutMs);timers.push(setTimeout(()=>killProcessTree(child,"SIGTERM"),grace)),timers.push(setTimeout(()=>{escalated=!0,killProcessTree(child,"SIGKILL"),this.child!==child&&finish()},grace+closeTimeoutMs)),USE_PROCESS_GROUPS&&
|
|
45
|
+
timers.push(setInterval(()=>{this.child!==child&&!groupAlive()&&finish()},20)),child.stdin?.end(),this.child!==child&&onClose()}),await this.closing}};var MAX_ERROR_BODY_BYTES=8*1024,ERROR_MESSAGE_BODY_CHARS=500,DEFAULT_RECONNECT_INITIAL_DELAY_MS=1e3,DEFAULT_RECONNECT_MAX_DELAY_MS=3e4,DEFAULT_RECONNECT_MAX_RETRIES=5;async function consumeSseStream(stream,options){let reader=stream.getReader(),decoder=new TextDecoder,signal=options.signal,onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});let buffered="",eventName,eventId,dataLines=[],dataBytes=0,maxEventBytes=options.maxEventBytes??DEFAULT_MAX_MESSAGE_BYTES,
|
|
46
|
+
dispatch=()=>{if(dataLines.length===0){eventName=void 0,eventId=void 0;return}let data=dataLines.join(`
|
|
47
|
+
`);options.onEvent({...eventName?{event:eventName}:{},data,...eventId?{id:eventId}:{}}),eventName=void 0,eventId=void 0,dataLines=[],dataBytes=0},processLine=line=>{if(line===""){dispatch();return}if(line.startsWith(":"))return;let colon=line.indexOf(":"),field=colon<0?line:line.slice(0,colon),value=colon<0?"":line.slice(colon+1);if(value.startsWith(" ")&&(value=value.slice(1)),field==="data"){if(dataBytes+=Buffer.byteLength(value)+(dataLines.length>0?1:0),dataBytes>maxEventBytes)throw new Error(
|
|
48
|
+
`MCP SSE event exceeds ${maxEventBytes} bytes`);dataLines.push(value)}else field==="event"?eventName=value:field==="id"&&!value.includes("\0")?(eventId=value,options.onId?.(value)):field==="retry"&&/^\d+$/.test(value)&&options.onRetry?.(Number(value))},skipLeadingLf=!1,consumeLines=()=>{let start=0;for(let i=0;i<buffered.length;i++){let char=buffered[i];char!=="\r"&&char!==`
|
|
49
|
+
`||(processLine(buffered.slice(start,i)),char==="\r"&&(i+1<buffered.length?buffered[i+1]===`
|
|
50
|
+
`&&i++:skipLeadingLf=!0),start=i+1)}buffered=buffered.slice(start)};try{for(;;){if(signal?.aborted)throw new McpAbortError;let{done,value}=await reader.read();if(signal?.aborted)throw new McpAbortError;if(done)break;let text=decoder.decode(value,{stream:!0});if(skipLeadingLf&&text.length>0&&(text.startsWith(`
|
|
51
|
+
`)&&(text=text.slice(1)),skipLeadingLf=!1),buffered+=text,consumeLines(),Buffer.byteLength(buffered)>maxEventBytes)throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`)}let tail=decoder.decode();skipLeadingLf&&tail.startsWith(`
|
|
52
|
+
`)&&(tail=tail.slice(1)),buffered+=tail,consumeLines(),buffered&&processLine(buffered),dispatch()}finally{signal?.removeEventListener("abort",onAbort),reader.cancel().catch(()=>{}),reader.releaseLock()}}var McpHttpError=class extends Error{status;body;constructor(status,message,body=""){super(message),this.name="McpHttpError",this.status=status,this.body=body}},McpAuthRequiredError=class extends McpHttpError{wwwAuthenticate;constructor(response,body=""){super(401,"MCP server requires authenticat\
|
|
53
|
+
ion",body),this.name="McpAuthRequiredError",this.wwwAuthenticate=response.headers.get("www-authenticate")}},McpSessionExpiredError=class extends McpHttpError{constructor(body=""){super(404,"MCP session expired",body),this.name="McpSessionExpiredError"}};function contentType(response){return response.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()}function needsAuthorization(response){return response.status===401?!0:response.status!==403?!1:/(?:^|[\s,])error="?insufficient_scope"?/i.
|
|
54
|
+
test(response.headers.get("www-authenticate")??"")}function isTransientStatus(status){return status===408||status===429||status>=500}function discard(response){return response.body?.cancel().catch(()=>{})??Promise.resolve()}function describeHttpFailure(status,body){let text=body.trim(),snippet=text.length>ERROR_MESSAGE_BODY_CHARS?`${text.slice(0,ERROR_MESSAGE_BODY_CHARS-3)}...`:text;return`MCP HTTP request failed with status ${status}${snippet?`: ${snippet}`:""}`}async function readResponseText(response,maxBytes,signal,overflow){
|
|
55
|
+
if(!response.body){if(signal.aborted)throw new McpAbortError;return""}let reader=response.body.getReader(),decoder=new TextDecoder,size=0,text="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw new McpAbortError;let{done,value}=await reader.read();if(signal.aborted)throw new McpAbortError;if(done)return text+decoder.decode();let remaining=maxBytes-size;if(value.byteLength>remaining&&overflow==="reject")throw new Error(
|
|
56
|
+
`MCP HTTP message exceeds ${maxBytes} bytes`);if(text+=decoder.decode(value.subarray(0,remaining),{stream:!0}),size+=value.byteLength,overflow==="truncate"&&size>=maxBytes)return text}}finally{signal.removeEventListener("abort",onAbort),reader.cancel().catch(()=>{}),reader.releaseLock()}}var StreamableHttpTransport=class extends TransportEvents{url;options;fetch;controller=new AbortController;started=!1;closed=!1;sessionIdValue;protocolVersion;getStreamStarted=!1;lastToken;constructor(options){super(),
|
|
57
|
+
this.options=Object.freeze({...options,headers:options.headers?{...options.headers}:void 0}),this.url=new URL(options.url);let fetch=options.fetch??globalThis.fetch;this.fetch=(input,init)=>fetch(input,init)}get sessionId(){return this.sessionIdValue}async start(){if(this.started)throw new Error("MCP Streamable HTTP transport already started");if(this.closed)throw new McpConnectionClosedError;this.started=!0}setProtocolVersion(version){this.protocolVersion=version}async send(message,{signal}={}){
|
|
58
|
+
if(!this.started||this.closed)throw new McpConnectionClosedError;let requestSignal=signal?AbortSignal.any([signal,this.controller.signal]):this.controller.signal,response=await this.authorizedFetch("POST",{headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(message)},requestSignal);if(await this.checkResponse(response,requestSignal),this.captureSession(response),!isJsonRpcRequest(message)){await discard(response),"method"in message&&message.
|
|
59
|
+
method==="notifications/initialized"&&this.startGetStream();return}if(response.status===202||response.status===204)throw new McpHttpError(response.status,`MCP server accepted request ${message.method} without a response`);let type=contentType(response);if(type==="application/json"){let body=JSON.parse(await readResponseText(response,this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES,requestSignal,"reject"));for(let item of Array.isArray(body)?body:[body])this.emitMessage(parseJsonRpcMessage(
|
|
60
|
+
item));return}if(type==="text/event-stream"&&response.body){this.consumeResponseStream(response.body,message.id,requestSignal);return}throw await discard(response),new McpHttpError(response.status,`Unsupported MCP response content type: ${type??"missing"}`)}async close(){if(!this.closed){if(this.closed=!0,this.controller.abort(),this.started&&this.sessionIdValue)try{let response=await this.fetch(this.url,{method:"DELETE",headers:this.buildHeaders({},this.lastToken),signal:AbortSignal.timeout(1e3)});
|
|
61
|
+
await discard(response)}catch{}this.emitClose()}}async authorizedFetch(method,init,signal){let onUnauthorized=this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);for(let attempt=0;;attempt++){let{headers,token}=await this.headers(init.headers);if(signal?.aborted)throw new McpAbortError;let response=await this.fetch(this.url,{method,headers,body:init.body,signal:signal??this.controller.signal});if(attempt>0||!onUnauthorized||!needsAuthorization(response))return response;try{
|
|
62
|
+
await onUnauthorized({response,serverUrl:this.url,fetch:this.fetch,token})}finally{await discard(response)}}}async headers(extra={}){let token=await this.options.authProvider?.token();return this.lastToken=token,{headers:this.buildHeaders(extra,token),...token?{token}:{}}}buildHeaders(extra,token){let headers=new Headers(this.options.headers);for(let[name,value]of Object.entries(extra))headers.set(name,value);return this.sessionIdValue&&headers.set("Mcp-Session-Id",this.sessionIdValue),this.protocolVersion&&
|
|
63
|
+
headers.set("MCP-Protocol-Version",this.protocolVersion),token&&headers.set("Authorization",`Bearer ${token}`),headers}captureSession(response){let sessionId=response.headers.get("mcp-session-id");sessionId&&(this.sessionIdValue=sessionId)}async checkResponse(response,signal){if(response.ok)return;let body=await readResponseText(response,MAX_ERROR_BODY_BYTES,signal,"truncate").catch(error=>{if(signal.aborted)throw new McpAbortError;if(error instanceof McpAbortError)throw error;return""});throw response.
|
|
64
|
+
status===401?new McpAuthRequiredError(response,body):response.status===404&&this.sessionIdValue?new McpSessionExpiredError(body):new McpHttpError(response.status,describeHttpFailure(response.status,body),body)}async consumeSse(stream,cursor,onMessage,signal=this.controller.signal){await consumeSseStream(stream,{signal,maxEventBytes:this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES,onId:id=>{cursor.lastEventId=id},onRetry:delayMs=>{cursor.retryMs=delayMs},onEvent:event=>{if(cursor.received=
|
|
65
|
+
!0,!event.data.trim()||event.event!==void 0&&event.event!=="message")return;let message;try{message=parseJsonRpcMessage(JSON.parse(event.data))}catch(error){this.emitError(error);return}onMessage?.(message),this.emitMessage(message)}})}async consumeResponseStream(body,requestId,signal){let cursor={lastEventId:void 0,retryMs:void 0,received:!1},answered=!1,onMessage=message=>{isJsonRpcResponse(message)&&message.id===requestId&&(answered=!0)},stream=body,failure;for(let attempt=0;;){if(stream)try{
|
|
66
|
+
await this.consumeSse(stream,cursor,onMessage,signal),failure=void 0}catch(error){failure=error}if(answered||this.closed||signal.aborted)return;if(failure!==void 0&&!this.isRetryable(failure)||cursor.lastEventId===void 0||attempt>=this.maxRetries())break;if(cursor.received&&(attempt=0),cursor.received=!1,!await this.sleep(this.reconnectDelay(attempt++,cursor.retryMs),signal))return;try{stream=await this.openSseStream(cursor.lastEventId,signal)}catch(error){if(failure=error,!this.isRetryable(error))
|
|
67
|
+
break;stream=void 0}}if(this.closed||signal.aborted)return;let reason=failure===void 0?"stream ended without a response":toError(failure).message;this.emitMessage({jsonrpc:"2.0",id:requestId,error:{code:JSON_RPC_ERROR_CODES.internalError,message:`MCP response stream failed: ${reason}`}})}startGetStream(){this.options.openGetStream===!1||this.getStreamStarted||this.closed||(this.getStreamStarted=!0,this.runGetStream())}async runGetStream(){let cursor={lastEventId:void 0,retryMs:void 0,received:!1};
|
|
68
|
+
for(let attempt=0;!this.closed;){try{let stream=await this.openSseStream(cursor.lastEventId);if(!stream)return;let openedAt=Date.now();await this.consumeSse(stream,cursor),(cursor.received||Date.now()-openedAt>this.maxDelay())&&(attempt=0)}catch(error){if(this.closed)return;if(!this.isRetryable(error)){this.emitError(error);return}}if(cursor.received=!1,attempt>=this.maxRetries()){this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));return}if(!await this.sleep(
|
|
69
|
+
this.reconnectDelay(attempt++,cursor.retryMs)))return}}async openSseStream(lastEventId,signal=this.controller.signal){let response=await this.authorizedFetch("GET",{headers:{accept:"text/event-stream",...lastEventId===void 0?{}:{"last-event-id":lastEventId}}},signal);if(response.status===405){await discard(response);return}await this.checkResponse(response,signal),this.captureSession(response);let type=contentType(response);if(type!=="text/event-stream"||!response.body)throw await discard(response),
|
|
70
|
+
new McpHttpError(response.status,`Unsupported MCP GET response content type: ${type??"missing"}`);return response.body}isRetryable(error){if(error instanceof McpHttpError)return isTransientStatus(error.status);if(error instanceof TypeError)return!0;let code=error?.code;return typeof code=="string"&&(code.startsWith("E")||code.startsWith("UND_ERR"))}reconnectDelay(attempt,serverDelayMs){if(serverDelayMs!==void 0)return serverDelayMs;let initial=this.options.reconnect?.initialDelayMs??DEFAULT_RECONNECT_INITIAL_DELAY_MS;
|
|
71
|
+
return Math.min(initial*2**attempt,this.maxDelay())}maxDelay(){return this.options.reconnect?.maxDelayMs??DEFAULT_RECONNECT_MAX_DELAY_MS}maxRetries(){return this.options.reconnect?.maxRetries??DEFAULT_RECONNECT_MAX_RETRIES}sleep(ms,signal=this.controller.signal){return signal.aborted?Promise.resolve(!1):new Promise(resolve2=>{let onAbort=()=>{clearTimeout(timer),resolve2(!1)},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve2(!0)},ms);timer.unref?.(),signal.addEventListener(
|
|
72
|
+
"abort",onAbort,{once:!0})})}};function blockToLlmContent(block){switch(block.type){case"text":return{type:"text",text:block.text};case"image":return{type:"image",data:block.data,mimeType:block.mimeType};case"audio":return{type:"text",text:`[audio ${block.mimeType} omitted]`};case"resource_link":return{type:"text",text:`${block.name}: ${block.uri}`};case"resource":{let resource=block.resource;return"text"in resource?{type:"text",text:resource.text}:resource.mimeType?.startsWith("image/")?{type:"image",data:resource.blob,mimeType:resource.
|
|
73
|
+
mimeType}:{type:"text",text:`[binary resource ${resource.uri} (${resource.mimeType??"unknown type"}) omitted]`}}default:return{type:"text",text:`[unsupported MCP content ${block.type}]`}}}function toLlmContent(result){let content=(result.content??[]).map(blockToLlmContent);return content.length===0&&result.structuredContent!==void 0&&content.push({type:"text",text:JSON.stringify(result.structuredContent,null,2)}),content}export{JSON_RPC_ERROR_CODES,McpError,isObject,LATEST_PROTOCOL_VERSION,McpClient,toLlmContent,StdioTransport,McpHttpError,McpAuthRequiredError,McpSessionExpiredError,StreamableHttpTransport};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{mcpNamespace,validateMcpServerConfig}from"./chunk-PWUDFU5V.js";import{require_proper_lockfile}from"./chunk-F6ZAYLU2.js";import{CONFIG_DIR_NAME,stripBom}from"./chunk-VFLVWPLZ.js";import{__toESM}from"./chunk-JXWJOIH4.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{chmodSync,existsSync,lstatSync,mkdirSync,readFileSync,realpathSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";var OVERRIDE_KEYS=["enabled","exposure","toolExposure"];function isOverride(value){return value.command===void 0&&value.url===void 0&&value.type===void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readConfigFile(path,scope,state){let{servers,errors}=state;if(!existsSync(path))return;let parsed;try{parsed=JSON.parse(stripBom(readFileSync(path,"utf8")))}catch(error){errors.push(`${path}: ${error instanceof Error?error.message:String(error)}`);
|
|
3
|
+
return}if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers)){errors.push(`${path}: expected an object with an "mcpServers" object`);return}typeof parsed.autoEnableCodemode=="boolean"?state.autoEnableCodemode=parsed.autoEnableCodemode:parsed.autoEnableCodemode!==void 0&&errors.push(`${path}: autoEnableCodemode must be a boolean`);for(let[name,value]of Object.entries(parsed.mcpServers??{})){if(scope==="project"&&isRecord(value)&&isOverride(value)){let base=servers.get(name),
|
|
4
|
+
extra=Object.keys(value).filter(key=>!OVERRIDE_KEYS.includes(key));if(!base)errors.push(`${path}: server "${name}" needs "command" or "url", or a global server to override`);else if(extra.length>0)errors.push(`${path}: server "${name}": an override can only set ${OVERRIDE_KEYS.join(", ")}`);else{let config2=validateMcpServerConfig(name,{...base.config,...value});typeof config2=="string"?errors.push(`${path}: ${config2}`):servers.set(name,{...base,config:config2,override:path})}continue}let config=validateMcpServerConfig(
|
|
5
|
+
name,value);if(typeof config=="string"){errors.push(`${path}: ${config}`);continue}let clash=[...servers.keys()].find(other=>other!==name&&mcpNamespace(other)===mcpNamespace(name));if(clash){errors.push(`${path}: server "${name}" conflicts with "${clash}"`);continue}if(scope==="project"&&"url"in config&&config.auth){errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);continue}servers.set(name,{name,config,source:path,scope})}}function loadMcpConfig(options){let state={
|
|
6
|
+
servers:new Map,errors:[]};readConfigFile(join(options.agentDir,"mcp.json"),"global",state);let projectConfig=options.projectTrusted?join(options.cwd,CONFIG_DIR_NAME,"mcp.json"):void 0;return projectConfig&&readConfigFile(projectConfig,"project",state),{servers:[...state.servers.values()],...state.autoEnableCodemode===void 0?{}:{autoEnableCodemode:state.autoEnableCodemode},errors:state.errors,...projectConfig?{projectConfig}:{}}}function updateMcpServerConfig(path,name,patch,options={}){editMcpServers(
|
|
7
|
+
path,(servers,parsed)=>{let server=servers?.[name];if(server===void 0&&options.override&&(server={},parsed.mcpServers={...servers,[name]:server}),!isRecord(server))throw new Error(`${path} does not define MCP server "${name}"`);let keepDefaults=isOverride(server);return patch.enabled!==void 0&&(patch.enabled&&!keepDefaults?delete server.enabled:server.enabled=patch.enabled),patch.exposure!==void 0&&(patch.exposure==="codemode"&&!keepDefaults?delete server.exposure:server.exposure=patch.exposure),
|
|
8
|
+
!0})}function addMcpServerConfig(path,name,config){return updateMcpConfigLocked(path,servers=>{let replaced=servers[name]!==void 0;return servers[name]=config,replaced})}function updateMcpConfigLocked(path,mutate){let result;return editMcpServers(path,(servers,parsed)=>{let target=servers??{},before=JSON.stringify(target);return result=mutate(target),JSON.stringify(target)===before?!1:(parsed.mcpServers=target,!0)}),result}function removeMcpServerConfig(path,name){if(!existsSync(path))return!1;let removed=!1;return editMcpServers(path,servers=>!servers||servers[name]===void 0?!1:(delete servers[name],removed=!0,!0)),removed}function parseMcpFile(path,text){let parsed=text===void 0?{}:JSON.parse(stripBom(text));if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers))throw new Error(`${path}: expected an object with an "mcpServers" object`);return{parsed,servers:isRecord(parsed.mcpServers)?parsed.
|
|
9
|
+
mcpServers:void 0}}function canonicalMcpPath(path){mkdirSync(dirname(path),{recursive:!0});let isSymlink=!1;try{isSymlink=lstatSync(path).isSymbolicLink()}catch(error){if(error.code!=="ENOENT")throw error;return join(realpathSync(dirname(path)),basename(path))}try{return realpathSync(path)}catch(error){throw isSymlink&&error.code==="ENOENT"?new Error(`Refusing to modify ${path}: it is a dangling symlink. Create its target or remove the link.`):error}}function acquireMcpLockSync(path){let dir=dirname(
|
|
10
|
+
path),maxAttempts=50,delayMs=20;for(let attempt=1;;attempt++)try{return import_proper_lockfile.default.lockSync(dir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;let start=Date.now();for(;Date.now()-start<delayMs;);}}function editMcpServers(path,edit){let canonical=canonicalMcpPath(path),release=acquireMcpLockSync(canonical);try{if(canonicalMcpPath(path)!==
|
|
11
|
+
canonical)throw new Error(`Refusing to modify ${path}: it changed while waiting for the lock. Retry.`);let text=existsSync(canonical)?readFileSync(canonical,"utf8"):void 0,{parsed,servers}=parseMcpFile(path,text);if(!edit(servers,parsed))return;let indent=text&&/^([ \t]+)\S/m.exec(text)?.[1]||" ",targetPath=canonical,tempPath=join(dirname(targetPath),`${randomUUID()}.tmp`),mode=text!==void 0?statSync(targetPath).mode&511:384;try{writeFileSync(tempPath,`${JSON.stringify(parsed,null,indent)}
|
|
12
|
+
`,{flag:"wx",mode}),chmodSync(tempPath,mode),renameSync(tempPath,targetPath)}catch(error){throw rmSync(tempPath,{force:!0}),error}}finally{release()}}export{loadMcpConfig,updateMcpServerConfig,addMcpServerConfig,updateMcpConfigLocked,removeMcpServerConfig};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{createHash}from"node:crypto";import{chmodSync,closeSync,constants,fchmodSync,fstatSync,lstatSync,mkdirSync,openSync,realpathSync}from"node:fs";import{dirname,join,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_KEY=/^[a-f0-9]{16}$/,canonicalTmpDir;function getCanonicalTmpDir(){return canonicalTmpDir??=realpathSync(
|
|
3
|
+
"/tmp"),canonicalTmpDir}function assertRepositoryKey(repositoryKey){if(repositoryKey!=="device"&&!REPOSITORY_KEY.test(repositoryKey))throw new Error(`Invalid repository key: ${repositoryKey}`)}function getCoordinationRuntimePaths(agentDir,repositoryKey,uid=process.getuid?.()??0){assertRepositoryKey(repositoryKey);let runtimeDir=join(agentDir,"coordination",repositoryKey),defaultSocket=join(runtimeDir,"broker.sock"),socketPath=Buffer.byteLength(defaultSocket,"utf8")<=MAX_SOCKET_PATH_BYTES?defaultSocket:
|
|
4
|
+
join(getCanonicalTmpDir(),`humain-coord-${uid}`,`${repositoryKey==="device"?`${createHash("sha256").update(agentDir).digest("hex").slice(0,16)}-device`:repositoryKey}.sock`);return{runtimeDir,socketPath,pidPath:join(runtimeDir,"broker.pid"),spawnLockPath:join(runtimeDir,"broker.spawn.lock"),mailboxPath:join(runtimeDir,"mailbox.json"),pendingAsksDir:join(runtimeDir,"pending-asks"),artifactsDir:join(runtimeDir,"artifacts")}}function currentUid(){return process.getuid?.()}function resolveCoordinationRuntimePaths(agentDir,repositoryKey,uid){
|
|
5
|
+
assertRepositoryKey(repositoryKey),mkdirSync(agentDir,{recursive:!0,mode:COORDINATION_DIR_MODE});let canonicalAgentDir=realpathSync(agentDir);return assertSafeAncestors(join(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){
|
|
6
|
+
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!==
|
|
7
|
+
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){
|
|
8
|
+
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 \
|
|
9
|
+
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.
|
|
10
|
+
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(
|
|
11
|
+
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)}
|
|
12
|
+
function restrictRuntimeFile(filePath){chmodSync(filePath,COORDINATION_FILE_MODE)}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){
|
|
13
|
+
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\
|
|
14
|
+
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.
|
|
15
|
+
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;
|
|
16
|
+
if(headerBytes=0,payload=null,payloadBytes=0,payloadLength=0,!reportMessage(framePayload))return}}}export{COORDINATION_DIR_MODE,COORDINATION_FILE_MODE,COORDINATION_PROTOCOL_NAME,COORDINATION_PROTOCOL_VERSION,MAX_MESSAGE_TEXT_BYTES,getCanonicalTmpDir,getCoordinationRuntimePaths,resolveCoordinationRuntimePaths,assertSafeAncestors,assertCanonicalRuntimeDir,ensureRuntimeDir,ensureCoordinationRuntimeDir,assertPrivateSocket,restrictRuntimeFile,framePayloadBytes,writeMessage,createMessageReader};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{AGENT_MONITOR_PROTOCOL,AGENT_MONITOR_ROLE,MAX_AGENTS,MAX_REPORT_FRAME_BYTES,MAX_SNAPSHOT_FRAME_BYTES,parseHello,parseReport,resolveAgentMonitorPaths}from"./chunk-TGDPZCSW.js";import{COORDINATION_ROLE_ENV,MAX_RUNTIME_TEXT_FILE_BYTES,writeTextAtomic}from"./chunk-6PNQYO6A.js";import{createMessageReader,ensureCoordinationRuntimeDir,restrictRuntimeFile,writeMessage}from"./chunk-R5OOX7RW.js";import{getAgentDir}from"./chunk-VFLVWPLZ.js";import{lstatSync,unlinkSync}from"node:fs";import net from"node:net";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+(.*)$/;
|
|
3
|
+
function parsePsOutput(stdout){let entries=[];for(let line of stdout.split(`
|
|
4
|
+
`)){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$/.
|
|
5
|
+
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{
|
|
6
|
+
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:"\
|
|
7
|
+
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(
|
|
8
|
+
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.
|
|
9
|
+
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 errorCode(error){return error?.code}function isListening(socketPath){
|
|
10
|
+
return new Promise(resolve=>{let socket=net.connect(socketPath),settle=live=>{clearTimeout(timer),socket.destroy(),resolve(live)},timer=setTimeout(()=>settle(!0),1e3);socket.once("connect",()=>settle(!0)),socket.once("error",error=>{let code=errorCode(error);settle(code!=="ECONNREFUSED"&&code!=="ENOENT")})})}function unlinkQuietly(path){try{unlinkSync(path)}catch{}}function fitFrame(agents){let budget=MAX_SNAPSHOT_FRAME_BYTES-4096,kept=[];for(let agent of agents.slice(0,MAX_AGENTS)){if(budget-=Buffer.
|
|
11
|
+
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;
|
|
12
|
+
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.
|
|
13
|
+
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((resolve,reject)=>{let onError=error=>{this.server.off("listening",onListening),reject(error)},onListening=()=>{this.server.off("error",onError),resolve()};this.server.once("error",onError),this.server.once("listening",onListening),this.server.listen(this.paths.socketPath)})}async claimSocket(){try{await this.
|
|
14
|
+
listen();return}catch(error){if(errorCode(error)!=="EADDRINUSE")throw error}if(await isListening(this.paths.socketPath))throw new MonitorAlreadyRunningError(this.paths.socketPath);if(!lstatSync(this.paths.socketPath).isSocket())throw new Error(`Refusing to remove ${this.paths.socketPath}: it is not a socket`);unlinkSync(this.paths.socketPath);try{await this.listen()}catch(error){throw errorCode(error)==="EADDRINUSE"?new MonitorAlreadyRunningError(this.paths.socketPath):error}}accept(socket){if(this.
|
|
15
|
+
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.revealTimer),
|
|
16
|
+
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==="health"&&typeof typed.
|
|
17
|
+
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.has(socket))throw new Error(
|
|
18
|
+
"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 message");let report=parseReport(
|
|
19
|
+
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{this.
|
|
20
|
+
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.
|
|
21
|
+
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(
|
|
22
|
+
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[
|
|
23
|
+
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.
|
|
24
|
+
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\
|
|
25
|
+
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{runAgentMonitorCommand};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{APIError,Stream}from"./chunk-
|
|
2
|
+
import{APIError,Stream}from"./chunk-SCINMV4X.js";import{createSseDecoder,decodeSseText}from"./chunk-YZMQXAJM.js";function isAbortError(error){return typeof error=="object"&&error!==null&&("name"in error&&error.name==="AbortError"||"message"in error&&String(error.message).includes("FetchRequestCanceledException"))}var LOG_LEVELS={off:0,error:200,warn:300,info:400,debug:500};function logError(client,message){if(!client){console.error(message);return}let level=LOG_LEVELS[client.logLevel??"off"];client.logger&&level!==void 0&&level>=LOG_LEVELS.error&&client.logger.error(message)}async function*iterateOpenAISseMessages(body,signal){
|
|
3
3
|
let reader=body.getReader(),decoder=new TextDecoder("utf-8",{ignoreBOM:!0}),state=createSseDecoder({stripLineBom:!0}),closed=!1,failed=!1,cancellation,cancel=()=>(closed||cancellation||(cancellation=reader.cancel(),cancellation.catch(()=>{})),cancellation),onAbort=()=>queueMicrotask(()=>{cancel()});signal.addEventListener("abort",onAbort,{once:!0}),signal.aborted&&onAbort();try{for(;;){if(signal.aborted)return;let result;try{result=await reader.read()}catch(error){if(signal.aborted&&(isAbortError(
|
|
4
4
|
error)||error===signal.reason))return;throw error}if(signal.aborted)return;if(result.done){closed=!0;break}for(let event of decodeSseText(state,decoder.decode(result.value,{stream:!0}),!1)){if(signal.aborted)return;yield event}}for(let event of decodeSseText(state,decoder.decode(),!0)){if(signal.aborted)return;yield event}}catch(error){if(failed=!0,!signal.aborted||!isAbortError(error)&&error!==signal.reason)throw error}finally{if(signal.removeEventListener("abort",onAbort),!closed){let pending=cancel();
|
|
5
5
|
pending&&!failed&&!signal.aborted&&await pending}reader.releaseLock()}}function parseEventData(data,client){try{return JSON.parse(data)}catch{throw logError(client,"Could not parse message into JSON:"),logError(client,"From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}}async function*iterateOpenAIStream(stream,response,client){if(!(stream instanceof Stream)||!response.body){yield*stream;return}let controller=stream.controller,done=!1,receivedCompletionSentinel=!1,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|