@ai-agent-forge/agent-forge 0.87.0 → 0.88.1
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 +56 -0
- package/README.md +2 -2
- package/bundled-plugins/agent-loop-policy/agent-forge.json +19 -0
- package/bundled-plugins/agent-loop-policy/dist/entry.d.ts +28 -0
- package/bundled-plugins/agent-loop-policy/dist/entry.d.ts.map +1 -0
- package/bundled-plugins/agent-loop-policy/dist/entry.js +69 -0
- package/bundled-plugins/agent-loop-policy/dist/entry.js.map +1 -0
- package/bundled-plugins/agent-loop-policy/dist/loop-guard.d.ts +199 -0
- package/bundled-plugins/agent-loop-policy/dist/loop-guard.d.ts.map +1 -0
- package/bundled-plugins/agent-loop-policy/dist/loop-guard.js +208 -0
- package/bundled-plugins/agent-loop-policy/dist/loop-guard.js.map +1 -0
- package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.d.ts +17 -0
- package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.d.ts.map +1 -0
- package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.js +18 -0
- package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.js.map +1 -0
- package/bundled-plugins/agent-loop-policy/plugin.json +7 -0
- package/bundled-plugins/coding-tools/agent-forge.json +19 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/bash.d.ts +5 -44
- package/bundled-plugins/coding-tools/dist/bash.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/bash.js +15 -119
- package/bundled-plugins/coding-tools/dist/bash.js.map +1 -0
- package/bundled-plugins/coding-tools/dist/capability.d.ts +25 -0
- package/bundled-plugins/coding-tools/dist/capability.d.ts.map +1 -0
- package/bundled-plugins/coding-tools/dist/capability.js +98 -0
- package/bundled-plugins/coding-tools/dist/capability.js.map +1 -0
- package/bundled-plugins/coding-tools/dist/config.d.ts +8 -0
- package/bundled-plugins/coding-tools/dist/config.d.ts.map +1 -0
- package/bundled-plugins/coding-tools/dist/config.js +8 -0
- package/bundled-plugins/coding-tools/dist/config.js.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/edit.d.ts +3 -3
- package/bundled-plugins/coding-tools/dist/edit.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/edit.js +12 -10
- package/bundled-plugins/coding-tools/dist/edit.js.map +1 -0
- package/bundled-plugins/coding-tools/dist/entry.d.ts +14 -0
- package/bundled-plugins/coding-tools/dist/entry.d.ts.map +1 -0
- package/bundled-plugins/coding-tools/dist/entry.js +23 -0
- package/bundled-plugins/coding-tools/dist/entry.js.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/find.d.ts +4 -4
- package/bundled-plugins/coding-tools/dist/find.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/find.js +10 -8
- package/bundled-plugins/coding-tools/dist/find.js.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/grep.d.ts +3 -3
- package/bundled-plugins/coding-tools/dist/grep.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/grep.js +10 -8
- package/bundled-plugins/coding-tools/dist/grep.js.map +1 -0
- package/bundled-plugins/coding-tools/dist/index.d.ts +17 -0
- package/bundled-plugins/coding-tools/dist/index.d.ts.map +1 -0
- package/bundled-plugins/coding-tools/dist/index.js +17 -0
- package/bundled-plugins/coding-tools/dist/index.js.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/ls.d.ts +3 -3
- package/bundled-plugins/coding-tools/dist/ls.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/ls.js +8 -6
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/ls.js.map +1 -1
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/powershell.d.ts +2 -1
- package/bundled-plugins/coding-tools/dist/powershell.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/powershell.js +6 -3
- package/bundled-plugins/coding-tools/dist/powershell.js.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/read.d.ts +3 -3
- package/bundled-plugins/coding-tools/dist/read.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/read.js +15 -13
- package/bundled-plugins/coding-tools/dist/read.js.map +1 -0
- package/bundled-plugins/coding-tools/dist/types.d.ts +74 -0
- package/bundled-plugins/coding-tools/dist/types.d.ts.map +1 -0
- package/bundled-plugins/coding-tools/dist/types.js +28 -0
- package/bundled-plugins/coding-tools/dist/types.js.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/write.d.ts +2 -2
- package/bundled-plugins/coding-tools/dist/write.d.ts.map +1 -0
- package/{dist/core/tools → bundled-plugins/coding-tools/dist}/write.js +11 -9
- package/bundled-plugins/coding-tools/dist/write.js.map +1 -0
- package/bundled-plugins/coding-tools/plugin.json +10 -0
- package/bundled-plugins/compaction-policy/agent-forge.json +19 -0
- package/bundled-plugins/compaction-policy/dist/branch-summary-policy.d.ts +6 -0
- package/bundled-plugins/compaction-policy/dist/branch-summary-policy.d.ts.map +1 -0
- package/bundled-plugins/compaction-policy/dist/branch-summary-policy.js +19 -0
- package/bundled-plugins/compaction-policy/dist/branch-summary-policy.js.map +1 -0
- package/bundled-plugins/compaction-policy/dist/compaction-policy.d.ts +6 -0
- package/bundled-plugins/compaction-policy/dist/compaction-policy.d.ts.map +1 -0
- package/bundled-plugins/compaction-policy/dist/compaction-policy.js +38 -0
- package/bundled-plugins/compaction-policy/dist/compaction-policy.js.map +1 -0
- package/bundled-plugins/compaction-policy/dist/entry.d.ts +13 -0
- package/bundled-plugins/compaction-policy/dist/entry.d.ts.map +1 -0
- package/bundled-plugins/compaction-policy/dist/entry.js +23 -0
- package/bundled-plugins/compaction-policy/dist/entry.js.map +1 -0
- package/bundled-plugins/compaction-policy/plugin.json +10 -0
- package/bundled-plugins/mcp-http/dist/index.d.ts +8 -0
- package/bundled-plugins/mcp-http/dist/index.d.ts.map +1 -0
- package/bundled-plugins/mcp-http/dist/index.js +8 -0
- package/bundled-plugins/mcp-http/dist/index.js.map +1 -0
- package/bundled-plugins/mcp-http/dist/mcp-http.d.ts.map +1 -0
- package/{dist/plugins → bundled-plugins/mcp-http/dist}/mcp-http.js +1 -1
- package/bundled-plugins/mcp-http/dist/mcp-http.js.map +1 -0
- package/bundled-plugins/overflow-policy/agent-forge.json +19 -0
- package/bundled-plugins/overflow-policy/dist/entry.d.ts +16 -0
- package/bundled-plugins/overflow-policy/dist/entry.d.ts.map +1 -0
- package/bundled-plugins/overflow-policy/dist/entry.js +35 -0
- package/bundled-plugins/overflow-policy/dist/entry.js.map +1 -0
- package/bundled-plugins/overflow-policy/plugin.json +10 -0
- package/bundled-plugins/provider-failover/agent-forge.json +19 -0
- package/bundled-plugins/provider-failover/dist/entry.d.ts +8 -0
- package/bundled-plugins/provider-failover/dist/entry.d.ts.map +1 -0
- package/bundled-plugins/provider-failover/dist/entry.js +8 -0
- package/bundled-plugins/provider-failover/dist/entry.js.map +1 -0
- package/bundled-plugins/provider-failover/dist/provider-failover.d.ts +122 -0
- package/bundled-plugins/provider-failover/dist/provider-failover.d.ts.map +1 -0
- package/{dist/core/extensions → bundled-plugins/provider-failover/dist}/provider-failover.js +149 -61
- package/bundled-plugins/provider-failover/dist/provider-failover.js.map +1 -0
- package/bundled-plugins/provider-failover/plugin.json +7 -0
- package/bundled-plugins/retry-policy/agent-forge.json +19 -0
- package/bundled-plugins/retry-policy/dist/entry.d.ts +16 -0
- package/bundled-plugins/retry-policy/dist/entry.d.ts.map +1 -0
- package/bundled-plugins/retry-policy/dist/entry.js +34 -0
- package/bundled-plugins/retry-policy/dist/entry.js.map +1 -0
- package/bundled-plugins/retry-policy/plugin.json +10 -0
- package/dist/bundle/.build-manifest.json +105 -183
- package/dist/bundle/chunks/{anthropic-messages-ALDZBUKI.js → anthropic-messages-PLAKXR73.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-A2WJWZFB.js → azure-openai-responses-OUWQ2AZD.js} +1 -1
- package/dist/bundle/chunks/{chunk-CIX3FSBK.js → chunk-A3JYRWB6.js} +1 -1
- package/dist/bundle/chunks/{chunk-SQFG22WN.js → chunk-AC2FIS4G.js} +1 -1
- package/dist/bundle/chunks/chunk-AQLNTW2B.js +664 -0
- package/dist/bundle/chunks/chunk-D3ARGZFR.js +13 -0
- package/dist/bundle/chunks/{chunk-YJCQVXW5.js → chunk-HTEVUY7F.js} +1 -1
- package/dist/bundle/chunks/{chunk-Y7HXTASS.js → chunk-HV64ASMT.js} +1 -1
- package/dist/bundle/chunks/chunk-LZOEQITZ.js +855 -0
- package/dist/bundle/chunks/{chunk-7ZY7IXZD.js → chunk-TRDNDS6A.js} +1 -1
- package/dist/bundle/chunks/chunk-Z72JWUZ4.js +4 -0
- package/dist/bundle/chunks/{google-generative-ai-NIB4WONV.js → google-generative-ai-DLII6DAT.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-DCPYUEUO.js → google-vertex-G7BZL7GM.js} +1 -1
- package/dist/bundle/chunks/image-resize-worker.js +3 -3
- package/dist/bundle/chunks/{mistral-conversations-OC6LA5XL.js → mistral-conversations-JXUK24ID.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-IO2X4Y7L.js → openai-codex-responses-5GSGFIPG.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-XYQQHETU.js → openai-completions-EI2I6DTG.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-DLIRN3CI.js → openai-responses-AUJQ3NWT.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-E6RRYBO7.js → pi-messages-PWU2VJMR.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-WF6WRHP7.js +5 -0
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/client.js +1 -1
- package/dist/bundle/index.js +3 -3
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/capabilities/builtin.d.ts +1 -1
- package/dist/capabilities/builtin.d.ts.map +1 -1
- package/dist/capabilities/builtin.js +5 -0
- package/dist/capabilities/builtin.js.map +1 -1
- package/dist/cli/auth-check.d.ts.map +1 -1
- package/dist/cli/auth-check.js +14 -2
- package/dist/cli/auth-check.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js +1 -1
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/plugin-command.d.ts.map +1 -1
- package/dist/cli/plugin-command.js +17 -1
- package/dist/cli/plugin-command.js.map +1 -1
- package/dist/config.d.ts +2 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +5 -6
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-bash.d.ts +1 -1
- package/dist/core/agent-session-bash.d.ts.map +1 -1
- package/dist/core/agent-session-bash.js +1 -1
- package/dist/core/agent-session-bash.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts +6 -10
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +21 -112
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-internal.d.ts +1 -7
- package/dist/core/agent-session-internal.d.ts.map +1 -1
- package/dist/core/agent-session-internal.js.map +1 -1
- package/dist/core/agent-session-loop.d.ts +4 -3
- package/dist/core/agent-session-loop.d.ts.map +1 -1
- package/dist/core/agent-session-loop.js +9 -6
- package/dist/core/agent-session-loop.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts +1 -1
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +32 -4
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +30 -9
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session-tools.d.ts.map +1 -1
- package/dist/core/agent-session-tools.js +5 -1
- package/dist/core/agent-session-tools.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -33
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +61 -67
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/extensions/bootstrap-agent-loop.d.ts +23 -151
- package/dist/core/extensions/bootstrap-agent-loop.d.ts.map +1 -1
- package/dist/core/extensions/bootstrap-agent-loop.js +28 -290
- package/dist/core/extensions/bootstrap-agent-loop.js.map +1 -1
- package/dist/core/extensions/capability-runtime-types.d.ts +5 -3
- package/dist/core/extensions/capability-runtime-types.d.ts.map +1 -1
- package/dist/core/extensions/capability-runtime-types.js.map +1 -1
- package/dist/core/extensions/capability-runtime.d.ts.map +1 -1
- package/dist/core/extensions/capability-runtime.js +42 -6
- package/dist/core/extensions/capability-runtime.js.map +1 -1
- package/dist/core/extensions/index.d.ts +12 -5
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +12 -5
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/virtual-modules.js +65 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -1
- package/dist/core/facade/coding-agent-facade.d.ts +1 -7
- package/dist/core/facade/coding-agent-facade.d.ts.map +1 -1
- package/dist/core/facade/coding-agent-facade.js +0 -3
- package/dist/core/facade/coding-agent-facade.js.map +1 -1
- package/dist/core/i18n/locales/zh-cn/cli.d.ts.map +1 -1
- package/dist/core/i18n/locales/zh-cn/cli.js +3 -1
- package/dist/core/i18n/locales/zh-cn/cli.js.map +1 -1
- package/dist/core/i18n/locales/zh-cn/core-contract-core.d.ts +1 -1
- package/dist/core/i18n/locales/zh-cn/core-contract-core.d.ts.map +1 -1
- package/dist/core/i18n/locales/zh-cn/core-contract-core.js +1 -1
- package/dist/core/i18n/locales/zh-cn/core-contract-core.js.map +1 -1
- package/dist/core/i18n/locales/zh-cn/core-contract-extensions.d.ts.map +1 -1
- package/dist/core/i18n/locales/zh-cn/core-contract-extensions.js +2 -4
- package/dist/core/i18n/locales/zh-cn/core-contract-extensions.js.map +1 -1
- package/dist/core/i18n/locales/zh-cn/core-errors.d.ts.map +1 -1
- package/dist/core/i18n/locales/zh-cn/core-errors.js +3 -1
- package/dist/core/i18n/locales/zh-cn/core-errors.js.map +1 -1
- package/dist/core/i18n/locales/zh-cn/interactive-mode.d.ts.map +1 -1
- package/dist/core/i18n/locales/zh-cn/interactive-mode.js +2 -0
- package/dist/core/i18n/locales/zh-cn/interactive-mode.js.map +1 -1
- package/dist/core/i18n/locales/zh-cn/tui-components-selectors.d.ts.map +1 -1
- package/dist/core/i18n/locales/zh-cn/tui-components-selectors.js +0 -2
- package/dist/core/i18n/locales/zh-cn/tui-components-selectors.js.map +1 -1
- package/dist/core/model-config.d.ts +0 -1
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +9 -1
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +3 -3
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/provider-composer.d.ts +2 -2
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +7 -8
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/sdk.d.ts +18 -3
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +267 -76
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +9 -20
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +20 -54
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/bash-operations.d.ts +41 -0
- package/dist/core/tools/bash-operations.d.ts.map +1 -0
- package/dist/core/tools/bash-operations.js +113 -0
- package/dist/core/tools/bash-operations.js.map +1 -0
- package/dist/core/tools/index.d.ts +12 -36
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -117
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/readme-path.d.ts +3 -0
- package/dist/core/tools/readme-path.d.ts.map +1 -0
- package/dist/core/tools/readme-path.js +15 -0
- package/dist/core/tools/readme-path.js.map +1 -0
- package/dist/index.d.ts +3 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -39
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +3 -2
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +0 -2
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +2 -7
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -6
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +6 -28
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +0 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +9 -25
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +0 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +23 -36
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +0 -8
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +0 -12
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +0 -9
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +0 -19
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/plugins/ecosystem/cli.d.ts.map +1 -1
- package/dist/plugins/ecosystem/cli.js +14 -2
- package/dist/plugins/ecosystem/cli.js.map +1 -1
- package/dist/plugins/ecosystem/node-npm-registry-source.d.ts +7 -2
- package/dist/plugins/ecosystem/node-npm-registry-source.d.ts.map +1 -1
- package/dist/plugins/ecosystem/node-npm-registry-source.js +64 -9
- package/dist/plugins/ecosystem/node-npm-registry-source.js.map +1 -1
- package/dist/plugins/ecosystem/node-plugin-acquisition-host.d.ts.map +1 -1
- package/dist/plugins/ecosystem/node-plugin-acquisition-host.js +6 -0
- package/dist/plugins/ecosystem/node-plugin-acquisition-host.js.map +1 -1
- package/dist/plugins/ecosystem/node-plugin-bootstrap.d.ts +9 -2
- package/dist/plugins/ecosystem/node-plugin-bootstrap.d.ts.map +1 -1
- package/dist/plugins/ecosystem/node-plugin-bootstrap.js +23 -0
- package/dist/plugins/ecosystem/node-plugin-bootstrap.js.map +1 -1
- package/dist/plugins/ecosystem/plugin-bootstrap.d.ts +9 -1
- package/dist/plugins/ecosystem/plugin-bootstrap.d.ts.map +1 -1
- package/dist/plugins/ecosystem/plugin-bootstrap.js +5 -0
- package/dist/plugins/ecosystem/plugin-bootstrap.js.map +1 -1
- package/dist/profiles/builtin-suites.d.ts +5 -1
- package/dist/profiles/builtin-suites.d.ts.map +1 -1
- package/dist/profiles/builtin-suites.js +6 -1
- package/dist/profiles/builtin-suites.js.map +1 -1
- package/dist/utils/photon.d.ts +2 -2
- package/dist/utils/photon.d.ts.map +1 -1
- package/dist/utils/photon.js +2 -2
- package/dist/utils/photon.js.map +1 -1
- package/docs/compaction.md +1 -3
- package/docs/docs.json +4 -0
- package/docs/index.md +1 -0
- package/docs/mcp.md +103 -0
- package/docs/models.md +14 -22
- package/docs/providers.md +0 -1
- package/docs/rpc.md +1 -26
- package/docs/sdk.md +4 -6
- package/docs/settings.md +9 -12
- package/docs/skills.md +1 -9
- package/docs/usage.md +1 -1
- package/examples/extensions/bash-spawn-hook/index.ts +7 -2
- package/examples/extensions/built-in-tool-renderer/index.ts +4 -2
- package/examples/extensions/minimal-mode/index.ts +2 -2
- package/examples/extensions/truncated-tool/index.ts +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/extensions/with-deps/plugin.json +1 -1
- package/examples/sdk/10-settings.ts +2 -4
- package/examples/sdk/12-full-control.ts +1 -2
- package/package.json +3 -4
- package/dist/bundle/chunks/chunk-6ZKDNZHA.js +0 -145
- package/dist/bundle/chunks/chunk-BFC2BDVJ.js +0 -13
- package/dist/bundle/chunks/chunk-MOHOLL3F.js +0 -1456
- package/dist/bundle/chunks/virtual-modules-KZ5DRH7Q.js +0 -2
- package/dist/core/extensions/bootstrap-branch-summary-policy.d.ts +0 -7
- package/dist/core/extensions/bootstrap-branch-summary-policy.d.ts.map +0 -1
- package/dist/core/extensions/bootstrap-branch-summary-policy.js +0 -28
- package/dist/core/extensions/bootstrap-branch-summary-policy.js.map +0 -1
- package/dist/core/extensions/bootstrap-compaction-policy.d.ts +0 -7
- package/dist/core/extensions/bootstrap-compaction-policy.d.ts.map +0 -1
- package/dist/core/extensions/bootstrap-compaction-policy.js +0 -82
- package/dist/core/extensions/bootstrap-compaction-policy.js.map +0 -1
- package/dist/core/extensions/bootstrap-overflow-policy.d.ts +0 -7
- package/dist/core/extensions/bootstrap-overflow-policy.d.ts.map +0 -1
- package/dist/core/extensions/bootstrap-overflow-policy.js +0 -30
- package/dist/core/extensions/bootstrap-overflow-policy.js.map +0 -1
- package/dist/core/extensions/bootstrap-retry-policy.d.ts +0 -7
- package/dist/core/extensions/bootstrap-retry-policy.d.ts.map +0 -1
- package/dist/core/extensions/bootstrap-retry-policy.js +0 -29
- package/dist/core/extensions/bootstrap-retry-policy.js.map +0 -1
- package/dist/core/extensions/bootstrap-tools.d.ts +0 -20
- package/dist/core/extensions/bootstrap-tools.d.ts.map +0 -1
- package/dist/core/extensions/bootstrap-tools.js +0 -36
- package/dist/core/extensions/bootstrap-tools.js.map +0 -1
- package/dist/core/extensions/microcompact.d.ts +0 -80
- package/dist/core/extensions/microcompact.d.ts.map +0 -1
- package/dist/core/extensions/microcompact.js +0 -134
- package/dist/core/extensions/microcompact.js.map +0 -1
- package/dist/core/extensions/provider-failover.d.ts +0 -106
- package/dist/core/extensions/provider-failover.d.ts.map +0 -1
- package/dist/core/extensions/provider-failover.js.map +0 -1
- package/dist/core/tools/bash.d.ts.map +0 -1
- package/dist/core/tools/bash.js.map +0 -1
- package/dist/core/tools/edit.d.ts.map +0 -1
- package/dist/core/tools/edit.js.map +0 -1
- package/dist/core/tools/find.d.ts.map +0 -1
- package/dist/core/tools/find.js.map +0 -1
- package/dist/core/tools/grep.d.ts.map +0 -1
- package/dist/core/tools/grep.js.map +0 -1
- package/dist/core/tools/ls.d.ts.map +0 -1
- package/dist/core/tools/powershell.d.ts.map +0 -1
- package/dist/core/tools/powershell.js.map +0 -1
- package/dist/core/tools/read.d.ts.map +0 -1
- package/dist/core/tools/read.js.map +0 -1
- package/dist/core/tools/write.d.ts.map +0 -1
- package/dist/core/tools/write.js.map +0 -1
- package/dist/plugins/mcp-http.d.ts.map +0 -1
- package/dist/plugins/mcp-http.js.map +0 -1
- package/dist/profile/child-facade.d.ts +0 -44
- package/dist/profile/child-facade.d.ts.map +0 -1
- package/dist/profile/child-facade.js +0 -56
- package/dist/profile/child-facade.js.map +0 -1
- package/dist/profile/dependency-wiring.d.ts +0 -48
- package/dist/profile/dependency-wiring.d.ts.map +0 -1
- package/dist/profile/dependency-wiring.js +0 -56
- package/dist/profile/dependency-wiring.js.map +0 -1
- package/dist/profile/domain-recovery.d.ts +0 -60
- package/dist/profile/domain-recovery.d.ts.map +0 -1
- package/dist/profile/domain-recovery.js +0 -94
- package/dist/profile/domain-recovery.js.map +0 -1
- package/dist/profile/first-roles.d.ts +0 -30
- package/dist/profile/first-roles.d.ts.map +0 -1
- package/dist/profile/first-roles.js +0 -83
- package/dist/profile/first-roles.js.map +0 -1
- package/dist/profile/goal-plugin.d.ts +0 -38
- package/dist/profile/goal-plugin.d.ts.map +0 -1
- package/dist/profile/goal-plugin.js +0 -132
- package/dist/profile/goal-plugin.js.map +0 -1
- package/dist/profile/plan-plugin.d.ts +0 -44
- package/dist/profile/plan-plugin.d.ts.map +0 -1
- package/dist/profile/plan-plugin.js +0 -157
- package/dist/profile/plan-plugin.js.map +0 -1
- package/dist/profile/policy-manifest.d.ts +0 -53
- package/dist/profile/policy-manifest.d.ts.map +0 -1
- package/dist/profile/policy-manifest.js +0 -53
- package/dist/profile/policy-manifest.js.map +0 -1
- package/dist/profile/role-assembly.d.ts +0 -47
- package/dist/profile/role-assembly.d.ts.map +0 -1
- package/dist/profile/role-assembly.js +0 -31
- package/dist/profile/role-assembly.js.map +0 -1
- package/dist/profile/role-catalog.d.ts +0 -43
- package/dist/profile/role-catalog.d.ts.map +0 -1
- package/dist/profile/role-catalog.js +0 -132
- package/dist/profile/role-catalog.js.map +0 -1
- package/dist/profile/role-orchestrator.d.ts +0 -123
- package/dist/profile/role-orchestrator.d.ts.map +0 -1
- package/dist/profile/role-orchestrator.js +0 -195
- package/dist/profile/role-orchestrator.js.map +0 -1
- package/dist/profile/role-runner.d.ts +0 -99
- package/dist/profile/role-runner.d.ts.map +0 -1
- package/dist/profile/role-runner.js +0 -79
- package/dist/profile/role-runner.js.map +0 -1
- package/dist/profile/root-facade.d.ts +0 -36
- package/dist/profile/root-facade.d.ts.map +0 -1
- package/dist/profile/root-facade.js +0 -49
- package/dist/profile/root-facade.js.map +0 -1
- package/dist/profile/skill-discovery-wiring.d.ts +0 -58
- package/dist/profile/skill-discovery-wiring.d.ts.map +0 -1
- package/dist/profile/skill-discovery-wiring.js +0 -80
- package/dist/profile/skill-discovery-wiring.js.map +0 -1
- package/dist/profile/state-store.d.ts +0 -62
- package/dist/profile/state-store.d.ts.map +0 -1
- package/dist/profile/state-store.js +0 -144
- package/dist/profile/state-store.js.map +0 -1
- package/dist/profile/todo-plugin.d.ts +0 -37
- package/dist/profile/todo-plugin.d.ts.map +0 -1
- package/dist/profile/todo-plugin.js +0 -137
- package/dist/profile/todo-plugin.js.map +0 -1
- package/dist/server/create-harness.d.ts +0 -26
- package/dist/server/create-harness.d.ts.map +0 -1
- package/dist/server/create-harness.js +0 -106
- package/dist/server/create-harness.js.map +0 -1
- /package/{dist/plugins → bundled-plugins/mcp-http/dist}/mcp-http.d.ts +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGzC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAUrE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjG,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EACN,qBAAqB,GAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAGN,kBAAkB,GAElB,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAsMxD,8EAA8E;AAC9E,+EAA2D;AAC3D,8EAA8E;AAE9E,gEAAgE;AAChE,MAAM,mBAAmB,GAAG,UAAU,CAAC;AACvC,qFAAqF;AACrF,MAAM,YAAY,GAAG,UAAU,CAAC;AAChC,gGAAgG;AAChG,MAAM,m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xE,GAAG,CAAC,OAAO,CAAC,8BAA8B,KAAK,SAAS;YACvD,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,8BAA8B,EAAE,OAAO,CAAC,8BAA8B,EAAE,CAAC;KAC9E,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ThinkingLevel } from \"@agent-forge/agent-core\";\nimport type { Api, CredentialStore, Model } from \"@agent-forge/ai\";\nimport { CONFIG_DIR_NAME, getAgentDir, VERSION } from \"../config.ts\";\nimport type { HostFactsV1 } from \"../plugins/ecosystem/types.ts\";\nimport type { ObservabilityPlugin } from \"../plugins/observability-types.ts\";\nimport type {\n\tBuiltinPluginManifestOverridesV1,\n\tBuiltinPluginProfileIdV1,\n\tBuiltinPluginProfileResolutionV1,\n} from \"../profile/plugin-profiles.ts\";\nimport type { VerifiedToolPluginV1 } from \"../profile/profile-assembly.ts\";\nimport type { SuiteDefinition } from \"../profiles/builtin-suites.ts\";\nimport { createSuiteAssembly, resolveSuiteId, SUITE_ENV_VAR } from \"../profiles/suite-loader.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { EXPERIMENTAL_PUBLIC_API_VERSION } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport {\n\ttype CreateAgentSessionOptions,\n\ttype CreateAgentSessionResult,\n\tcreateAgentSession,\n\ttype InstalledCapabilityPluginV1,\n} from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SessionStartMetadata } from \"./session-start.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { ToolDefinition } from \"./tools/tool-definition.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\t/**\n\t * Credential storage used by the default model runtime (D-067 phase 1):\n\t * forwarded to `ModelRuntime.create` when `modelRuntime` is omitted.\n\t * Ignored when an explicit `modelRuntime` is supplied. Defaults to the\n\t * file at `<agentDir>/auth.json`.\n\t */\n\tcredentials?: CredentialStore;\n\tmodelRuntimeSignal?: AbortSignal;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n\t/**\n\t * Explicit suite id (highest resolution priority, 设计 §9). Without it the\n\t * suite resolves via AGENT_FORGE_SUITE, then settings, then \"coding\".\n\t */\n\tsuite?: string;\n\t/**\n\t * Wire the full suite assembly (agents.md three-level chain, system prompt\n\t * gate, skill/extension association filters, MCP registration pool) into\n\t * these services' DefaultResourceLoader. Default false: services built\n\t * without it keep the plain loader behavior (evals and testkit\n\t * determinism). When true, the suite id is resolved exactly once here and\n\t * exposed as AgentSessionServices.suiteId so session creation reuses it\n\t * instead of resolving again. The MCP pool (设计 §4/§5) additionally reads\n\t * the mcp.json config surface, filters it by associations.mcp, and\n\t * materializes the injected servers as capability-plugin manifests\n\t * (AgentSessionServices.mcpCapabilityPluginPaths).\n\t */\n\tsuiteAssembly?: boolean;\n\t/** Optional domain plugin profile selected for this suite. */\n\tpluginProfileId?: BuiltinPluginProfileIdV1;\n\t/** Optional subset of plugins from the selected builtin Profile. */\n\tselectedPluginIds?: readonly string[];\n\t/** Optional plugin IDs disabled within the selected builtin Profile. */\n\tdisabledPluginIds?: readonly string[];\n\tpluginHost?: HostFactsV1;\n\tverifiedPlugins?: readonly VerifiedToolPluginV1[];\n\t/** Explicit host-owned active installed manifests; never discovered implicitly. */\n\tmanifestOverrides?: BuiltinPluginManifestOverridesV1;\n\t/**\n\t * Verified active installations (D-075 S2 installed-code-loading) from the\n\t * host's active-binding resolution; forwarded to session creation so their\n\t * plugin.json paths enter the sdk's candidate pool for profile members.\n\t */\n\tinstalledCapabilityPlugins?: readonly InstalledCapabilityPluginV1[];\n\t/** Host diagnostics from active-install resolution; no package data is retained. */\n\tpluginBindingDiagnostics?: readonly AgentSessionRuntimeDiagnostic[];\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartMetadata;\n\tmodel?: Model<Api>;\n\tstreamFn?: CreateAgentSessionOptions[\"streamFn\"];\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcapabilityMode?: CreateAgentSessionOptions[\"capabilityMode\"];\n\tdiscoverCapabilityPlugins?: CreateAgentSessionOptions[\"discoverCapabilityPlugins\"];\n\t/**\n\t * Session trace collection (设计 §4.4/§6), forwarded to createAgentSession.\n\t * Omitted keeps the sdk default (tracing on); hosts pass `false` for\n\t * `--no-trace`.\n\t */\n\ttraceEnabled?: CreateAgentSessionOptions[\"traceEnabled\"];\n\t/**\n\t * Host-process logger forwarded to createAgentSession (设计 §5). Omitted\n\t * keeps the sdk's explicit no-logging contract (instrumentation no-ops).\n\t */\n\thostLogger?: CreateAgentSessionOptions[\"hostLogger\"];\n\tcapabilityPluginPaths?: CreateAgentSessionOptions[\"capabilityPluginPaths\"];\n\tcontextStrategyName?: CreateAgentSessionOptions[\"contextStrategyName\"];\n\tretryPolicyName?: CreateAgentSessionOptions[\"retryPolicyName\"];\n\tcompactionPolicyName?: CreateAgentSessionOptions[\"compactionPolicyName\"];\n\toverflowPolicyName?: CreateAgentSessionOptions[\"overflowPolicyName\"];\n\tbranchSummaryPolicyName?: CreateAgentSessionOptions[\"branchSummaryPolicyName\"];\n\t/** Host adapter for cancellable interaction tasks, forwarded to createAgentSession. */\n\tinteractionHost?: CreateAgentSessionOptions[\"interactionHost\"];\n\t/**\n\t * 覆盖 services 自带 loader。pooled runner 的叶子会话用它注入子任务档案的\n\t * `systemPromptAppend`(追加语义,不替换继承内容);缺省沿用 services 的 loader。\n\t */\n\tresourceLoader?: CreateAgentSessionOptions[\"resourceLoader\"];\n\t/**\n\t * Forwarded to createAgentSession. Headless subagent runners pass `false` so a\n\t * runner task session stays a leaf (no nested agent tasks; D-045 increment 2b).\n\t */\n\tenableAgentTasks?: CreateAgentSessionOptions[\"enableAgentTasks\"];\n\tcustomTools?: ToolDefinition[];\n\t/**\n\t * Explicit suite id forwarded to createAgentSession. When omitted, the\n\t * services' resolved suiteId (suiteAssembly: true) is used; without either,\n\t * createAgentSession resolves the suite itself.\n\t */\n\tsuite?: string;\n\t/**\n\t * Wire the suite's capability surface (方案系统 M3) onto the created\n\t * sessions. Default: on when the services ran the suite assembly\n\t * (suiteAssembly: true, so first-party entries get the builtin capability\n\t * whitelist and plugin-pool filtering); otherwise off, matching the sdk's\n\t * caller-supplied-loader assembly boundary.\n\t */\n\tsuiteCapabilityWiring?: boolean;\n\t/**\n\t * 子代理通信面的宿主接线(D-060 S5 pooled parity):pooled runner 的叶子会话\n\t * 用它注入 post/drainInbox 闭包(身份绑定到叶子会话,信箱为文件承载、跨进程)。\n\t */\n\tsubagentCommunicationWiring?: CreateAgentSessionOptions[\"subagentCommunicationWiring\"];\n\t/**\n\t * 承载退役切片 1(生产 CLI 默认 pooled):转发 createAgentSession 的\n\t * self-invocation 自动池化声明。仅真实 CLI 装配传 true。\n\t */\n\tsubagentPoolFromSelfInvocation?: CreateAgentSessionOptions[\"subagentPoolFromSelfInvocation\"];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\t/**\n\t * /metrics 命令的数据源共享 ref(observability 插件工厂创建时写入\n\t * plugin.getMetrics、dispose 时置空;宿主装配完成后读取接进命令 options)。\n\t * 空 = 插件未挂载(/metrics 显示未装配警告)。\n\t */\n\tobservabilityGetMetricsRef?: { current?: ObservabilityPlugin[\"getMetrics\"] };\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n\t/**\n\t * Suite id resolved for these services when `suiteAssembly` was requested;\n\t * undefined when assembly was off (no suite filtering was applied here).\n\t */\n\tsuiteId?: string;\n\tpluginProfile?: BuiltinPluginProfileResolutionV1;\n\tpluginProfileId?: BuiltinPluginProfileIdV1;\n\t/**\n\t * Verified active installations (D-075 S2) forwarded from the services\n\t * options; createAgentSessionFromServices passes them to the sdk's\n\t * installed-code-loading candidate pool.\n\t */\n\tinstalledCapabilityPlugins?: readonly InstalledCapabilityPluginV1[];\n\t/**\n\t * Capability-plugin manifest paths materialized for the suite's MCP\n\t * registration pool (M4, 设计 §4/§5). Defined only when `suiteAssembly`\n\t * injected at least one associated mcp.json server;\n\t * createAgentSessionFromServices appends them to the created session's\n\t * capabilityPluginPaths.\n\t */\n\tmcpCapabilityPluginPaths?: readonly string[];\n\t/**\n\t * Plugin ids of the MCP pool servers configured with `deferredTools: true`.\n\t * Their tools register normally but stay out of the default active set; the\n\t * session's tool_search tool discovers and activates them on demand.\n\t */\n\tmcpDeferredToolPluginIds?: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// Suite MCP registration pool (方案系统 M4: MCP 配置面, 设计 §4/§5)\n// ---------------------------------------------------------------------------\n\n/** User-level MCP config file directly inside the agent dir. */\nconst MCP_CONFIG_FILENAME = \"mcp.json\";\n/** Generated per-server capability-plugin manifests live below this agentDir dir. */\nconst MCP_POOL_DIR = \"mcp/pool\";\n/** Shared stdio bridge module inside the pool dir (leading \"_\" keeps server names distinct). */\nconst MCP_POOL_BRIDGE_DIR = \"_bridge\";\n/** Server names are associations keys and pool directory names; \"_\" is reserved for the bridge. */\nconst MCP_SERVER_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * Implementation backing url-configured pool entries (createMcpHttpServerPlugin).\n * Sources resolve first so development always runs the current implementation;\n * published installs ship only dist, so dist is the fallback.\n */\nconst MCP_HTTP_PLUGIN_SOURCE_PATH = fileURLToPath(new URL(\"../plugins/mcp-http.ts\", import.meta.url));\nconst MCP_HTTP_PLUGIN_DIST_PATH = fileURLToPath(new URL(\"../../dist/plugins/mcp-http.js\", import.meta.url));\n\n/** One MCP server resolved from an mcp.json configuration file. */\nexport interface SuiteMcpServerV1 {\n\t/** Server name: the associations.mcp match key and the pool directory name. */\n\treadonly name: string;\n\t/** stdio launch command; undefined for remote HTTP servers (`url` set). */\n\treadonly command?: string;\n\treadonly args: readonly string[];\n\t/** Remote HTTP endpoint; undefined for stdio servers (`command` set). */\n\treadonly url?: string;\n\t/**\n\t * Custom request headers sent with every request to a remote HTTP server;\n\t * undefined for stdio servers (`headers` there only contributes a\n\t * diagnostic and is never forwarded).\n\t */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/**\n\t * Config layer the server came from. \"project\" (`<cwd>/.agent-forge/mcp.json`)\n\t * is the third layer (设计 §4) and always passes; \"user\"\n\t * (`<agentDir>/mcp.json`) injects only when associated.\n\t */\n\treadonly scope: \"user\" | \"project\";\n\t/** Generated capability-plugin manifest path for this server. */\n\treadonly manifestPath: string;\n\t/** Whether the server's tools stay out of the default active set until tool_search activates them. */\n\treadonly deferred: boolean;\n}\n\nexport interface SuiteMcpPoolV1 {\n\t/** Injected servers in deterministic order (project first, then user). */\n\treadonly servers: readonly SuiteMcpServerV1[];\n\t/** Manifest paths ready for the session's capabilityPluginPaths channel. */\n\treadonly manifestPaths: readonly string[];\n\t/** Plugin ids whose tools are registered but excluded from the default active set. */\n\treadonly deferredPluginIds: readonly string[];\n\t/**\n\t * Diagnostics: unreadable/invalid config files, filtered non-associated\n\t * servers, project-overridden duplicates, and dangling associations.\n\t * Reported, never thrown (设计 §11.3).\n\t */\n\treadonly diagnostics: readonly string[];\n}\n\ninterface McpServerConfigV1 {\n\treadonly command?: string;\n\treadonly args: readonly string[];\n\treadonly url?: string;\n\t/** Custom request headers for remote HTTP servers; ignored (with a diagnostic) on stdio entries. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\treadonly deferredTools?: boolean;\n}\n\n/**\n * Remote MCP URLs accept only http/https; any other protocol or unparseable\n * value is a configuration error, not a fallback path.\n */\nfunction isHttpUrl(value: string): boolean {\n\ttry {\n\t\tconst protocol = new URL(value).protocol;\n\t\treturn protocol === \"http:\" || protocol === \"https:\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Reads one mcp.json (`{ \"mcpServers\": { \"<name>\": { \"command\", \"args\" } } }`\n * for stdio servers, or `{ \"url\" }` for remote HTTP servers). Each entry must\n * carry exactly one of \"command\" and \"url\". Corruption tolerance: a missing\n * file is an empty config; an unreadable or malformed file, and invalid\n * per-server entries, contribute a diagnostic and are skipped — never thrown.\n */\nfunction parseMcpConfig(path: string): {\n\tservers: Map<string, McpServerConfigV1>;\n\tdiagnostics: string[];\n} {\n\tconst servers = new Map<string, McpServerConfigV1>();\n\tconst diagnostics: string[] = [];\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(readFileSync(path, \"utf8\"));\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { servers, diagnostics };\n\t\tdiagnostics.push(\n\t\t\t`MCP config at ${path} is unreadable; ignoring it. Errors: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t\treturn { servers, diagnostics };\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tdiagnostics.push(`MCP config at ${path} must be an object with an \"mcpServers\" map; ignoring it.`);\n\t\treturn { servers, diagnostics };\n\t}\n\tconst mcpServers = (value as Record<string, unknown>).mcpServers;\n\tif (mcpServers === undefined) return { servers, diagnostics };\n\tif (typeof mcpServers !== \"object\" || mcpServers === null || Array.isArray(mcpServers)) {\n\t\tdiagnostics.push(`MCP config at ${path} must carry an \"mcpServers\" object; ignoring it.`);\n\t\treturn { servers, diagnostics };\n\t}\n\tfor (const [name, entry] of Object.entries(mcpServers as Record<string, unknown>)) {\n\t\tif (!MCP_SERVER_NAME_PATTERN.test(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server name \"${name}\" in ${path} is invalid (must match ${MCP_SERVER_NAME_PATTERN.source}); ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} must be an object with a \"command\" or \"url\"; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst config = entry as Record<string, unknown>;\n\t\tif (config.url !== undefined && (typeof config.url !== \"string\" || config.url.trim().length === 0)) {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} requires \"url\" to be a non-empty string; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst hasCommand = typeof config.command === \"string\" && config.command.trim().length > 0;\n\t\tconst hasUrl = typeof config.url === \"string\" && config.url.trim().length > 0;\n\t\tif (hasCommand && hasUrl) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" in ${path} accepts either \"command\" (stdio server) or \"url\" (remote HTTP server), not both; ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasCommand && !hasUrl) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" in ${path} requires a non-empty string \"command\" (stdio server) or \"url\" (remote HTTP server); ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasUrl && !isHttpUrl(config.url as string)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" in ${path} requires \"url\" to be a valid http:// or https:// URL; ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\tconfig.args !== undefined &&\n\t\t\t(!Array.isArray(config.args) || !config.args.every((arg) => typeof arg === \"string\"))\n\t\t) {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} requires \"args\" to be a string array; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (config.deferredTools !== undefined && typeof config.deferredTools !== \"boolean\") {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} requires \"deferredTools\" to be a boolean; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (config.headers !== undefined) {\n\t\t\tif (hasCommand) {\n\t\t\t\t// Same acceptance style as a url entry carrying args: the entry\n\t\t\t\t// loads, but the field belongs to the other transport shape.\n\t\t\t\tdiagnostics.push(\n\t\t\t\t\t`MCP server \"${name}\" in ${path} carries \"headers\" but headers only apply to remote \"url\" (HTTP) servers; ignoring them.`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst headersValid =\n\t\t\t\t\ttypeof config.headers === \"object\" &&\n\t\t\t\t\tconfig.headers !== null &&\n\t\t\t\t\t!Array.isArray(config.headers) &&\n\t\t\t\t\tObject.values(config.headers as Record<string, unknown>).every(\n\t\t\t\t\t\t(headerValue) => typeof headerValue === \"string\" && headerValue.length > 0,\n\t\t\t\t\t);\n\t\t\t\tif (!headersValid) {\n\t\t\t\t\tdiagnostics.push(\n\t\t\t\t\t\t`MCP server \"${name}\" in ${path} requires \"headers\" to be an object with non-empty string values; ignoring it.`,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tservers.set(name, {\n\t\t\targs: (config.args as readonly string[] | undefined) ?? [],\n\t\t\tdeferredTools: config.deferredTools === true ? true : undefined,\n\t\t\t...(hasCommand\n\t\t\t\t? { command: config.command as string }\n\t\t\t\t: {\n\t\t\t\t\t\turl: config.url as string,\n\t\t\t\t\t\t// Kept verbatim (no case normalization): managed remote MCP\n\t\t\t\t\t\t// endpoints compare header names and values exactly.\n\t\t\t\t\t\t...(config.headers === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { headers: config.headers as Readonly<Record<string, string>> }),\n\t\t\t\t\t}),\n\t\t});\n\t}\n\treturn { servers, diagnostics };\n}\n\n/**\n * Generated stdio bridge shared by every injected server: JSON-RPC 2.0 over a\n * spawned child process (argv, never a shell — except on win32, where a\n * resolved `.cmd`/`.bat` shim is launched through `cmd.exe /d /s /c`, so its\n * arguments cross cmd's command-line interpreter exactly as with\n * `shell: true`), MCP initialize/tools/list\n * handshake, and one registerTool per remote tool through the public\n * capability API. Tool call policy stays host-owned; the bridge only forwards\n * requests and maps results. On win32 the transport additionally resolves\n * `.cmd`/`.bat` shims (bare names via PATH, explicit suffixes verbatim) and\n * launches them through `cmd.exe /d /s /c` with MSVCRT argv quoting, because\n * Node >= 18.20 refuses to spawn extension shims directly (EINVAL) and\n * extension-less shim names ENOENT.\n */\nconst MCP_POOL_BRIDGE_SOURCE = `// Generated by the suite MCP registration pool (agent-session-services). Do not edit.\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst REQUEST_TIMEOUT_MS = 30000;\n\n// Windows .cmd/.bat shims cannot be spawned directly: Node >= 18.20 raises\n// EINVAL for commands carrying a shim extension and ENOENT for bare names\n// (npx, pnpm, ...), so bare command names (no path separator) are probed\n// along PATH for a .cmd/.bat shim, and explicit .cmd/.bat commands pass\n// through for cmd.exe wrapping. Everything else - .exe/.com, path-bearing\n// executables, non-win32 platforms, and PATH misses - resolves to undefined\n// and keeps the direct spawn behavior (a miss keeps the original ENOENT).\nfunction resolveWin32ShimCommand(command) {\n\tif (process.platform !== 'win32') return undefined;\n\tconst lowered = command.toLowerCase();\n\tif (lowered.endsWith('.cmd') || lowered.endsWith('.bat')) return command;\n\tif (command.includes('/') || command.includes('\\\\\\\\')) return undefined;\n\tfor (const dir of (process.env.PATH || '').split(';')) {\n\t\tif (!dir) continue;\n\t\tconst cmdShim = join(dir, command + '.cmd');\n\t\tif (existsSync(cmdShim)) return cmdShim;\n\t\tconst batShim = join(dir, command + '.bat');\n\t\tif (existsSync(batShim)) return batShim;\n\t}\n\treturn undefined;\n}\n\n// MSVCRT argv quoting for the cmd.exe /c command string: an argument that is\n// empty or contains space/tab/quote is wrapped in double quotes, embedded\n// quotes are escaped as \\\\\", and backslashes directly before a quote (or a\n// quoted argument's trailing backslashes) double up (2n rule) so they cannot\n// escape the closing quote. Plain arguments pass through untouched.\nfunction quoteCommandString(parts) {\n\tconst quoted = [];\n\tfor (const part of parts) {\n\t\tif (part !== '' && !/[ \\\\t\"]/.test(part)) {\n\t\t\tquoted.push(part);\n\t\t\tcontinue;\n\t\t}\n\t\tlet inner = '';\n\t\tlet backslashes = 0;\n\t\tfor (const ch of part) {\n\t\t\tif (ch === '\\\\\\\\') {\n\t\t\t\tbackslashes += 1;\n\t\t\t} else if (ch === '\"') {\n\t\t\t\tinner += '\\\\\\\\'.repeat(backslashes * 2 + 1) + '\"';\n\t\t\t\tbackslashes = 0;\n\t\t\t} else {\n\t\t\t\tif (backslashes > 0) {\n\t\t\t\t\tinner += '\\\\\\\\'.repeat(backslashes);\n\t\t\t\t\tbackslashes = 0;\n\t\t\t\t}\n\t\t\t\tinner += ch;\n\t\t\t}\n\t\t}\n\t\tif (backslashes > 0) {\n\t\t\tinner += '\\\\\\\\'.repeat(backslashes * 2);\n\t\t}\n\t\tquoted.push('\"' + inner + '\"');\n\t}\n\treturn quoted.join(' ');\n}\n\nfunction startTransport(command, args) {\n\t// win32 only: wrap .cmd/.bat shims through cmd.exe (resolveWin32ShimCommand).\n\t// The MSVCRT-quoted command string gets ONE more plain outer pair of\n\t// quotes (cmd.exe dialect, not MSVCRT): /S strips that outer pair and\n\t// re-parses the inner string. windowsVerbatimArguments is required so the\n\t// pre-built string reaches cmd.exe untouched; Node's default quoting would\n\t// wrap it again and cmd.exe would see literal \\\\\" sequences instead.\n\tconst shim = resolveWin32ShimCommand(command);\n\tconst child =\n\t\tshim === undefined\n\t\t\t? spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'] })\n\t\t\t: spawn('cmd.exe', ['/d', '/s', '/c', '\"' + quoteCommandString([shim].concat(args)) + '\"'], {\n\t\t\t\t\twindowsVerbatimArguments: true,\n\t\t\t\t\tstdio: ['pipe', 'pipe', 'pipe'],\n\t\t\t\t});\n\tlet nextId = 1;\n\tlet closed = false;\n\tlet failure = null;\n\tlet buffered = '';\n\tconst pending = new Map();\n\tconst rejectAll = (error) => {\n\t\tif (failure) return;\n\t\tfailure = error;\n\t\tclosed = true;\n\t\tfor (const request of pending.values()) request.reject(error);\n\t\tpending.clear();\n\t};\n\tchild.stdout.setEncoding('utf8');\n\tchild.stdout.on('data', (chunk) => {\n\t\tbuffered += chunk;\n\t\tconst lines = buffered.split(/\\\\r?\\\\n/);\n\t\tbuffered = lines.pop() || '';\n\t\tfor (const line of lines) {\n\t\t\tif (!line.trim()) continue;\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = JSON.parse(line);\n\t\t\t} catch {\n\t\t\t\trejectAll(new Error('MCP server produced a malformed JSON-RPC response'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.id === undefined || response.id === null) continue;\n\t\t\tconst request = pending.get(response.id);\n\t\t\tif (!request) continue;\n\t\t\tpending.delete(response.id);\n\t\t\tif (response.error) {\n\t\t\t\trequest.reject(new Error('MCP request failed: ' + String(response.error.message || 'unknown error')));\n\t\t\t} else {\n\t\t\t\trequest.resolve(response.result);\n\t\t\t}\n\t\t}\n\t});\n\tchild.stderr.setEncoding('utf8');\n\tchild.stderr.on('data', () => undefined);\n\tchild.once('error', (error) => rejectAll(new Error('Failed to spawn MCP server: ' + error.message)));\n\tchild.once('close', (exitCode) => rejectAll(new Error('MCP server exited with code ' + String(exitCode))));\n\tconst send = (message) => {\n\t\tchild.stdin.write(JSON.stringify(message) + '\\\\n');\n\t};\n\tconst request = (method, params, signal) => {\n\t\tif (failure || closed) return Promise.reject(failure || new Error('MCP transport is closed'));\n\t\tif (signal && signal.aborted) return Promise.reject(new Error('MCP request aborted'));\n\t\tconst id = nextId++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tpending.delete(id);\n\t\t\t\treject(new Error('MCP request timed out: ' + method));\n\t\t\t}, REQUEST_TIMEOUT_MS);\n\t\t\tpending.set(id, {\n\t\t\t\tresolve: (result) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(result);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (signal) {\n\t\t\t\tsignal.addEventListener(\n\t\t\t\t\t'abort',\n\t\t\t\t\t() => {\n\t\t\t\t\t\tif (pending.delete(id)) reject(new Error('MCP request aborted'));\n\t\t\t\t\t},\n\t\t\t\t\t{ once: true },\n\t\t\t\t);\n\t\t\t}\n\t\t\tsend(Object.assign({ jsonrpc: '2.0', id, method }, params === undefined ? {} : { params }));\n\t\t});\n\t};\n\treturn {\n\t\trequest,\n\t\tnotify(method, params) {\n\t\t\tif (closed) return;\n\t\t\tsend(Object.assign({ jsonrpc: '2.0', method }, params === undefined ? {} : { params }));\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tchild.stdin.end();\n\t\t\tif (!child.killed) child.kill();\n\t\t},\n\t};\n}\n\nfunction normalizeToolResult(result) {\n\tif (result && typeof result === 'object' && Array.isArray(result.content)) {\n\t\treturn { content: result.content, details: result.details };\n\t}\n\tif (result === undefined) return { content: [{ type: 'text', text: '' }], details: undefined };\n\treturn { content: [{ type: 'text', text: JSON.stringify(result) }], details: undefined };\n}\n\nexport default function createMcpStdioServerPlugin(config) {\n\treturn async (api) => {\n\t\tconst transport = startTransport(config.command, config.args || []);\n\t\ttry {\n\t\t\tawait transport.request('initialize', {\n\t\t\t\tprotocolVersion: '2024-11-05',\n\t\t\t\tcapabilities: {},\n\t\t\t\tclientInfo: { name: 'agent-forge-mcp-pool', version: '0.1.0' },\n\t\t\t});\n\t\t\ttransport.notify('notifications/initialized');\n\t\t\tconst listing = await transport.request('tools/list');\n\t\t\tif (!listing || !Array.isArray(listing.tools)) {\n\t\t\t\tthrow new Error('MCP tools/list result must contain tools[]');\n\t\t\t}\n\t\t\tfor (const tool of listing.tools) {\n\t\t\t\tif (!tool || typeof tool.name !== 'string' || !tool.name) {\n\t\t\t\t\tthrow new Error('MCP tool requires a non-empty name');\n\t\t\t\t}\n\t\t\t\tapi.registerTool({\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\tlabel: tool.name,\n\t\t\t\t\tdescription: typeof tool.description === 'string' ? tool.description : 'MCP tool: ' + tool.name,\n\t\t\t\t\tparameters:\n\t\t\t\t\t\ttool.inputSchema && typeof tool.inputSchema === 'object'\n\t\t\t\t\t\t\t? tool.inputSchema\n\t\t\t\t\t\t\t: { type: 'object', properties: {} },\n\t\t\t\t\texecute: async (toolCallId, params, signal) => {\n\t\t\t\t\t\t// Dual call convention: the session passes (toolCallId, params,\n\t\t\t\t\t\t// signal); the runtime's invokeTool passes the input as the\n\t\t\t\t\t\t// single first argument.\n\t\t\t\t\t\tconst singleArgCall = params === undefined && typeof toolCallId !== 'string';\n\t\t\t\t\t\tconst input = singleArgCall ? toolCallId : params;\n\t\t\t\t\t\tconst result = await transport.request(\n\t\t\t\t\t\t\t'tools/call',\n\t\t\t\t\t\t\t{ name: tool.name, arguments: input || {} },\n\t\t\t\t\t\t\tsingleArgCall ? undefined : signal,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn normalizeToolResult(result);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tdispose() {\n\t\t\t\t\ttransport.close();\n\t\t\t\t},\n\t\t\t};\n\t\t} catch (error) {\n\t\t\ttransport.close();\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n`;\n\nfunction writeMcpPoolBridge(poolDir: string): void {\n\tconst bridgeDir = join(poolDir, MCP_POOL_BRIDGE_DIR);\n\tmkdirSync(bridgeDir, { recursive: true });\n\twriteFileSync(join(bridgeDir, \"index.mjs\"), MCP_POOL_BRIDGE_SOURCE, \"utf8\");\n}\n\n/**\n * Import specifier for the HTTP server plugin implementation, as written into\n * a generated pool entry below `fromDir`. Relative same-drive form matches the\n * stdio entry's style; a cross-drive relative() result stays an absolute POSIX\n * path, which the capability loader (jiti) resolves.\n */\nfunction mcpHttpPluginImportSpec(fromDir: string): string {\n\tconst implPath = existsSync(MCP_HTTP_PLUGIN_SOURCE_PATH) ? MCP_HTTP_PLUGIN_SOURCE_PATH : MCP_HTTP_PLUGIN_DIST_PATH;\n\tconst relNative = relative(fromDir, implPath);\n\tconst relPosix = relNative.split(sep).join(\"/\");\n\treturn isAbsolute(relNative) ? relPosix : `./${relPosix}`;\n}\n\n/** Materializes one server as a capability-plugin manifest; returns the manifest path. */\nfunction writeMcpPoolServer(poolDir: string, name: string, server: McpServerConfigV1): string {\n\tconst serverDir = join(poolDir, name);\n\tmkdirSync(serverDir, { recursive: true });\n\tconst manifest = {\n\t\tid: `agent-forge.mcp.${name}`,\n\t\tversion: \"0.1.0\",\n\t\t// The pool is re-materialized every session, so the declared range always\n\t\t// includes the running host (D-073): an upgraded host never rejects its\n\t\t// own generated pool manifests through the hostVersion gate.\n\t\thostVersion: `>=${VERSION}`,\n\t\tapiVersion: EXPERIMENTAL_PUBLIC_API_VERSION,\n\t\tentry: \"./index.mjs\",\n\t\trequiredCapabilities: [\"tools\"],\n\t};\n\twriteFileSync(join(serverDir, \"plugin.json\"), `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\n\tconst entry =\n\t\tserver.url === undefined\n\t\t\t? [\n\t\t\t\t\t\"// Generated by the suite MCP registration pool (agent-session-services). Do not edit.\",\n\t\t\t\t\t`import createMcpStdioServerPlugin from \"../${MCP_POOL_BRIDGE_DIR}/index.mjs\";`,\n\t\t\t\t\t`export default createMcpStdioServerPlugin(${JSON.stringify({ command: server.command, args: server.args })});`,\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\")\n\t\t\t: [\n\t\t\t\t\t\"// Generated by the suite MCP registration pool (agent-session-services). Do not edit.\",\n\t\t\t\t\t`import { createMcpHttpServerPlugin } from \"${mcpHttpPluginImportSpec(serverDir)}\";`,\n\t\t\t\t\t`export default createMcpHttpServerPlugin(${JSON.stringify({\n\t\t\t\t\t\turl: server.url,\n\t\t\t\t\t\t...(server.headers === undefined ? {} : { headers: server.headers }),\n\t\t\t\t\t})});`,\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\");\n\twriteFileSync(join(serverDir, \"index.mjs\"), entry, \"utf8\");\n\treturn join(serverDir, \"plugin.json\");\n}\n\n/**\n * Resolves the suite's MCP registration pool (方案系统 M4: MCP 配置面, 设计\n * §4/§5) and materializes each injected server as a capability-plugin\n * manifest below `<agentDir>/mcp/pool/`, ready for the session's\n * `capabilityPluginPaths` channel — the same way plugins directory discovery\n * injects manifests. Filtering: the project level\n * (`<cwd>/.agent-forge/mcp.json`) is the third layer (设计 §4) and always\n * passes; the user level (`<agentDir>/mcp.json`) injects only servers named\n * in `suite.associations.mcp` — an empty association list means zero\n * user-level injection, the same semantics as skills/extensions.\n */\nexport function resolveSuiteMcpPool(options: {\n\tcwd: string;\n\tagentDir: string;\n\tsuite: SuiteDefinition;\n}): SuiteMcpPoolV1 {\n\tconst { cwd, agentDir, suite } = options;\n\tconst userConfigPath = join(agentDir, MCP_CONFIG_FILENAME);\n\tconst projectConfigPath = join(cwd, CONFIG_DIR_NAME, MCP_CONFIG_FILENAME);\n\tconst user = parseMcpConfig(userConfigPath);\n\tconst project = parseMcpConfig(projectConfigPath);\n\tconst diagnostics = [...project.diagnostics, ...user.diagnostics];\n\n\tconst selected = new Map<string, McpServerConfigV1 & { scope: \"user\" | \"project\" }>();\n\t// Third layer (设计 §4): project-level servers always pass; they win name\n\t// collisions over user definitions.\n\tfor (const [name, server] of project.servers) selected.set(name, { ...server, scope: \"project\" });\n\tfor (const [name, server] of user.servers) {\n\t\tif (selected.has(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" from ${userConfigPath} is overridden by the project-level definition at ${projectConfigPath}; keeping the project one.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!suite.associations.mcp.includes(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`Suite \"${suite.id}\" MCP server \"${name}\" is not associated (associations.mcp); not injected.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tselected.set(name, { ...server, scope: \"user\" });\n\t}\n\tfor (const name of suite.associations.mcp) {\n\t\tif (!selected.has(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`Suite \"${suite.id}\" dangling association \"${name}\" (mcp): not found in the discovered registry; ignored.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst servers: SuiteMcpServerV1[] = [];\n\tconst manifestPaths: string[] = [];\n\tconst deferredPluginIds: string[] = [];\n\tif (selected.size > 0) {\n\t\tconst poolDir = join(agentDir, MCP_POOL_DIR);\n\t\twriteMcpPoolBridge(poolDir);\n\t\tfor (const [name, server] of selected) {\n\t\t\tconst manifestPath = writeMcpPoolServer(poolDir, name, server);\n\t\t\tmanifestPaths.push(manifestPath);\n\t\t\tservers.push({\n\t\t\t\tname,\n\t\t\t\targs: server.args,\n\t\t\t\tscope: server.scope,\n\t\t\t\tmanifestPath,\n\t\t\t\tdeferred: server.deferredTools === true,\n\t\t\t\t...(server.url === undefined\n\t\t\t\t\t? { command: server.command }\n\t\t\t\t\t: {\n\t\t\t\t\t\t\turl: server.url,\n\t\t\t\t\t\t\t...(server.headers === undefined ? {} : { headers: server.headers }),\n\t\t\t\t\t\t}),\n\t\t\t});\n\t\t\tif (server.deferredTools === true) {\n\t\t\t\tdeferredPluginIds.push(`agent-forge.mcp.${name}`);\n\t\t\t}\n\t\t}\n\t}\n\treturn { servers, manifestPaths, deferredPluginIds, diagnostics };\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tcredentials: options.credentials,\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t}));\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\t// Suite assembly (设计 §3/§4/§8, M2): resolve once and wire the shared\n\t// assembly into this loader. Off by default so evals/testkit services keep\n\t// their fixture resources unfiltered.\n\tlet suiteId: string | undefined;\n\tlet suiteLoaderOverrides:\n\t\t| Pick<\n\t\t\t\tDefaultResourceLoaderOptions,\n\t\t\t\t\"agentsFilesOverride\" | \"skillsOverride\" | \"systemPromptOverride\" | \"appendSystemPromptOverride\"\n\t\t >\n\t\t| undefined;\n\tlet suiteLocalSkillsDir: string | undefined;\n\tlet pluginProfile: BuiltinPluginProfileResolutionV1 | undefined;\n\t/** MCP registration pool for the assembled suite (M4); undefined when assembly is off. */\n\tlet mcpPool: SuiteMcpPoolV1 | undefined;\n\tif (options.suiteAssembly) {\n\t\tsuiteId = resolveSuiteId({\n\t\t\texplicit: options.suite,\n\t\t\tenvSuite: process.env[SUITE_ENV_VAR],\n\t\t\tsettings: settingsManager,\n\t\t\tagentDir,\n\t\t});\n\t\tconst suiteAssembly = createSuiteAssembly({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tsuiteId,\n\t\t\tpluginProfileId: options.pluginProfileId,\n\t\t\tselectedPluginIds: options.selectedPluginIds,\n\t\t\tdisabledPluginIds: options.disabledPluginIds,\n\t\t\tpluginHost: options.pluginHost,\n\t\t\tverifiedPlugins: options.verifiedPlugins,\n\t\t\tmanifestOverrides: options.manifestOverrides,\n\t\t});\n\t\tpluginProfile = suiteAssembly.pluginProfile;\n\t\tsuiteLoaderOverrides = suiteAssembly.loaderOverrides;\n\t\t// Suite-local skill layer (统一修复轮 B): <suiteDir>/skills rides this\n\t\t// loader's skill paths when the suite is active, mirroring the sdk's\n\t\t// self-built loader path so the two first-party entries cannot drift.\n\t\tsuiteLocalSkillsDir = suiteAssembly.localSkillsDir;\n\t\t// MCP registration pool (M4): read the mcp.json config surface, filter\n\t\t// by associations.mcp, and materialize the injected servers as\n\t\t// capability-plugin manifests for the session's explicit paths channel.\n\t\tmcpPool = resolveSuiteMcpPool({ cwd, agentDir, suite: suiteAssembly.workspace.suite });\n\t}\n\tconst additionalSkillPaths = [\n\t\t...(options.resourceLoaderOptions?.additionalSkillPaths ?? []),\n\t\t...(suiteLocalSkillsDir === undefined ? [] : [suiteLocalSkillsDir]),\n\t];\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\t...suiteLoaderOverrides,\n\t\t...(additionalSkillPaths.length > 0 ? { additionalSkillPaths } : {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tfor (const message of mcpPool?.diagnostics ?? []) {\n\t\tdiagnostics.push({ type: \"info\", message });\n\t}\n\tdiagnostics.push(...(options.pluginBindingDiagnostics ?? []));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t\t...(suiteId === undefined ? {} : { suiteId }),\n\t\t...(pluginProfile === undefined ? {} : { pluginProfile }),\n\t\t...(options.pluginProfileId === undefined ? {} : { pluginProfileId: options.pluginProfileId }),\n\t\t...(options.installedCapabilityPlugins === undefined\n\t\t\t? {}\n\t\t\t: { installedCapabilityPlugins: Object.freeze([...options.installedCapabilityPlugins]) }),\n\t\t...(mcpPool !== undefined && mcpPool.manifestPaths.length > 0\n\t\t\t? { mcpCapabilityPluginPaths: mcpPool.manifestPaths }\n\t\t\t: {}),\n\t\t...(mcpPool !== undefined && mcpPool.deferredPluginIds.length > 0\n\t\t\t? { mcpDeferredToolPluginIds: mcpPool.deferredPluginIds }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.resourceLoader ?? options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tstreamFn: options.streamFn,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\t// Suite binding: an explicit option wins; otherwise the services' single\n\t\t// resolution result is forwarded so the sdk does not resolve again and\n\t\t// the two sides cannot drift (设计 §9).\n\t\t...(options.suite !== undefined || options.services.suiteId !== undefined\n\t\t\t? { suite: options.suite ?? options.services.suiteId }\n\t\t\t: {}),\n\t\t// Capability wiring (方案系统 M3): the sdk's caller-supplied-loader\n\t\t// boundary would leave it off for the services' own loader, so first-party\n\t\t// assembly turns it on here; an explicit option wins.\n\t\t...((options.suiteCapabilityWiring ?? options.services.suiteId !== undefined)\n\t\t\t? { suiteCapabilityWiring: true as const }\n\t\t\t: {}),\n\t\t...(options.services.pluginProfile === undefined ? {} : { pluginProfile: options.services.pluginProfile }),\n\t\t...(options.services.installedCapabilityPlugins === undefined\n\t\t\t? {}\n\t\t\t: { installedCapabilityPlugins: options.services.installedCapabilityPlugins }),\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tcapabilityMode: options.capabilityMode,\n\t\tdiscoverCapabilityPlugins: options.discoverCapabilityPlugins,\n\t\t// Trace/log control face (设计 §4.4/§5/§6): undefined passes through, so\n\t\t// the sdk defaults (trace on, no host logging) stay in effect.\n\t\ttraceEnabled: options.traceEnabled,\n\t\thostLogger: options.hostLogger,\n\t\t// MCP registration pool (M4): the services' generated manifest paths ride\n\t\t// the explicit caller-intent channel, so they bypass associations.plugins\n\t\t// filtering (they are governed by associations.mcp, not associations.plugins);\n\t\t// caller-provided paths keep discovery-order precedence on id conflicts.\n\t\t...(options.services.mcpCapabilityPluginPaths === undefined\n\t\t\t? { capabilityPluginPaths: options.capabilityPluginPaths }\n\t\t\t: {\n\t\t\t\t\tcapabilityPluginPaths: [\n\t\t\t\t\t\t...(options.capabilityPluginPaths ?? []),\n\t\t\t\t\t\t...options.services.mcpCapabilityPluginPaths,\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t...(options.services.mcpDeferredToolPluginIds === undefined\n\t\t\t? {}\n\t\t\t: { deferredToolPluginIds: options.services.mcpDeferredToolPluginIds }),\n\t\tcontextStrategyName: options.contextStrategyName,\n\t\tretryPolicyName: options.retryPolicyName,\n\t\tcompactionPolicyName: options.compactionPolicyName,\n\t\toverflowPolicyName: options.overflowPolicyName,\n\t\tbranchSummaryPolicyName: options.branchSummaryPolicyName,\n\t\t...(options.interactionHost === undefined ? {} : { interactionHost: options.interactionHost }),\n\t\t...(options.enableAgentTasks === undefined ? {} : { enableAgentTasks: options.enableAgentTasks }),\n\t\t...(options.subagentCommunicationWiring === undefined\n\t\t\t? {}\n\t\t\t: { subagentCommunicationWiring: options.subagentCommunicationWiring }),\n\t\t...(options.subagentPoolFromSelfInvocation === undefined\n\t\t\t? {}\n\t\t\t: { subagentPoolFromSelfInvocation: options.subagentPoolFromSelfInvocation }),\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-services.js","sourceRoot":"","sources":["../../src/core/agent-session-services.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGzC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAUrE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjG,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,+BAA+B,EAAE,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irSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ThinkingLevel } from \"@agent-forge/agent-core\";\nimport type { Api, CredentialStore, Model } from \"@agent-forge/ai\";\nimport { CONFIG_DIR_NAME, getAgentDir, VERSION } from \"../config.ts\";\nimport type { HostFactsV1 } from \"../plugins/ecosystem/types.ts\";\nimport type { ObservabilityPlugin } from \"../plugins/observability-types.ts\";\nimport type {\n\tBuiltinPluginManifestOverridesV1,\n\tBuiltinPluginProfileIdV1,\n\tBuiltinPluginProfileResolutionV1,\n} from \"../profile/plugin-profiles.ts\";\nimport type { VerifiedToolPluginV1 } from \"../profile/profile-assembly.ts\";\nimport type { SuiteDefinition } from \"../profiles/builtin-suites.ts\";\nimport { createSuiteAssembly, resolveSuiteId, SUITE_ENV_VAR } from \"../profiles/suite-loader.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { EXPERIMENTAL_PUBLIC_API_VERSION } from \"./extensions/index.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport {\n\tDefaultResourceLoader,\n\ttype DefaultResourceLoaderOptions,\n\ttype ResourceLoader,\n\ttype ResourceLoaderReloadOptions,\n} from \"./resource-loader.ts\";\nimport {\n\ttype CreateAgentSessionOptions,\n\ttype CreateAgentSessionResult,\n\tcreateAgentSession,\n\ttype InstalledCapabilityPluginV1,\n} from \"./sdk.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SessionStartMetadata } from \"./session-start.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { ToolDefinition } from \"./tools/tool-definition.ts\";\n\n/**\n * Non-fatal issues collected while creating services or sessions.\n *\n * Runtime creation returns diagnostics to the caller instead of printing or\n * exiting. The app layer decides whether warnings should be shown and whether\n * errors should abort startup.\n */\nexport interface AgentSessionRuntimeDiagnostic {\n\ttype: \"info\" | \"warning\" | \"error\";\n\tmessage: string;\n}\n\n/**\n * Inputs for creating cwd-bound runtime services.\n *\n * These services are recreated whenever the effective session cwd changes.\n * CLI-provided resource paths should be resolved to absolute paths before they\n * reach this function, so later cwd switches do not reinterpret them.\n */\nexport interface CreateAgentSessionServicesOptions {\n\tcwd: string;\n\tagentDir?: string;\n\tsettingsManager?: SettingsManager;\n\tmodelRuntime?: ModelRuntime;\n\t/**\n\t * Credential storage used by the default model runtime (D-067 phase 1):\n\t * forwarded to `ModelRuntime.create` when `modelRuntime` is omitted.\n\t * Ignored when an explicit `modelRuntime` is supplied. Defaults to the\n\t * file at `<agentDir>/auth.json`.\n\t */\n\tcredentials?: CredentialStore;\n\tmodelRuntimeSignal?: AbortSignal;\n\tresourceLoaderOptions?: Omit<DefaultResourceLoaderOptions, \"cwd\" | \"agentDir\" | \"settingsManager\">;\n\tresourceLoaderReloadOptions?: ResourceLoaderReloadOptions;\n\t/**\n\t * Explicit suite id (highest resolution priority, 设计 §9). Without it the\n\t * suite resolves via AGENT_FORGE_SUITE, then settings, then \"coding\".\n\t */\n\tsuite?: string;\n\t/**\n\t * Wire the full suite assembly (agents.md three-level chain, system prompt\n\t * gate, skill/extension association filters, MCP registration pool) into\n\t * these services' DefaultResourceLoader. Default false: services built\n\t * without it keep the plain loader behavior (evals and testkit\n\t * determinism). When true, the suite id is resolved exactly once here and\n\t * exposed as AgentSessionServices.suiteId so session creation reuses it\n\t * instead of resolving again. The MCP pool (设计 §4/§5) additionally reads\n\t * the mcp.json config surface, filters it by associations.mcp, and\n\t * materializes the injected servers as capability-plugin manifests\n\t * (AgentSessionServices.mcpCapabilityPluginPaths).\n\t */\n\tsuiteAssembly?: boolean;\n\t/** Optional domain plugin profile selected for this suite. */\n\tpluginProfileId?: BuiltinPluginProfileIdV1;\n\t/** Optional subset of plugins from the selected builtin Profile. */\n\tselectedPluginIds?: readonly string[];\n\t/** Optional plugin IDs disabled within the selected builtin Profile. */\n\tdisabledPluginIds?: readonly string[];\n\tpluginHost?: HostFactsV1;\n\tverifiedPlugins?: readonly VerifiedToolPluginV1[];\n\t/** Explicit host-owned active installed manifests; never discovered implicitly. */\n\tmanifestOverrides?: BuiltinPluginManifestOverridesV1;\n\t/**\n\t * Verified active installations (D-075 S2 installed-code-loading) from the\n\t * host's active-binding resolution; forwarded to session creation so their\n\t * plugin.json paths enter the sdk's candidate pool for profile members.\n\t */\n\tinstalledCapabilityPlugins?: readonly InstalledCapabilityPluginV1[];\n\t/** Host diagnostics from active-install resolution; no package data is retained. */\n\tpluginBindingDiagnostics?: readonly AgentSessionRuntimeDiagnostic[];\n}\n\n/**\n * Inputs for creating an AgentSession from already-created services.\n *\n * Use this after services exist and any cwd-bound model/tool/session options\n * have been resolved against those services.\n */\nexport interface CreateAgentSessionFromServicesOptions {\n\tservices: AgentSessionServices;\n\tsessionManager: SessionManager;\n\tsessionStartEvent?: SessionStartMetadata;\n\tmodel?: Model<Api>;\n\tstreamFn?: CreateAgentSessionOptions[\"streamFn\"];\n\tthinkingLevel?: ThinkingLevel;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\ttools?: string[];\n\texcludeTools?: CreateAgentSessionOptions[\"excludeTools\"];\n\tnoTools?: CreateAgentSessionOptions[\"noTools\"];\n\tcapabilityMode?: CreateAgentSessionOptions[\"capabilityMode\"];\n\tdiscoverCapabilityPlugins?: CreateAgentSessionOptions[\"discoverCapabilityPlugins\"];\n\t/**\n\t * Session trace collection (设计 §4.4/§6), forwarded to createAgentSession.\n\t * Omitted keeps the sdk default (tracing on); hosts pass `false` for\n\t * `--no-trace`.\n\t */\n\ttraceEnabled?: CreateAgentSessionOptions[\"traceEnabled\"];\n\t/**\n\t * Host-process logger forwarded to createAgentSession (设计 §5). Omitted\n\t * keeps the sdk's explicit no-logging contract (instrumentation no-ops).\n\t */\n\thostLogger?: CreateAgentSessionOptions[\"hostLogger\"];\n\tcapabilityPluginPaths?: CreateAgentSessionOptions[\"capabilityPluginPaths\"];\n\tcontextStrategyName?: CreateAgentSessionOptions[\"contextStrategyName\"];\n\tretryPolicyName?: CreateAgentSessionOptions[\"retryPolicyName\"];\n\tcompactionPolicyName?: CreateAgentSessionOptions[\"compactionPolicyName\"];\n\toverflowPolicyName?: CreateAgentSessionOptions[\"overflowPolicyName\"];\n\tbranchSummaryPolicyName?: CreateAgentSessionOptions[\"branchSummaryPolicyName\"];\n\t/** Host adapter for cancellable interaction tasks, forwarded to createAgentSession. */\n\tinteractionHost?: CreateAgentSessionOptions[\"interactionHost\"];\n\t/**\n\t * 覆盖 services 自带 loader。pooled runner 的叶子会话用它注入子任务档案的\n\t * `systemPromptAppend`(追加语义,不替换继承内容);缺省沿用 services 的 loader。\n\t */\n\tresourceLoader?: CreateAgentSessionOptions[\"resourceLoader\"];\n\t/**\n\t * Forwarded to createAgentSession. Headless subagent runners pass `false` so a\n\t * runner task session stays a leaf (no nested agent tasks; D-045 increment 2b).\n\t */\n\tenableAgentTasks?: CreateAgentSessionOptions[\"enableAgentTasks\"];\n\tcustomTools?: ToolDefinition[];\n\t/**\n\t * Explicit suite id forwarded to createAgentSession. When omitted, the\n\t * services' resolved suiteId (suiteAssembly: true) is used; without either,\n\t * createAgentSession resolves the suite itself.\n\t */\n\tsuite?: string;\n\t/**\n\t * Wire the suite's capability surface (方案系统 M3) onto the created\n\t * sessions. Default: on when the services ran the suite assembly\n\t * (suiteAssembly: true, so first-party entries get the builtin capability\n\t * whitelist and plugin-pool filtering); otherwise off, matching the sdk's\n\t * caller-supplied-loader assembly boundary.\n\t */\n\tsuiteCapabilityWiring?: boolean;\n\t/**\n\t * 子代理通信面的宿主接线(D-060 S5 pooled parity):pooled runner 的叶子会话\n\t * 用它注入 post/drainInbox 闭包(身份绑定到叶子会话,信箱为文件承载、跨进程)。\n\t */\n\tsubagentCommunicationWiring?: CreateAgentSessionOptions[\"subagentCommunicationWiring\"];\n\t/**\n\t * 承载退役切片 1(生产 CLI 默认 pooled):转发 createAgentSession 的\n\t * self-invocation 自动池化声明。仅真实 CLI 装配传 true。\n\t */\n\tsubagentPoolFromSelfInvocation?: CreateAgentSessionOptions[\"subagentPoolFromSelfInvocation\"];\n}\n\n/**\n * Coherent cwd-bound runtime services for one effective session cwd.\n *\n * This is infrastructure only. The AgentSession itself is created separately so\n * session options can be resolved against these services first.\n */\nexport interface AgentSessionServices {\n\tcwd: string;\n\t/**\n\t * /metrics 命令的数据源共享 ref(observability 插件工厂创建时写入\n\t * plugin.getMetrics、dispose 时置空;宿主装配完成后读取接进命令 options)。\n\t * 空 = 插件未挂载(/metrics 显示未装配警告)。\n\t */\n\tobservabilityGetMetricsRef?: { current?: ObservabilityPlugin[\"getMetrics\"] };\n\tagentDir: string;\n\tmodelRuntime: ModelRuntime;\n\tsettingsManager: SettingsManager;\n\tresourceLoader: ResourceLoader;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n\t/**\n\t * Suite id resolved for these services when `suiteAssembly` was requested;\n\t * undefined when assembly was off (no suite filtering was applied here).\n\t */\n\tsuiteId?: string;\n\tpluginProfile?: BuiltinPluginProfileResolutionV1;\n\tpluginProfileId?: BuiltinPluginProfileIdV1;\n\t/**\n\t * Verified active installations (D-075 S2) forwarded from the services\n\t * options; createAgentSessionFromServices passes them to the sdk's\n\t * installed-code-loading candidate pool.\n\t */\n\tinstalledCapabilityPlugins?: readonly InstalledCapabilityPluginV1[];\n\t/**\n\t * Capability-plugin manifest paths materialized for the suite's MCP\n\t * registration pool (M4, 设计 §4/§5). Defined only when `suiteAssembly`\n\t * injected at least one associated mcp.json server;\n\t * createAgentSessionFromServices appends them to the created session's\n\t * capabilityPluginPaths.\n\t */\n\tmcpCapabilityPluginPaths?: readonly string[];\n\t/**\n\t * Plugin ids of the MCP pool servers configured with `deferredTools: true`.\n\t * Their tools register normally but stay out of the default active set; the\n\t * session's tool_search tool discovers and activates them on demand.\n\t */\n\tmcpDeferredToolPluginIds?: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// Suite MCP registration pool (方案系统 M4: MCP 配置面, 设计 §4/§5)\n// ---------------------------------------------------------------------------\n\n/** User-level MCP config file directly inside the agent dir. */\nconst MCP_CONFIG_FILENAME = \"mcp.json\";\n/** Generated per-server capability-plugin manifests live below this agentDir dir. */\nconst MCP_POOL_DIR = \"mcp/pool\";\n/** Shared stdio bridge module inside the pool dir (leading \"_\" keeps server names distinct). */\nconst MCP_POOL_BRIDGE_DIR = \"_bridge\";\n/** Server names are associations keys and pool directory names; \"_\" is reserved for the bridge. */\nconst MCP_SERVER_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/** One MCP server resolved from an mcp.json configuration file. */\nexport interface SuiteMcpServerV1 {\n\t/** Server name: the associations.mcp match key and the pool directory name. */\n\treadonly name: string;\n\t/** stdio launch command; undefined for remote HTTP servers (`url` set). */\n\treadonly command?: string;\n\treadonly args: readonly string[];\n\t/** Remote HTTP endpoint; undefined for stdio servers (`command` set). */\n\treadonly url?: string;\n\t/**\n\t * Custom request headers sent with every request to a remote HTTP server;\n\t * undefined for stdio servers (`headers` there only contributes a\n\t * diagnostic and is never forwarded).\n\t */\n\treadonly headers?: Readonly<Record<string, string>>;\n\t/**\n\t * Config layer the server came from. \"project\" (`<cwd>/.agent-forge/mcp.json`)\n\t * is the third layer (设计 §4) and always passes; \"user\"\n\t * (`<agentDir>/mcp.json`) injects only when associated.\n\t */\n\treadonly scope: \"user\" | \"project\";\n\t/** Generated capability-plugin manifest path for this server. */\n\treadonly manifestPath: string;\n\t/** Whether the server's tools stay out of the default active set until tool_search activates them. */\n\treadonly deferred: boolean;\n}\n\nexport interface SuiteMcpPoolV1 {\n\t/** Injected servers in deterministic order (project first, then user). */\n\treadonly servers: readonly SuiteMcpServerV1[];\n\t/** Manifest paths ready for the session's capabilityPluginPaths channel. */\n\treadonly manifestPaths: readonly string[];\n\t/** Plugin ids whose tools are registered but excluded from the default active set. */\n\treadonly deferredPluginIds: readonly string[];\n\t/**\n\t * Diagnostics: unreadable/invalid config files, filtered non-associated\n\t * servers, project-overridden duplicates, and dangling associations.\n\t * Reported, never thrown (设计 §11.3).\n\t */\n\treadonly diagnostics: readonly string[];\n}\n\ninterface McpServerConfigV1 {\n\treadonly command?: string;\n\treadonly args: readonly string[];\n\treadonly url?: string;\n\t/** Custom request headers for remote HTTP servers; ignored (with a diagnostic) on stdio entries. */\n\treadonly headers?: Readonly<Record<string, string>>;\n\treadonly deferredTools?: boolean;\n}\n\n/**\n * Remote MCP URLs accept only http/https; any other protocol or unparseable\n * value is a configuration error, not a fallback path.\n */\nfunction isHttpUrl(value: string): boolean {\n\ttry {\n\t\tconst protocol = new URL(value).protocol;\n\t\treturn protocol === \"http:\" || protocol === \"https:\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Reads one mcp.json (`{ \"mcpServers\": { \"<name>\": { \"command\", \"args\" } } }`\n * for stdio servers, or `{ \"url\" }` for remote HTTP servers). Each entry must\n * carry exactly one of \"command\" and \"url\". Corruption tolerance: a missing\n * file is an empty config; an unreadable or malformed file, and invalid\n * per-server entries, contribute a diagnostic and are skipped — never thrown.\n */\nfunction parseMcpConfig(path: string): {\n\tservers: Map<string, McpServerConfigV1>;\n\tdiagnostics: string[];\n} {\n\tconst servers = new Map<string, McpServerConfigV1>();\n\tconst diagnostics: string[] = [];\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(readFileSync(path, \"utf8\"));\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { servers, diagnostics };\n\t\tdiagnostics.push(\n\t\t\t`MCP config at ${path} is unreadable; ignoring it. Errors: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t\treturn { servers, diagnostics };\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tdiagnostics.push(`MCP config at ${path} must be an object with an \"mcpServers\" map; ignoring it.`);\n\t\treturn { servers, diagnostics };\n\t}\n\tconst mcpServers = (value as Record<string, unknown>).mcpServers;\n\tif (mcpServers === undefined) return { servers, diagnostics };\n\tif (typeof mcpServers !== \"object\" || mcpServers === null || Array.isArray(mcpServers)) {\n\t\tdiagnostics.push(`MCP config at ${path} must carry an \"mcpServers\" object; ignoring it.`);\n\t\treturn { servers, diagnostics };\n\t}\n\tfor (const [name, entry] of Object.entries(mcpServers as Record<string, unknown>)) {\n\t\tif (!MCP_SERVER_NAME_PATTERN.test(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server name \"${name}\" in ${path} is invalid (must match ${MCP_SERVER_NAME_PATTERN.source}); ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} must be an object with a \"command\" or \"url\"; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst config = entry as Record<string, unknown>;\n\t\tif (config.url !== undefined && (typeof config.url !== \"string\" || config.url.trim().length === 0)) {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} requires \"url\" to be a non-empty string; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst hasCommand = typeof config.command === \"string\" && config.command.trim().length > 0;\n\t\tconst hasUrl = typeof config.url === \"string\" && config.url.trim().length > 0;\n\t\tif (hasCommand && hasUrl) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" in ${path} accepts either \"command\" (stdio server) or \"url\" (remote HTTP server), not both; ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!hasCommand && !hasUrl) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" in ${path} requires a non-empty string \"command\" (stdio server) or \"url\" (remote HTTP server); ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (hasUrl && !isHttpUrl(config.url as string)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" in ${path} requires \"url\" to be a valid http:// or https:// URL; ignoring it.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (\n\t\t\tconfig.args !== undefined &&\n\t\t\t(!Array.isArray(config.args) || !config.args.every((arg) => typeof arg === \"string\"))\n\t\t) {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} requires \"args\" to be a string array; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (config.deferredTools !== undefined && typeof config.deferredTools !== \"boolean\") {\n\t\t\tdiagnostics.push(`MCP server \"${name}\" in ${path} requires \"deferredTools\" to be a boolean; ignoring it.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (config.headers !== undefined) {\n\t\t\tif (hasCommand) {\n\t\t\t\t// Same acceptance style as a url entry carrying args: the entry\n\t\t\t\t// loads, but the field belongs to the other transport shape.\n\t\t\t\tdiagnostics.push(\n\t\t\t\t\t`MCP server \"${name}\" in ${path} carries \"headers\" but headers only apply to remote \"url\" (HTTP) servers; ignoring them.`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst headersValid =\n\t\t\t\t\ttypeof config.headers === \"object\" &&\n\t\t\t\t\tconfig.headers !== null &&\n\t\t\t\t\t!Array.isArray(config.headers) &&\n\t\t\t\t\tObject.values(config.headers as Record<string, unknown>).every(\n\t\t\t\t\t\t(headerValue) => typeof headerValue === \"string\" && headerValue.length > 0,\n\t\t\t\t\t);\n\t\t\t\tif (!headersValid) {\n\t\t\t\t\tdiagnostics.push(\n\t\t\t\t\t\t`MCP server \"${name}\" in ${path} requires \"headers\" to be an object with non-empty string values; ignoring it.`,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tservers.set(name, {\n\t\t\targs: (config.args as readonly string[] | undefined) ?? [],\n\t\t\tdeferredTools: config.deferredTools === true ? true : undefined,\n\t\t\t...(hasCommand\n\t\t\t\t? { command: config.command as string }\n\t\t\t\t: {\n\t\t\t\t\t\turl: config.url as string,\n\t\t\t\t\t\t// Kept verbatim (no case normalization): managed remote MCP\n\t\t\t\t\t\t// endpoints compare header names and values exactly.\n\t\t\t\t\t\t...(config.headers === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { headers: config.headers as Readonly<Record<string, string>> }),\n\t\t\t\t\t}),\n\t\t});\n\t}\n\treturn { servers, diagnostics };\n}\n\n/**\n * Generated stdio bridge shared by every injected server: JSON-RPC 2.0 over a\n * spawned child process (argv, never a shell — except on win32, where a\n * resolved `.cmd`/`.bat` shim is launched through `cmd.exe /d /s /c`, so its\n * arguments cross cmd's command-line interpreter exactly as with\n * `shell: true`), MCP initialize/tools/list\n * handshake, and one registerTool per remote tool through the public\n * capability API. Tool call policy stays host-owned; the bridge only forwards\n * requests and maps results. On win32 the transport additionally resolves\n * `.cmd`/`.bat` shims (bare names via PATH, explicit suffixes verbatim) and\n * launches them through `cmd.exe /d /s /c` with MSVCRT argv quoting, because\n * Node >= 18.20 refuses to spawn extension shims directly (EINVAL) and\n * extension-less shim names ENOENT.\n */\nconst MCP_POOL_BRIDGE_SOURCE = `// Generated by the suite MCP registration pool (agent-session-services). Do not edit.\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nconst REQUEST_TIMEOUT_MS = 30000;\n\n// Windows .cmd/.bat shims cannot be spawned directly: Node >= 18.20 raises\n// EINVAL for commands carrying a shim extension and ENOENT for bare names\n// (npx, pnpm, ...), so bare command names (no path separator) are probed\n// along PATH for a .cmd/.bat shim, and explicit .cmd/.bat commands pass\n// through for cmd.exe wrapping. Everything else - .exe/.com, path-bearing\n// executables, non-win32 platforms, and PATH misses - resolves to undefined\n// and keeps the direct spawn behavior (a miss keeps the original ENOENT).\nfunction resolveWin32ShimCommand(command) {\n\tif (process.platform !== 'win32') return undefined;\n\tconst lowered = command.toLowerCase();\n\tif (lowered.endsWith('.cmd') || lowered.endsWith('.bat')) return command;\n\tif (command.includes('/') || command.includes('\\\\\\\\')) return undefined;\n\tfor (const dir of (process.env.PATH || '').split(';')) {\n\t\tif (!dir) continue;\n\t\tconst cmdShim = join(dir, command + '.cmd');\n\t\tif (existsSync(cmdShim)) return cmdShim;\n\t\tconst batShim = join(dir, command + '.bat');\n\t\tif (existsSync(batShim)) return batShim;\n\t}\n\treturn undefined;\n}\n\n// MSVCRT argv quoting for the cmd.exe /c command string: an argument that is\n// empty or contains space/tab/quote is wrapped in double quotes, embedded\n// quotes are escaped as \\\\\", and backslashes directly before a quote (or a\n// quoted argument's trailing backslashes) double up (2n rule) so they cannot\n// escape the closing quote. Plain arguments pass through untouched.\nfunction quoteCommandString(parts) {\n\tconst quoted = [];\n\tfor (const part of parts) {\n\t\tif (part !== '' && !/[ \\\\t\"]/.test(part)) {\n\t\t\tquoted.push(part);\n\t\t\tcontinue;\n\t\t}\n\t\tlet inner = '';\n\t\tlet backslashes = 0;\n\t\tfor (const ch of part) {\n\t\t\tif (ch === '\\\\\\\\') {\n\t\t\t\tbackslashes += 1;\n\t\t\t} else if (ch === '\"') {\n\t\t\t\tinner += '\\\\\\\\'.repeat(backslashes * 2 + 1) + '\"';\n\t\t\t\tbackslashes = 0;\n\t\t\t} else {\n\t\t\t\tif (backslashes > 0) {\n\t\t\t\t\tinner += '\\\\\\\\'.repeat(backslashes);\n\t\t\t\t\tbackslashes = 0;\n\t\t\t\t}\n\t\t\t\tinner += ch;\n\t\t\t}\n\t\t}\n\t\tif (backslashes > 0) {\n\t\t\tinner += '\\\\\\\\'.repeat(backslashes * 2);\n\t\t}\n\t\tquoted.push('\"' + inner + '\"');\n\t}\n\treturn quoted.join(' ');\n}\n\nfunction startTransport(command, args) {\n\t// win32 only: wrap .cmd/.bat shims through cmd.exe (resolveWin32ShimCommand).\n\t// The MSVCRT-quoted command string gets ONE more plain outer pair of\n\t// quotes (cmd.exe dialect, not MSVCRT): /S strips that outer pair and\n\t// re-parses the inner string. windowsVerbatimArguments is required so the\n\t// pre-built string reaches cmd.exe untouched; Node's default quoting would\n\t// wrap it again and cmd.exe would see literal \\\\\" sequences instead.\n\tconst shim = resolveWin32ShimCommand(command);\n\tconst child =\n\t\tshim === undefined\n\t\t\t? spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'] })\n\t\t\t: spawn('cmd.exe', ['/d', '/s', '/c', '\"' + quoteCommandString([shim].concat(args)) + '\"'], {\n\t\t\t\t\twindowsVerbatimArguments: true,\n\t\t\t\t\tstdio: ['pipe', 'pipe', 'pipe'],\n\t\t\t\t});\n\tlet nextId = 1;\n\tlet closed = false;\n\tlet failure = null;\n\tlet buffered = '';\n\tconst pending = new Map();\n\tconst rejectAll = (error) => {\n\t\tif (failure) return;\n\t\tfailure = error;\n\t\tclosed = true;\n\t\tfor (const request of pending.values()) request.reject(error);\n\t\tpending.clear();\n\t};\n\tchild.stdout.setEncoding('utf8');\n\tchild.stdout.on('data', (chunk) => {\n\t\tbuffered += chunk;\n\t\tconst lines = buffered.split(/\\\\r?\\\\n/);\n\t\tbuffered = lines.pop() || '';\n\t\tfor (const line of lines) {\n\t\t\tif (!line.trim()) continue;\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = JSON.parse(line);\n\t\t\t} catch {\n\t\t\t\trejectAll(new Error('MCP server produced a malformed JSON-RPC response'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (response.id === undefined || response.id === null) continue;\n\t\t\tconst request = pending.get(response.id);\n\t\t\tif (!request) continue;\n\t\t\tpending.delete(response.id);\n\t\t\tif (response.error) {\n\t\t\t\trequest.reject(new Error('MCP request failed: ' + String(response.error.message || 'unknown error')));\n\t\t\t} else {\n\t\t\t\trequest.resolve(response.result);\n\t\t\t}\n\t\t}\n\t});\n\tchild.stderr.setEncoding('utf8');\n\tchild.stderr.on('data', () => undefined);\n\tchild.once('error', (error) => rejectAll(new Error('Failed to spawn MCP server: ' + error.message)));\n\tchild.once('close', (exitCode) => rejectAll(new Error('MCP server exited with code ' + String(exitCode))));\n\tconst send = (message) => {\n\t\tchild.stdin.write(JSON.stringify(message) + '\\\\n');\n\t};\n\tconst request = (method, params, signal) => {\n\t\tif (failure || closed) return Promise.reject(failure || new Error('MCP transport is closed'));\n\t\tif (signal && signal.aborted) return Promise.reject(new Error('MCP request aborted'));\n\t\tconst id = nextId++;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tpending.delete(id);\n\t\t\t\treject(new Error('MCP request timed out: ' + method));\n\t\t\t}, REQUEST_TIMEOUT_MS);\n\t\t\tpending.set(id, {\n\t\t\t\tresolve: (result) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(result);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (signal) {\n\t\t\t\tsignal.addEventListener(\n\t\t\t\t\t'abort',\n\t\t\t\t\t() => {\n\t\t\t\t\t\tif (pending.delete(id)) reject(new Error('MCP request aborted'));\n\t\t\t\t\t},\n\t\t\t\t\t{ once: true },\n\t\t\t\t);\n\t\t\t}\n\t\t\tsend(Object.assign({ jsonrpc: '2.0', id, method }, params === undefined ? {} : { params }));\n\t\t});\n\t};\n\treturn {\n\t\trequest,\n\t\tnotify(method, params) {\n\t\t\tif (closed) return;\n\t\t\tsend(Object.assign({ jsonrpc: '2.0', method }, params === undefined ? {} : { params }));\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tchild.stdin.end();\n\t\t\tif (!child.killed) child.kill();\n\t\t},\n\t};\n}\n\nfunction normalizeToolResult(result) {\n\tif (result && typeof result === 'object' && Array.isArray(result.content)) {\n\t\treturn { content: result.content, details: result.details };\n\t}\n\tif (result === undefined) return { content: [{ type: 'text', text: '' }], details: undefined };\n\treturn { content: [{ type: 'text', text: JSON.stringify(result) }], details: undefined };\n}\n\nexport default function createMcpStdioServerPlugin(config) {\n\treturn async (api) => {\n\t\tconst transport = startTransport(config.command, config.args || []);\n\t\ttry {\n\t\t\tawait transport.request('initialize', {\n\t\t\t\tprotocolVersion: '2024-11-05',\n\t\t\t\tcapabilities: {},\n\t\t\t\tclientInfo: { name: 'agent-forge-mcp-pool', version: '0.1.0' },\n\t\t\t});\n\t\t\ttransport.notify('notifications/initialized');\n\t\t\tconst listing = await transport.request('tools/list');\n\t\t\tif (!listing || !Array.isArray(listing.tools)) {\n\t\t\t\tthrow new Error('MCP tools/list result must contain tools[]');\n\t\t\t}\n\t\t\tfor (const tool of listing.tools) {\n\t\t\t\tif (!tool || typeof tool.name !== 'string' || !tool.name) {\n\t\t\t\t\tthrow new Error('MCP tool requires a non-empty name');\n\t\t\t\t}\n\t\t\t\tapi.registerTool({\n\t\t\t\t\tname: tool.name,\n\t\t\t\t\tlabel: tool.name,\n\t\t\t\t\tdescription: typeof tool.description === 'string' ? tool.description : 'MCP tool: ' + tool.name,\n\t\t\t\t\tparameters:\n\t\t\t\t\t\ttool.inputSchema && typeof tool.inputSchema === 'object'\n\t\t\t\t\t\t\t? tool.inputSchema\n\t\t\t\t\t\t\t: { type: 'object', properties: {} },\n\t\t\t\t\texecute: async (toolCallId, params, signal) => {\n\t\t\t\t\t\t// Dual call convention: the session passes (toolCallId, params,\n\t\t\t\t\t\t// signal); the runtime's invokeTool passes the input as the\n\t\t\t\t\t\t// single first argument.\n\t\t\t\t\t\tconst singleArgCall = params === undefined && typeof toolCallId !== 'string';\n\t\t\t\t\t\tconst input = singleArgCall ? toolCallId : params;\n\t\t\t\t\t\tconst result = await transport.request(\n\t\t\t\t\t\t\t'tools/call',\n\t\t\t\t\t\t\t{ name: tool.name, arguments: input || {} },\n\t\t\t\t\t\t\tsingleArgCall ? undefined : signal,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn normalizeToolResult(result);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tdispose() {\n\t\t\t\t\ttransport.close();\n\t\t\t\t},\n\t\t\t};\n\t\t} catch (error) {\n\t\t\ttransport.close();\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n`;\n\nfunction writeMcpPoolBridge(poolDir: string): void {\n\tconst bridgeDir = join(poolDir, MCP_POOL_BRIDGE_DIR);\n\tmkdirSync(bridgeDir, { recursive: true });\n\twriteFileSync(join(bridgeDir, \"index.mjs\"), MCP_POOL_BRIDGE_SOURCE, \"utf8\");\n}\n\n/**\n * Implementation backing url-configured pool entries (createMcpHttpServerPlugin),\n * owned by the plugins/mcp-http package since D-082 批 2. Sources resolve first\n * so development always runs the current implementation; published installs\n * ship only dist, so the bundled snapshot is the fallback.\n */\nfunction mcpHttpPluginImplPath(): string {\n\t// Package-root probe, identical to bundledCapabilityPluginDirectories\n\t// (core/sdk.ts): src runs sit at src/core (two levels up), unbundled dist\n\t// runs at dist/core (two levels up), and the Node bundle at dist/bundle\n\t// (three levels up). The first ancestor carrying a package.json wins.\n\tconst moduleDir = fileURLToPath(new URL(\".\", import.meta.url));\n\tfor (const depth of [2, 3]) {\n\t\tlet candidate = moduleDir;\n\t\tfor (let index = 0; index < depth; index++) candidate = dirname(candidate);\n\t\tif (!existsSync(join(candidate, \"package.json\"))) continue;\n\t\tconst devSource = join(candidate, \"..\", \"..\", \"plugins\", \"mcp-http\", \"src\", \"mcp-http.ts\");\n\t\tif (existsSync(devSource)) return devSource;\n\t\treturn join(candidate, \"bundled-plugins\", \"mcp-http\", \"dist\", \"mcp-http.js\");\n\t}\n\t// Unreachable in every supported layout (the probe always finds the package\n\t// root within depth 3); fail loudly instead of materializing a pool entry\n\t// that imports a guessed path.\n\tthrow new Error(\"Unable to locate the agent-forge package root for the mcp-http plugin implementation\");\n}\n\n/**\n * Import specifier for the HTTP server plugin implementation, as written into\n * a generated pool entry below `fromDir`. Relative same-drive form matches the\n * stdio entry's style; a cross-drive relative() result stays an absolute POSIX\n * path, which the capability loader (jiti) resolves.\n */\nfunction mcpHttpPluginImportSpec(fromDir: string): string {\n\tconst implPath = mcpHttpPluginImplPath();\n\tconst relNative = relative(fromDir, implPath);\n\tconst relPosix = relNative.split(sep).join(\"/\");\n\treturn isAbsolute(relNative) ? relPosix : `./${relPosix}`;\n}\n\n/** Materializes one server as a capability-plugin manifest; returns the manifest path. */\nfunction writeMcpPoolServer(poolDir: string, name: string, server: McpServerConfigV1): string {\n\tconst serverDir = join(poolDir, name);\n\tmkdirSync(serverDir, { recursive: true });\n\tconst manifest = {\n\t\tid: `agent-forge.mcp.${name}`,\n\t\tversion: \"0.1.0\",\n\t\t// The pool is re-materialized every session, so the declared range always\n\t\t// includes the running host (D-073): an upgraded host never rejects its\n\t\t// own generated pool manifests through the hostVersion gate.\n\t\thostVersion: `>=${VERSION}`,\n\t\tapiVersion: EXPERIMENTAL_PUBLIC_API_VERSION,\n\t\tentry: \"./index.mjs\",\n\t\trequiredCapabilities: [\"tools\"],\n\t};\n\twriteFileSync(join(serverDir, \"plugin.json\"), `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\n\tconst entry =\n\t\tserver.url === undefined\n\t\t\t? [\n\t\t\t\t\t\"// Generated by the suite MCP registration pool (agent-session-services). Do not edit.\",\n\t\t\t\t\t`import createMcpStdioServerPlugin from \"../${MCP_POOL_BRIDGE_DIR}/index.mjs\";`,\n\t\t\t\t\t`export default createMcpStdioServerPlugin(${JSON.stringify({ command: server.command, args: server.args })});`,\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\")\n\t\t\t: [\n\t\t\t\t\t\"// Generated by the suite MCP registration pool (agent-session-services). Do not edit.\",\n\t\t\t\t\t`import { createMcpHttpServerPlugin } from \"${mcpHttpPluginImportSpec(serverDir)}\";`,\n\t\t\t\t\t`export default createMcpHttpServerPlugin(${JSON.stringify({\n\t\t\t\t\t\turl: server.url,\n\t\t\t\t\t\t...(server.headers === undefined ? {} : { headers: server.headers }),\n\t\t\t\t\t})});`,\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\");\n\twriteFileSync(join(serverDir, \"index.mjs\"), entry, \"utf8\");\n\treturn join(serverDir, \"plugin.json\");\n}\n\n/**\n * Resolves the suite's MCP registration pool (方案系统 M4: MCP 配置面, 设计\n * §4/§5) and materializes each injected server as a capability-plugin\n * manifest below `<agentDir>/mcp/pool/`, ready for the session's\n * `capabilityPluginPaths` channel — the same way plugins directory discovery\n * injects manifests. Filtering: the project level\n * (`<cwd>/.agent-forge/mcp.json`) is the third layer (设计 §4) and always\n * passes; the user level (`<agentDir>/mcp.json`) injects only servers named\n * in `suite.associations.mcp` — an empty association list means zero\n * user-level injection, the same semantics as skills/extensions.\n */\nexport function resolveSuiteMcpPool(options: {\n\tcwd: string;\n\tagentDir: string;\n\tsuite: SuiteDefinition;\n}): SuiteMcpPoolV1 {\n\tconst { cwd, agentDir, suite } = options;\n\tconst userConfigPath = join(agentDir, MCP_CONFIG_FILENAME);\n\tconst projectConfigPath = join(cwd, CONFIG_DIR_NAME, MCP_CONFIG_FILENAME);\n\tconst user = parseMcpConfig(userConfigPath);\n\tconst project = parseMcpConfig(projectConfigPath);\n\tconst diagnostics = [...project.diagnostics, ...user.diagnostics];\n\n\tconst selected = new Map<string, McpServerConfigV1 & { scope: \"user\" | \"project\" }>();\n\t// Third layer (设计 §4): project-level servers always pass; they win name\n\t// collisions over user definitions.\n\tfor (const [name, server] of project.servers) selected.set(name, { ...server, scope: \"project\" });\n\tfor (const [name, server] of user.servers) {\n\t\tif (selected.has(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`MCP server \"${name}\" from ${userConfigPath} is overridden by the project-level definition at ${projectConfigPath}; keeping the project one.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!suite.associations.mcp.includes(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`Suite \"${suite.id}\" MCP server \"${name}\" is not associated (associations.mcp); not injected.`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tselected.set(name, { ...server, scope: \"user\" });\n\t}\n\tfor (const name of suite.associations.mcp) {\n\t\tif (!selected.has(name)) {\n\t\t\tdiagnostics.push(\n\t\t\t\t`Suite \"${suite.id}\" dangling association \"${name}\" (mcp): not found in the discovered registry; ignored.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst servers: SuiteMcpServerV1[] = [];\n\tconst manifestPaths: string[] = [];\n\tconst deferredPluginIds: string[] = [];\n\tif (selected.size > 0) {\n\t\tconst poolDir = join(agentDir, MCP_POOL_DIR);\n\t\twriteMcpPoolBridge(poolDir);\n\t\tfor (const [name, server] of selected) {\n\t\t\tconst manifestPath = writeMcpPoolServer(poolDir, name, server);\n\t\t\tmanifestPaths.push(manifestPath);\n\t\t\tservers.push({\n\t\t\t\tname,\n\t\t\t\targs: server.args,\n\t\t\t\tscope: server.scope,\n\t\t\t\tmanifestPath,\n\t\t\t\tdeferred: server.deferredTools === true,\n\t\t\t\t...(server.url === undefined\n\t\t\t\t\t? { command: server.command }\n\t\t\t\t\t: {\n\t\t\t\t\t\t\turl: server.url,\n\t\t\t\t\t\t\t...(server.headers === undefined ? {} : { headers: server.headers }),\n\t\t\t\t\t\t}),\n\t\t\t});\n\t\t\tif (server.deferredTools === true) {\n\t\t\t\tdeferredPluginIds.push(`agent-forge.mcp.${name}`);\n\t\t\t}\n\t\t}\n\t}\n\treturn { servers, manifestPaths, deferredPluginIds, diagnostics };\n}\n\n/**\n * Create cwd-bound runtime services.\n *\n * Returns services plus diagnostics. It does not create an AgentSession.\n */\nexport async function createAgentSessionServices(\n\toptions: CreateAgentSessionServicesOptions,\n): Promise<AgentSessionServices> {\n\tconst cwd = resolvePath(options.cwd);\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getAgentDir();\n\tconst modelRuntime =\n\t\toptions.modelRuntime ??\n\t\t(await ModelRuntime.create({\n\t\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\t\tcredentials: options.credentials,\n\t\t\tsignal: options.modelRuntimeSignal,\n\t\t}));\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\t// Suite assembly (设计 §3/§4/§8, M2): resolve once and wire the shared\n\t// assembly into this loader. Off by default so evals/testkit services keep\n\t// their fixture resources unfiltered.\n\tlet suiteId: string | undefined;\n\tlet suiteLoaderOverrides:\n\t\t| Pick<\n\t\t\t\tDefaultResourceLoaderOptions,\n\t\t\t\t\"agentsFilesOverride\" | \"skillsOverride\" | \"systemPromptOverride\" | \"appendSystemPromptOverride\"\n\t\t >\n\t\t| undefined;\n\tlet suiteLocalSkillsDir: string | undefined;\n\tlet pluginProfile: BuiltinPluginProfileResolutionV1 | undefined;\n\t/** MCP registration pool for the assembled suite (M4); undefined when assembly is off. */\n\tlet mcpPool: SuiteMcpPoolV1 | undefined;\n\tif (options.suiteAssembly) {\n\t\tsuiteId = resolveSuiteId({\n\t\t\texplicit: options.suite,\n\t\t\tenvSuite: process.env[SUITE_ENV_VAR],\n\t\t\tsettings: settingsManager,\n\t\t\tagentDir,\n\t\t});\n\t\tconst suiteAssembly = createSuiteAssembly({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tsuiteId,\n\t\t\tpluginProfileId: options.pluginProfileId,\n\t\t\tselectedPluginIds: options.selectedPluginIds,\n\t\t\tdisabledPluginIds: options.disabledPluginIds,\n\t\t\tpluginHost: options.pluginHost,\n\t\t\tverifiedPlugins: options.verifiedPlugins,\n\t\t\tmanifestOverrides: options.manifestOverrides,\n\t\t});\n\t\tpluginProfile = suiteAssembly.pluginProfile;\n\t\tsuiteLoaderOverrides = suiteAssembly.loaderOverrides;\n\t\t// Suite-local skill layer (统一修复轮 B): <suiteDir>/skills rides this\n\t\t// loader's skill paths when the suite is active, mirroring the sdk's\n\t\t// self-built loader path so the two first-party entries cannot drift.\n\t\tsuiteLocalSkillsDir = suiteAssembly.localSkillsDir;\n\t\t// MCP registration pool (M4): read the mcp.json config surface, filter\n\t\t// by associations.mcp, and materialize the injected servers as\n\t\t// capability-plugin manifests for the session's explicit paths channel.\n\t\tmcpPool = resolveSuiteMcpPool({ cwd, agentDir, suite: suiteAssembly.workspace.suite });\n\t}\n\tconst additionalSkillPaths = [\n\t\t...(options.resourceLoaderOptions?.additionalSkillPaths ?? []),\n\t\t...(suiteLocalSkillsDir === undefined ? [] : [suiteLocalSkillsDir]),\n\t];\n\tconst resourceLoader = new DefaultResourceLoader({\n\t\t...(options.resourceLoaderOptions ?? {}),\n\t\t...suiteLoaderOverrides,\n\t\t...(additionalSkillPaths.length > 0 ? { additionalSkillPaths } : {}),\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t});\n\tawait resourceLoader.reload(options.resourceLoaderReloadOptions);\n\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tawait modelRuntime.refresh({ allowNetwork: false });\n\tfor (const message of mcpPool?.diagnostics ?? []) {\n\t\tdiagnostics.push({ type: \"info\", message });\n\t}\n\tdiagnostics.push(...(options.pluginBindingDiagnostics ?? []));\n\n\treturn {\n\t\tcwd,\n\t\tagentDir,\n\t\tmodelRuntime,\n\t\tsettingsManager,\n\t\tresourceLoader,\n\t\tdiagnostics,\n\t\t...(suiteId === undefined ? {} : { suiteId }),\n\t\t...(pluginProfile === undefined ? {} : { pluginProfile }),\n\t\t...(options.pluginProfileId === undefined ? {} : { pluginProfileId: options.pluginProfileId }),\n\t\t...(options.installedCapabilityPlugins === undefined\n\t\t\t? {}\n\t\t\t: { installedCapabilityPlugins: Object.freeze([...options.installedCapabilityPlugins]) }),\n\t\t...(mcpPool !== undefined && mcpPool.manifestPaths.length > 0\n\t\t\t? { mcpCapabilityPluginPaths: mcpPool.manifestPaths }\n\t\t\t: {}),\n\t\t...(mcpPool !== undefined && mcpPool.deferredPluginIds.length > 0\n\t\t\t? { mcpDeferredToolPluginIds: mcpPool.deferredPluginIds }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Create an AgentSession from previously created services.\n *\n * This keeps session creation separate from service creation so callers can\n * resolve model, thinking, tools, and other session inputs against the target\n * cwd before constructing the session.\n */\nexport async function createAgentSessionFromServices(\n\toptions: CreateAgentSessionFromServicesOptions,\n): Promise<CreateAgentSessionResult> {\n\treturn createAgentSession({\n\t\tcwd: options.services.cwd,\n\t\tagentDir: options.services.agentDir,\n\t\tmodelRuntime: options.services.modelRuntime,\n\t\tsettingsManager: options.services.settingsManager,\n\t\tresourceLoader: options.resourceLoader ?? options.services.resourceLoader,\n\t\tsessionManager: options.sessionManager,\n\t\tmodel: options.model,\n\t\tstreamFn: options.streamFn,\n\t\tthinkingLevel: options.thinkingLevel,\n\t\tscopedModels: options.scopedModels,\n\t\ttools: options.tools,\n\t\texcludeTools: options.excludeTools,\n\t\tnoTools: options.noTools,\n\t\tcustomTools: options.customTools,\n\t\t// Suite binding: an explicit option wins; otherwise the services' single\n\t\t// resolution result is forwarded so the sdk does not resolve again and\n\t\t// the two sides cannot drift (设计 §9).\n\t\t...(options.suite !== undefined || options.services.suiteId !== undefined\n\t\t\t? { suite: options.suite ?? options.services.suiteId }\n\t\t\t: {}),\n\t\t// Capability wiring (方案系统 M3): the sdk's caller-supplied-loader\n\t\t// boundary would leave it off for the services' own loader, so first-party\n\t\t// assembly turns it on here; an explicit option wins.\n\t\t...((options.suiteCapabilityWiring ?? options.services.suiteId !== undefined)\n\t\t\t? { suiteCapabilityWiring: true as const }\n\t\t\t: {}),\n\t\t...(options.services.pluginProfile === undefined ? {} : { pluginProfile: options.services.pluginProfile }),\n\t\t...(options.services.installedCapabilityPlugins === undefined\n\t\t\t? {}\n\t\t\t: { installedCapabilityPlugins: options.services.installedCapabilityPlugins }),\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t\tcapabilityMode: options.capabilityMode,\n\t\tdiscoverCapabilityPlugins: options.discoverCapabilityPlugins,\n\t\t// Trace/log control face (设计 §4.4/§5/§6): undefined passes through, so\n\t\t// the sdk defaults (trace on, no host logging) stay in effect.\n\t\ttraceEnabled: options.traceEnabled,\n\t\thostLogger: options.hostLogger,\n\t\t// MCP registration pool (M4): the services' generated manifest paths ride\n\t\t// the explicit caller-intent channel, so they bypass associations.plugins\n\t\t// filtering (they are governed by associations.mcp, not associations.plugins);\n\t\t// caller-provided paths keep discovery-order precedence on id conflicts.\n\t\t...(options.services.mcpCapabilityPluginPaths === undefined\n\t\t\t? { capabilityPluginPaths: options.capabilityPluginPaths }\n\t\t\t: {\n\t\t\t\t\tcapabilityPluginPaths: [\n\t\t\t\t\t\t...(options.capabilityPluginPaths ?? []),\n\t\t\t\t\t\t...options.services.mcpCapabilityPluginPaths,\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t...(options.services.mcpDeferredToolPluginIds === undefined\n\t\t\t? {}\n\t\t\t: { deferredToolPluginIds: options.services.mcpDeferredToolPluginIds }),\n\t\tcontextStrategyName: options.contextStrategyName,\n\t\tretryPolicyName: options.retryPolicyName,\n\t\tcompactionPolicyName: options.compactionPolicyName,\n\t\toverflowPolicyName: options.overflowPolicyName,\n\t\tbranchSummaryPolicyName: options.branchSummaryPolicyName,\n\t\t...(options.interactionHost === undefined ? {} : { interactionHost: options.interactionHost }),\n\t\t...(options.enableAgentTasks === undefined ? {} : { enableAgentTasks: options.enableAgentTasks }),\n\t\t...(options.subagentCommunicationWiring === undefined\n\t\t\t? {}\n\t\t\t: { subagentCommunicationWiring: options.subagentCommunicationWiring }),\n\t\t...(options.subagentPoolFromSelfInvocation === undefined\n\t\t\t? {}\n\t\t\t: { subagentPoolFromSelfInvocation: options.subagentPoolFromSelfInvocation }),\n\t});\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-tools.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,qBAAqB,EAAuB,MAAM,6BAA6B,CAAC;AAQ9F,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,KAAK,EAAE,cAAc,EAAsB,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAG/F,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAOnF;AAED,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,MAAM,EAAE,CAapF;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,qBAAqB,GAAG,QAAQ,EAAE,CAQtE;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,qBAAqB,EAAE,IAAI,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAE1G;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,CAe9F;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAmC/F;AAED,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,wBAAwB,CAAC,EAAE,OAAO,CAAA;CAAE,GAC1E,IAAI,CA0HN;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAMxE;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,qBAAqB,GAAG,KAAK,EAAE,CAmD3E;AAED,wBAAgB,gCAAgC,CAAC,OAAO,EAAE,qBAAqB,GAAG,IAAI,CAkBrF;AAED,wBAAsB,sBAAsB,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAc1F","sourcesContent":["/**\n * Tool registry, capability skills, and system-prompt assembly for\n * AgentSession.\n *\n * Extracted from `agent-session.ts`. Every function here operates on the\n * internal session facade ({@link AgentSessionInternals}); `AgentSession`\n * keeps same-name delegates so call sites, dynamic dispatch, and test spies\n * keep working unchanged.\n */\n\nimport type { AgentTool } from \"@agent-forge/agent-core\";\nimport type { AgentSessionInternals, ToolDefinitionEntry } from \"./agent-session-internal.ts\";\nimport {\n\tinstallSessionBootstrapSkills,\n\trefreshSessionBootstrapSkills,\n\tSKILL_CONTRIBUTION_POINT_ID,\n\tSKILL_CONTRIBUTION_POINT_VERSION,\n} from \"./extensions/index.ts\";\nimport { t } from \"./i18n/index.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { createSyntheticSourceInfo } from \"./source-info.ts\";\nimport { buildSystemPrompt } from \"./system-prompt.ts\";\nimport type { ToolDefinition, ToolExecuteContext, ToolInfo } from \"./tools/tool-definition.ts\";\nimport { wrapToolDefinition } from \"./tools/tool-definition-wrapper.ts\";\n\nexport function normalizePromptSnippet(text: string | undefined): string | undefined {\n\tif (!text) return undefined;\n\tconst oneLine = text\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn oneLine.length > 0 ? oneLine : undefined;\n}\n\nexport function normalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\tif (!guidelines || guidelines.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst unique = new Set<string>();\n\tfor (const guideline of guidelines) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\tunique.add(normalized);\n\t\t}\n\t}\n\treturn Array.from(unique);\n}\n\n/**\n * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.\n */\nexport function getAllTools(session: AgentSessionInternals): ToolInfo[] {\n\treturn Array.from(session._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t\tsourceInfo,\n\t}));\n}\n\nexport function getToolDefinition(session: AgentSessionInternals, name: string): ToolDefinition | undefined {\n\treturn session._toolDefinitions.get(name)?.definition;\n}\n\n/**\n * Set active tools by name.\n * Only tools in the registry can be enabled. Unknown tool names are ignored.\n * Also rebuilds the system prompt to reflect the new tool set.\n * Changes take effect on the next agent turn.\n */\nexport function setActiveToolsByName(session: AgentSessionInternals, toolNames: string[]): void {\n\tconst tools: AgentTool[] = [];\n\tconst validToolNames: string[] = [];\n\tfor (const name of toolNames) {\n\t\tconst tool = session._toolRegistry.get(name);\n\t\tif (tool) {\n\t\t\ttools.push(tool);\n\t\t\tvalidToolNames.push(name);\n\t\t}\n\t}\n\tsession.agent.state.tools = tools;\n\n\t// Rebuild base system prompt with new tool set\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(validToolNames);\n\tsession.agent.state.systemPrompt = session._systemPromptOverride ?? session._baseSystemPrompt;\n}\n\nexport function rebuildSystemPrompt(session: AgentSessionInternals, toolNames: string[]): string {\n\tconst validToolNames = toolNames.filter((name) => session._toolRegistry.has(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tconst promptGuidelines: string[] = [];\n\tfor (const name of validToolNames) {\n\t\tconst snippet = session._toolPromptSnippets.get(name);\n\t\tif (snippet) {\n\t\t\ttoolSnippets[name] = snippet;\n\t\t}\n\n\t\tconst toolGuidelines = session._toolPromptGuidelines.get(name);\n\t\tif (toolGuidelines) {\n\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t}\n\t}\n\n\tconst loaderSystemPrompt = session._resourceLoader.getSystemPrompt();\n\tconst loaderAppendSystemPrompt = session._resourceLoader.getAppendSystemPrompt();\n\tconst appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join(\"\\n\\n\") : undefined;\n\tconst loadedSkills = session._getAvailableSkills();\n\tconst loadedContextFiles = session._resourceLoader.getAgentsFiles().agentsFiles;\n\n\tsession._baseSystemPromptOptions = {\n\t\tcwd: session._cwd,\n\t\tskills: loadedSkills,\n\t\tcontextFiles: loadedContextFiles,\n\t\tcustomPrompt: loaderSystemPrompt,\n\t\torientationPrompt: session._orientationPrompt,\n\t\tpreferenceCard: session._preferenceCard,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t};\n\treturn buildSystemPrompt(session._baseSystemPromptOptions);\n}\n\nexport function refreshToolRegistry(\n\tsession: AgentSessionInternals,\n\toptions?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean },\n): void {\n\tconst previousRegistryNames = new Set(session._toolRegistry.keys());\n\tconst previousActiveToolNames = session.getActiveToolNames();\n\tconst allowedToolNames = session._allowedToolNames;\n\tconst excludedToolNames = session._excludedToolNames;\n\tconst isAllowedTool = (name: string): boolean =>\n\t\t(!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);\n\n\tconst allCustomTools = session._customTools\n\t\t.map((definition) => ({\n\t\t\tdefinition,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: \"sdk\" }),\n\t\t}))\n\t\t.filter((tool) => isAllowedTool(tool.definition.name));\n\tconst definitionRegistry = new Map<string, ToolDefinitionEntry>(\n\t\tArray.from(session._baseToolDefinitions.entries())\n\t\t\t.filter(([name]) => isAllowedTool(name))\n\t\t\t.map(([name, definition]) => [\n\t\t\t\tname,\n\t\t\t\t{\n\t\t\t\t\tdefinition,\n\t\t\t\t\tsourceInfo:\n\t\t\t\t\t\tsession._baseToolSources.get(name) ??\n\t\t\t\t\t\tcreateSyntheticSourceInfo(`<bootstrap:${name}>`, { source: \"agent-forge.bootstrap-tools\" }),\n\t\t\t\t},\n\t\t\t]),\n\t);\n\tfor (const tool of allCustomTools) {\n\t\tdefinitionRegistry.set(tool.definition.name, {\n\t\t\tdefinition: tool.definition,\n\t\t\tsourceInfo: tool.sourceInfo,\n\t\t});\n\t}\n\tsession._toolDefinitions = definitionRegistry;\n\tsession._toolPromptSnippets = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst snippet = normalizePromptSnippet(definition.promptSnippet);\n\t\t\t\treturn snippet ? ([definition.name, snippet] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string] => entry !== undefined),\n\t);\n\tsession._toolPromptGuidelines = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst guidelines = normalizePromptGuidelines(definition.promptGuidelines);\n\t\t\t\treturn guidelines.length > 0 ? ([definition.name, guidelines] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string[]] => entry !== undefined),\n\t);\n\t// Session-resolved execute context and dynamic-tool tracking replace the\n\t// former runner-mediated wrapper: tools receive the same session facts and\n\t// a tool that activates more tools during execute still surfaces them via\n\t// addedToolNames.\n\tconst executeContext = (): ToolExecuteContext => ({\n\t\tcwd: session.sessionManager.getCwd(),\n\t\tmodel: session.model,\n\t\tsessionManager: session.sessionManager,\n\t\tthinkingLevel: session.thinkingLevel,\n\t});\n\tconst wrapWithDynamicToolTracking = ({ definition }: { definition: ToolDefinition }): AgentTool => {\n\t\tconst tool = wrapToolDefinition(definition, executeContext);\n\t\tconst execute = tool.execute;\n\t\treturn {\n\t\t\t...tool,\n\t\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\t\tconst activeBefore = session.getActiveToolNames();\n\t\t\t\tconst result = await execute(toolCallId, params, signal, onUpdate);\n\t\t\t\tconst activeAfter = session.getActiveToolNames();\n\t\t\t\tif (!activeBefore.every((name) => activeAfter.includes(name))) return result;\n\n\t\t\t\tconst beforeNames = new Set(activeBefore);\n\t\t\t\tconst addedToolNames = activeAfter.filter((name) => !beforeNames.has(name));\n\t\t\t\tif (addedToolNames.length === 0) return result;\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\taddedToolNames: [...new Set([...(result.addedToolNames ?? []), ...addedToolNames])],\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t};\n\tconst wrappedExtensionTools = allCustomTools.map(wrapWithDynamicToolTracking);\n\tconst wrappedBuiltInTools = Array.from(session._baseToolDefinitions.values())\n\t\t.filter((definition) => isAllowedTool(definition.name))\n\t\t.map((definition) => wrapWithDynamicToolTracking({ definition }));\n\n\tconst toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));\n\tfor (const tool of wrappedExtensionTools as AgentTool[]) {\n\t\ttoolRegistry.set(tool.name, tool);\n\t}\n\tsession._toolRegistry = toolRegistry;\n\n\tconst nextActiveToolNames = (\n\t\toptions?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]\n\t).filter((name) => isAllowedTool(name));\n\n\tif (allowedToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (allowedToolNames.has(toolName)) {\n\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t}\n\t\t}\n\t} else if (options?.includeAllExtensionTools) {\n\t\tfor (const tool of wrappedExtensionTools) {\n\t\t\tnextActiveToolNames.push(tool.name);\n\t\t}\n\t} else if (!options?.activeToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (previousRegistryNames.has(toolName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Deferred tools (e.g. MCP servers configured with deferredTools)\n\t\t\t// register but stay out of the default active set until tool_search\n\t\t\t// or an explicit activation names them.\n\t\t\tif (session._deferredToolPluginIds.has(session._baseToolSources.get(toolName)?.source ?? \"\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnextActiveToolNames.push(toolName);\n\t\t}\n\t}\n\n\tsession.setActiveToolsByName([...new Set(nextActiveToolNames)]);\n}\n\nexport function syncCapabilityTools(session: AgentSessionInternals): void {\n\tconst tools = session._capabilityRuntime?.listTools() ?? [];\n\tsession._baseToolDefinitions = new Map(tools.map(({ name, definition }) => [name, definition as ToolDefinition]));\n\tsession._baseToolSources = new Map(\n\t\ttools.map(({ name, source }) => [name, createSyntheticSourceInfo(`<plugin:${source}:${name}>`, { source })]),\n\t);\n}\n\nexport function getCapabilitySkills(session: AgentSessionInternals): Skill[] {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return [];\n\t// The skill contribution point is owned by the bootstrap-skills plugin. In\n\t// hosts that never install it (assistant suite, print mode) — or while that\n\t// owner is inactive — `listContributions` throws \"Contribution point is not\n\t// defined\". That state means \"no contributed skills\", not a failure: every\n\t// tool-registry change rebuilds the system prompt, so propagating the error\n\t// turned each rebuild into an error-level plugin.log record. Any other\n\t// failure still propagates.\n\tlet contributed: ReturnType<typeof runtime.listContributions>;\n\ttry {\n\t\tcontributed = runtime.listContributions(SKILL_CONTRIBUTION_POINT_ID, SKILL_CONTRIBUTION_POINT_VERSION);\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !error.message.startsWith(\"Contribution point is not defined\")) throw error;\n\t\treturn [];\n\t}\n\tconst contributedSkills = contributed\n\t\t.filter(\n\t\t\t(entry): entry is typeof entry & { value: Skill } =>\n\t\t\t\tentry.value !== null && typeof entry.value === \"object\" && \"name\" in entry.value,\n\t\t)\n\t\t.map((entry) => ({\n\t\t\t...entry.value,\n\t\t\tdisableModelInvocation: entry.value.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<contribution:${entry.owner}:${entry.id}>`, {\n\t\t\t\tsource: entry.owner,\n\t\t\t\tbaseDir: entry.value.baseDir,\n\t\t\t}),\n\t\t}));\n\tconst contributedNames = new Set(contributedSkills.map((skill) => skill.name));\n\tconst legacyFilter = session._capabilitySkillsFilter;\n\tconst legacy = runtime\n\t\t.listSkills()\n\t\t.filter(({ definition }) => !contributedNames.has(definition.name))\n\t\t.map(({ definition, source }) => ({\n\t\t\t...definition,\n\t\t\tdisableModelInvocation: definition.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<plugin:${source}:${definition.name}>`, {\n\t\t\t\tsource,\n\t\t\t\tbaseDir: definition.baseDir,\n\t\t\t}),\n\t\t}))\n\t\t// Suite association filtering (方案系统 M3): the assembler owns the\n\t\t// policy; the session only applies the injected function. The\n\t\t// bootstrap-skills contribution face is already loader-filtered and\n\t\t// must not be filtered twice.\n\t\t.filter((skill) => (legacyFilter ? legacyFilter([skill]).length > 0 : true));\n\treturn [...contributedSkills, ...legacy].sort(\n\t\t(left, right) => left.name.localeCompare(right.name) || left.sourceInfo.path.localeCompare(right.sourceInfo.path),\n\t);\n}\n\nexport function validateCapabilitySkillConflicts(session: AgentSessionInternals): void {\n\tconst resourceNames = new Set<string>();\n\tconst resourceFilePaths = new Set<string>();\n\tfor (const skill of session._resourceLoader.getSkills().skills) {\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill is duplicated in resources: {name}\", { name: skill.name }));\n\t\tresourceNames.add(skill.name);\n\t\tresourceFilePaths.add(skill.filePath);\n\t}\n\tfor (const skill of session._getCapabilitySkills()) {\n\t\t// bootstrap-skills mirrors the same on-disk SKILL.md into the capability\n\t\t// layer: same name AND same file is one skill seen through two channels,\n\t\t// not a conflict. Same name from a different file (e.g. an MCP server\n\t\t// contributing a skill that collides with a disk skill) is a real one.\n\t\tif (typeof skill.filePath === \"string\" && resourceFilePaths.has(skill.filePath)) continue;\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill conflicts with a resource skill: {name}\", { name: skill.name }));\n\t}\n}\n\nexport async function refreshBootstrapSkills(session: AgentSessionInternals): Promise<void> {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return;\n\tsession._validateCapabilitySkillConflicts();\n\tif (session._bootstrapSkillsHandle) {\n\t\tawait refreshSessionBootstrapSkills(runtime, session._resourceLoader.getSkills().skills);\n\t} else {\n\t\tsession._bootstrapSkillsHandle = installSessionBootstrapSkills(\n\t\t\truntime,\n\t\t\tsession._resourceLoader.getSkills().skills,\n\t\t);\n\t}\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(session.getActiveToolNames());\n\tsession.agent.state.systemPrompt = session._baseSystemPrompt;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-tools.d.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;AAED,wBAAsB,sBAAsB,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAc1F","sourcesContent":["/**\n * Tool registry, capability skills, and system-prompt assembly for\n * AgentSession.\n *\n * Extracted from `agent-session.ts`. Every function here operates on the\n * internal session facade ({@link AgentSessionInternals}); `AgentSession`\n * keeps same-name delegates so call sites, dynamic dispatch, and test spies\n * keep working unchanged.\n */\n\nimport type { AgentTool } from \"@agent-forge/agent-core\";\nimport type { AgentSessionInternals, ToolDefinitionEntry } from \"./agent-session-internal.ts\";\nimport {\n\tinstallSessionBootstrapSkills,\n\trefreshSessionBootstrapSkills,\n\tSKILL_CONTRIBUTION_POINT_ID,\n\tSKILL_CONTRIBUTION_POINT_VERSION,\n} from \"./extensions/index.ts\";\nimport { t } from \"./i18n/index.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { createSyntheticSourceInfo } from \"./source-info.ts\";\nimport { buildSystemPrompt } from \"./system-prompt.ts\";\nimport type { ToolDefinition, ToolExecuteContext, ToolInfo } from \"./tools/tool-definition.ts\";\nimport { wrapToolDefinition } from \"./tools/tool-definition-wrapper.ts\";\n\nexport function normalizePromptSnippet(text: string | undefined): string | undefined {\n\tif (!text) return undefined;\n\tconst oneLine = text\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn oneLine.length > 0 ? oneLine : undefined;\n}\n\nexport function normalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\tif (!guidelines || guidelines.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst unique = new Set<string>();\n\tfor (const guideline of guidelines) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\tunique.add(normalized);\n\t\t}\n\t}\n\treturn Array.from(unique);\n}\n\n/**\n * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.\n */\nexport function getAllTools(session: AgentSessionInternals): ToolInfo[] {\n\treturn Array.from(session._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t\tsourceInfo,\n\t}));\n}\n\nexport function getToolDefinition(session: AgentSessionInternals, name: string): ToolDefinition | undefined {\n\treturn session._toolDefinitions.get(name)?.definition;\n}\n\n/**\n * Set active tools by name.\n * Only tools in the registry can be enabled. Unknown tool names are ignored.\n * Also rebuilds the system prompt to reflect the new tool set.\n * Changes take effect on the next agent turn.\n */\nexport function setActiveToolsByName(session: AgentSessionInternals, toolNames: string[]): void {\n\tconst tools: AgentTool[] = [];\n\tconst validToolNames: string[] = [];\n\tfor (const name of toolNames) {\n\t\tconst tool = session._toolRegistry.get(name);\n\t\tif (tool) {\n\t\t\ttools.push(tool);\n\t\t\tvalidToolNames.push(name);\n\t\t}\n\t}\n\tsession.agent.state.tools = tools;\n\n\t// Rebuild base system prompt with new tool set\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(validToolNames);\n\tsession.agent.state.systemPrompt = session._systemPromptOverride ?? session._baseSystemPrompt;\n}\n\nexport function rebuildSystemPrompt(session: AgentSessionInternals, toolNames: string[]): string {\n\tconst validToolNames = toolNames.filter((name) => session._toolRegistry.has(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tconst promptGuidelines: string[] = [];\n\tfor (const name of validToolNames) {\n\t\tconst snippet = session._toolPromptSnippets.get(name);\n\t\tif (snippet) {\n\t\t\ttoolSnippets[name] = snippet;\n\t\t}\n\n\t\tconst toolGuidelines = session._toolPromptGuidelines.get(name);\n\t\tif (toolGuidelines) {\n\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t}\n\t}\n\n\tconst loaderSystemPrompt = session._resourceLoader.getSystemPrompt();\n\tconst loaderAppendSystemPrompt = session._resourceLoader.getAppendSystemPrompt();\n\tconst appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join(\"\\n\\n\") : undefined;\n\tconst loadedSkills = session._getAvailableSkills();\n\tconst loadedContextFiles = session._resourceLoader.getAgentsFiles().agentsFiles;\n\n\tsession._baseSystemPromptOptions = {\n\t\tcwd: session._cwd,\n\t\tskills: loadedSkills,\n\t\tcontextFiles: loadedContextFiles,\n\t\tcustomPrompt: loaderSystemPrompt,\n\t\torientationPrompt: session._orientationPrompt,\n\t\tpreferenceCard: session._preferenceCard,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t};\n\treturn buildSystemPrompt(session._baseSystemPromptOptions);\n}\n\nexport function refreshToolRegistry(\n\tsession: AgentSessionInternals,\n\toptions?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean },\n): void {\n\tconst previousRegistryNames = new Set(session._toolRegistry.keys());\n\tconst previousActiveToolNames = session.getActiveToolNames();\n\tconst allowedToolNames = session._allowedToolNames;\n\tconst excludedToolNames = session._excludedToolNames;\n\tconst isAllowedTool = (name: string): boolean =>\n\t\t(!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);\n\n\tconst allCustomTools = session._customTools\n\t\t.map((definition) => ({\n\t\t\tdefinition,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: \"sdk\" }),\n\t\t}))\n\t\t.filter((tool) => isAllowedTool(tool.definition.name));\n\tconst definitionRegistry = new Map<string, ToolDefinitionEntry>(\n\t\tArray.from(session._baseToolDefinitions.entries())\n\t\t\t.filter(([name]) => isAllowedTool(name))\n\t\t\t.map(([name, definition]) => [\n\t\t\t\tname,\n\t\t\t\t{\n\t\t\t\t\tdefinition,\n\t\t\t\t\t// syncCapabilityTools populates _baseToolSources in lockstep with\n\t\t\t\t\t// _baseToolDefinitions, so this fallback is a desync guard only;\n\t\t\t\t\t// the default coding tools surface rides the coding-tools package\n\t\t\t\t\t// id since D-082 批 1.\n\t\t\t\t\tsourceInfo:\n\t\t\t\t\t\tsession._baseToolSources.get(name) ??\n\t\t\t\t\t\tcreateSyntheticSourceInfo(`<bootstrap:${name}>`, { source: \"agent-forge.plugin.coding-tools\" }),\n\t\t\t\t},\n\t\t\t]),\n\t);\n\tfor (const tool of allCustomTools) {\n\t\tdefinitionRegistry.set(tool.definition.name, {\n\t\t\tdefinition: tool.definition,\n\t\t\tsourceInfo: tool.sourceInfo,\n\t\t});\n\t}\n\tsession._toolDefinitions = definitionRegistry;\n\tsession._toolPromptSnippets = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst snippet = normalizePromptSnippet(definition.promptSnippet);\n\t\t\t\treturn snippet ? ([definition.name, snippet] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string] => entry !== undefined),\n\t);\n\tsession._toolPromptGuidelines = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst guidelines = normalizePromptGuidelines(definition.promptGuidelines);\n\t\t\t\treturn guidelines.length > 0 ? ([definition.name, guidelines] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string[]] => entry !== undefined),\n\t);\n\t// Session-resolved execute context and dynamic-tool tracking replace the\n\t// former runner-mediated wrapper: tools receive the same session facts and\n\t// a tool that activates more tools during execute still surfaces them via\n\t// addedToolNames.\n\tconst executeContext = (): ToolExecuteContext => ({\n\t\tcwd: session.sessionManager.getCwd(),\n\t\tmodel: session.model,\n\t\tsessionManager: session.sessionManager,\n\t\tthinkingLevel: session.thinkingLevel,\n\t});\n\tconst wrapWithDynamicToolTracking = ({ definition }: { definition: ToolDefinition }): AgentTool => {\n\t\tconst tool = wrapToolDefinition(definition, executeContext);\n\t\tconst execute = tool.execute;\n\t\treturn {\n\t\t\t...tool,\n\t\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\t\tconst activeBefore = session.getActiveToolNames();\n\t\t\t\tconst result = await execute(toolCallId, params, signal, onUpdate);\n\t\t\t\tconst activeAfter = session.getActiveToolNames();\n\t\t\t\tif (!activeBefore.every((name) => activeAfter.includes(name))) return result;\n\n\t\t\t\tconst beforeNames = new Set(activeBefore);\n\t\t\t\tconst addedToolNames = activeAfter.filter((name) => !beforeNames.has(name));\n\t\t\t\tif (addedToolNames.length === 0) return result;\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\taddedToolNames: [...new Set([...(result.addedToolNames ?? []), ...addedToolNames])],\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t};\n\tconst wrappedExtensionTools = allCustomTools.map(wrapWithDynamicToolTracking);\n\tconst wrappedBuiltInTools = Array.from(session._baseToolDefinitions.values())\n\t\t.filter((definition) => isAllowedTool(definition.name))\n\t\t.map((definition) => wrapWithDynamicToolTracking({ definition }));\n\n\tconst toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));\n\tfor (const tool of wrappedExtensionTools as AgentTool[]) {\n\t\ttoolRegistry.set(tool.name, tool);\n\t}\n\tsession._toolRegistry = toolRegistry;\n\n\tconst nextActiveToolNames = (\n\t\toptions?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]\n\t).filter((name) => isAllowedTool(name));\n\n\tif (allowedToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (allowedToolNames.has(toolName)) {\n\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t}\n\t\t}\n\t} else if (options?.includeAllExtensionTools) {\n\t\tfor (const tool of wrappedExtensionTools) {\n\t\t\tnextActiveToolNames.push(tool.name);\n\t\t}\n\t} else if (!options?.activeToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (previousRegistryNames.has(toolName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Deferred tools (e.g. MCP servers configured with deferredTools)\n\t\t\t// register but stay out of the default active set until tool_search\n\t\t\t// or an explicit activation names them.\n\t\t\tif (session._deferredToolPluginIds.has(session._baseToolSources.get(toolName)?.source ?? \"\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnextActiveToolNames.push(toolName);\n\t\t}\n\t}\n\n\tsession.setActiveToolsByName([...new Set(nextActiveToolNames)]);\n}\n\nexport function syncCapabilityTools(session: AgentSessionInternals): void {\n\tconst tools = session._capabilityRuntime?.listTools() ?? [];\n\tsession._baseToolDefinitions = new Map(tools.map(({ name, definition }) => [name, definition as ToolDefinition]));\n\tsession._baseToolSources = new Map(\n\t\ttools.map(({ name, source }) => [name, createSyntheticSourceInfo(`<plugin:${source}:${name}>`, { source })]),\n\t);\n}\n\nexport function getCapabilitySkills(session: AgentSessionInternals): Skill[] {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return [];\n\t// The skill contribution point is owned by the bootstrap-skills plugin. In\n\t// hosts that never install it (assistant suite, print mode) — or while that\n\t// owner is inactive — `listContributions` throws \"Contribution point is not\n\t// defined\". That state means \"no contributed skills\", not a failure: every\n\t// tool-registry change rebuilds the system prompt, so propagating the error\n\t// turned each rebuild into an error-level plugin.log record. Any other\n\t// failure still propagates.\n\tlet contributed: ReturnType<typeof runtime.listContributions>;\n\ttry {\n\t\tcontributed = runtime.listContributions(SKILL_CONTRIBUTION_POINT_ID, SKILL_CONTRIBUTION_POINT_VERSION);\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !error.message.startsWith(\"Contribution point is not defined\")) throw error;\n\t\treturn [];\n\t}\n\tconst contributedSkills = contributed\n\t\t.filter(\n\t\t\t(entry): entry is typeof entry & { value: Skill } =>\n\t\t\t\tentry.value !== null && typeof entry.value === \"object\" && \"name\" in entry.value,\n\t\t)\n\t\t.map((entry) => ({\n\t\t\t...entry.value,\n\t\t\tdisableModelInvocation: entry.value.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<contribution:${entry.owner}:${entry.id}>`, {\n\t\t\t\tsource: entry.owner,\n\t\t\t\tbaseDir: entry.value.baseDir,\n\t\t\t}),\n\t\t}));\n\tconst contributedNames = new Set(contributedSkills.map((skill) => skill.name));\n\tconst legacyFilter = session._capabilitySkillsFilter;\n\tconst legacy = runtime\n\t\t.listSkills()\n\t\t.filter(({ definition }) => !contributedNames.has(definition.name))\n\t\t.map(({ definition, source }) => ({\n\t\t\t...definition,\n\t\t\tdisableModelInvocation: definition.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<plugin:${source}:${definition.name}>`, {\n\t\t\t\tsource,\n\t\t\t\tbaseDir: definition.baseDir,\n\t\t\t}),\n\t\t}))\n\t\t// Suite association filtering (方案系统 M3): the assembler owns the\n\t\t// policy; the session only applies the injected function. The\n\t\t// bootstrap-skills contribution face is already loader-filtered and\n\t\t// must not be filtered twice.\n\t\t.filter((skill) => (legacyFilter ? legacyFilter([skill]).length > 0 : true));\n\treturn [...contributedSkills, ...legacy].sort(\n\t\t(left, right) => left.name.localeCompare(right.name) || left.sourceInfo.path.localeCompare(right.sourceInfo.path),\n\t);\n}\n\nexport function validateCapabilitySkillConflicts(session: AgentSessionInternals): void {\n\tconst resourceNames = new Set<string>();\n\tconst resourceFilePaths = new Set<string>();\n\tfor (const skill of session._resourceLoader.getSkills().skills) {\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill is duplicated in resources: {name}\", { name: skill.name }));\n\t\tresourceNames.add(skill.name);\n\t\tresourceFilePaths.add(skill.filePath);\n\t}\n\tfor (const skill of session._getCapabilitySkills()) {\n\t\t// bootstrap-skills mirrors the same on-disk SKILL.md into the capability\n\t\t// layer: same name AND same file is one skill seen through two channels,\n\t\t// not a conflict. Same name from a different file (e.g. an MCP server\n\t\t// contributing a skill that collides with a disk skill) is a real one.\n\t\tif (typeof skill.filePath === \"string\" && resourceFilePaths.has(skill.filePath)) continue;\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill conflicts with a resource skill: {name}\", { name: skill.name }));\n\t}\n}\n\nexport async function refreshBootstrapSkills(session: AgentSessionInternals): Promise<void> {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return;\n\tsession._validateCapabilitySkillConflicts();\n\tif (session._bootstrapSkillsHandle) {\n\t\tawait refreshSessionBootstrapSkills(runtime, session._resourceLoader.getSkills().skills);\n\t} else {\n\t\tsession._bootstrapSkillsHandle = installSessionBootstrapSkills(\n\t\t\truntime,\n\t\t\tsession._resourceLoader.getSkills().skills,\n\t\t);\n\t}\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(session.getActiveToolNames());\n\tsession.agent.state.systemPrompt = session._baseSystemPrompt;\n}\n"]}
|
|
@@ -121,8 +121,12 @@ export function refreshToolRegistry(session, options) {
|
|
|
121
121
|
name,
|
|
122
122
|
{
|
|
123
123
|
definition,
|
|
124
|
+
// syncCapabilityTools populates _baseToolSources in lockstep with
|
|
125
|
+
// _baseToolDefinitions, so this fallback is a desync guard only;
|
|
126
|
+
// the default coding tools surface rides the coding-tools package
|
|
127
|
+
// id since D-082 批 1.
|
|
124
128
|
sourceInfo: session._baseToolSources.get(name) ??
|
|
125
|
-
createSyntheticSourceInfo(`<bootstrap:${name}>`, { source: "agent-forge.
|
|
129
|
+
createSyntheticSourceInfo(`<bootstrap:${name}>`, { source: "agent-forge.plugin.coding-tools" }),
|
|
126
130
|
},
|
|
127
131
|
]));
|
|
128
132
|
for (const tool of allCustomTools) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-tools.js","sourceRoot":"","sources":["../../src/core/agent-session-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EACN,6BAA6B,EAC7B,6BAA6B,EAC7B,2BAA2B,EAC3B,gCAAgC,GAChC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,CAAC,EAAE,MAAM,iBAAiB,CAAC;AAEpC,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,OAAO,E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O,CAAC,kBAAkB,CAAC;IAC3C,IAAI,CAAC,OAAO;QAAE,OAAO;IACrB,OAAO,CAAC,iCAAiC,EAAE,CAAC;IAC5C,IAAI,OAAO,CAAC,sBAAsB,EAAE,CAAC;QACpC,MAAM,6BAA6B,CAAC,OAAO,EAAE,OAAO,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,CAAC;IAC1F,CAAC;SAAM,CAAC;QACP,OAAO,CAAC,sBAAsB,GAAG,6BAA6B,CAC7D,OAAO,EACP,OAAO,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,MAAM,CAC1C,CAAC;IACH,CAAC;IACD,OAAO,CAAC,iBAAiB,GAAG,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAAC;IACvF,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,GAAG,OAAO,CAAC,iBAAiB,CAAC;AAAA,CAC7D","sourcesContent":["/**\n * Tool registry, capability skills, and system-prompt assembly for\n * AgentSession.\n *\n * Extracted from `agent-session.ts`. Every function here operates on the\n * internal session facade ({@link AgentSessionInternals}); `AgentSession`\n * keeps same-name delegates so call sites, dynamic dispatch, and test spies\n * keep working unchanged.\n */\n\nimport type { AgentTool } from \"@agent-forge/agent-core\";\nimport type { AgentSessionInternals, ToolDefinitionEntry } from \"./agent-session-internal.ts\";\nimport {\n\tinstallSessionBootstrapSkills,\n\trefreshSessionBootstrapSkills,\n\tSKILL_CONTRIBUTION_POINT_ID,\n\tSKILL_CONTRIBUTION_POINT_VERSION,\n} from \"./extensions/index.ts\";\nimport { t } from \"./i18n/index.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { createSyntheticSourceInfo } from \"./source-info.ts\";\nimport { buildSystemPrompt } from \"./system-prompt.ts\";\nimport type { ToolDefinition, ToolExecuteContext, ToolInfo } from \"./tools/tool-definition.ts\";\nimport { wrapToolDefinition } from \"./tools/tool-definition-wrapper.ts\";\n\nexport function normalizePromptSnippet(text: string | undefined): string | undefined {\n\tif (!text) return undefined;\n\tconst oneLine = text\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn oneLine.length > 0 ? oneLine : undefined;\n}\n\nexport function normalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\tif (!guidelines || guidelines.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst unique = new Set<string>();\n\tfor (const guideline of guidelines) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\tunique.add(normalized);\n\t\t}\n\t}\n\treturn Array.from(unique);\n}\n\n/**\n * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.\n */\nexport function getAllTools(session: AgentSessionInternals): ToolInfo[] {\n\treturn Array.from(session._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t\tsourceInfo,\n\t}));\n}\n\nexport function getToolDefinition(session: AgentSessionInternals, name: string): ToolDefinition | undefined {\n\treturn session._toolDefinitions.get(name)?.definition;\n}\n\n/**\n * Set active tools by name.\n * Only tools in the registry can be enabled. Unknown tool names are ignored.\n * Also rebuilds the system prompt to reflect the new tool set.\n * Changes take effect on the next agent turn.\n */\nexport function setActiveToolsByName(session: AgentSessionInternals, toolNames: string[]): void {\n\tconst tools: AgentTool[] = [];\n\tconst validToolNames: string[] = [];\n\tfor (const name of toolNames) {\n\t\tconst tool = session._toolRegistry.get(name);\n\t\tif (tool) {\n\t\t\ttools.push(tool);\n\t\t\tvalidToolNames.push(name);\n\t\t}\n\t}\n\tsession.agent.state.tools = tools;\n\n\t// Rebuild base system prompt with new tool set\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(validToolNames);\n\tsession.agent.state.systemPrompt = session._systemPromptOverride ?? session._baseSystemPrompt;\n}\n\nexport function rebuildSystemPrompt(session: AgentSessionInternals, toolNames: string[]): string {\n\tconst validToolNames = toolNames.filter((name) => session._toolRegistry.has(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tconst promptGuidelines: string[] = [];\n\tfor (const name of validToolNames) {\n\t\tconst snippet = session._toolPromptSnippets.get(name);\n\t\tif (snippet) {\n\t\t\ttoolSnippets[name] = snippet;\n\t\t}\n\n\t\tconst toolGuidelines = session._toolPromptGuidelines.get(name);\n\t\tif (toolGuidelines) {\n\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t}\n\t}\n\n\tconst loaderSystemPrompt = session._resourceLoader.getSystemPrompt();\n\tconst loaderAppendSystemPrompt = session._resourceLoader.getAppendSystemPrompt();\n\tconst appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join(\"\\n\\n\") : undefined;\n\tconst loadedSkills = session._getAvailableSkills();\n\tconst loadedContextFiles = session._resourceLoader.getAgentsFiles().agentsFiles;\n\n\tsession._baseSystemPromptOptions = {\n\t\tcwd: session._cwd,\n\t\tskills: loadedSkills,\n\t\tcontextFiles: loadedContextFiles,\n\t\tcustomPrompt: loaderSystemPrompt,\n\t\torientationPrompt: session._orientationPrompt,\n\t\tpreferenceCard: session._preferenceCard,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t};\n\treturn buildSystemPrompt(session._baseSystemPromptOptions);\n}\n\nexport function refreshToolRegistry(\n\tsession: AgentSessionInternals,\n\toptions?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean },\n): void {\n\tconst previousRegistryNames = new Set(session._toolRegistry.keys());\n\tconst previousActiveToolNames = session.getActiveToolNames();\n\tconst allowedToolNames = session._allowedToolNames;\n\tconst excludedToolNames = session._excludedToolNames;\n\tconst isAllowedTool = (name: string): boolean =>\n\t\t(!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);\n\n\tconst allCustomTools = session._customTools\n\t\t.map((definition) => ({\n\t\t\tdefinition,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: \"sdk\" }),\n\t\t}))\n\t\t.filter((tool) => isAllowedTool(tool.definition.name));\n\tconst definitionRegistry = new Map<string, ToolDefinitionEntry>(\n\t\tArray.from(session._baseToolDefinitions.entries())\n\t\t\t.filter(([name]) => isAllowedTool(name))\n\t\t\t.map(([name, definition]) => [\n\t\t\t\tname,\n\t\t\t\t{\n\t\t\t\t\tdefinition,\n\t\t\t\t\tsourceInfo:\n\t\t\t\t\t\tsession._baseToolSources.get(name) ??\n\t\t\t\t\t\tcreateSyntheticSourceInfo(`<bootstrap:${name}>`, { source: \"agent-forge.bootstrap-tools\" }),\n\t\t\t\t},\n\t\t\t]),\n\t);\n\tfor (const tool of allCustomTools) {\n\t\tdefinitionRegistry.set(tool.definition.name, {\n\t\t\tdefinition: tool.definition,\n\t\t\tsourceInfo: tool.sourceInfo,\n\t\t});\n\t}\n\tsession._toolDefinitions = definitionRegistry;\n\tsession._toolPromptSnippets = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst snippet = normalizePromptSnippet(definition.promptSnippet);\n\t\t\t\treturn snippet ? ([definition.name, snippet] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string] => entry !== undefined),\n\t);\n\tsession._toolPromptGuidelines = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst guidelines = normalizePromptGuidelines(definition.promptGuidelines);\n\t\t\t\treturn guidelines.length > 0 ? ([definition.name, guidelines] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string[]] => entry !== undefined),\n\t);\n\t// Session-resolved execute context and dynamic-tool tracking replace the\n\t// former runner-mediated wrapper: tools receive the same session facts and\n\t// a tool that activates more tools during execute still surfaces them via\n\t// addedToolNames.\n\tconst executeContext = (): ToolExecuteContext => ({\n\t\tcwd: session.sessionManager.getCwd(),\n\t\tmodel: session.model,\n\t\tsessionManager: session.sessionManager,\n\t\tthinkingLevel: session.thinkingLevel,\n\t});\n\tconst wrapWithDynamicToolTracking = ({ definition }: { definition: ToolDefinition }): AgentTool => {\n\t\tconst tool = wrapToolDefinition(definition, executeContext);\n\t\tconst execute = tool.execute;\n\t\treturn {\n\t\t\t...tool,\n\t\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\t\tconst activeBefore = session.getActiveToolNames();\n\t\t\t\tconst result = await execute(toolCallId, params, signal, onUpdate);\n\t\t\t\tconst activeAfter = session.getActiveToolNames();\n\t\t\t\tif (!activeBefore.every((name) => activeAfter.includes(name))) return result;\n\n\t\t\t\tconst beforeNames = new Set(activeBefore);\n\t\t\t\tconst addedToolNames = activeAfter.filter((name) => !beforeNames.has(name));\n\t\t\t\tif (addedToolNames.length === 0) return result;\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\taddedToolNames: [...new Set([...(result.addedToolNames ?? []), ...addedToolNames])],\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t};\n\tconst wrappedExtensionTools = allCustomTools.map(wrapWithDynamicToolTracking);\n\tconst wrappedBuiltInTools = Array.from(session._baseToolDefinitions.values())\n\t\t.filter((definition) => isAllowedTool(definition.name))\n\t\t.map((definition) => wrapWithDynamicToolTracking({ definition }));\n\n\tconst toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));\n\tfor (const tool of wrappedExtensionTools as AgentTool[]) {\n\t\ttoolRegistry.set(tool.name, tool);\n\t}\n\tsession._toolRegistry = toolRegistry;\n\n\tconst nextActiveToolNames = (\n\t\toptions?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]\n\t).filter((name) => isAllowedTool(name));\n\n\tif (allowedToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (allowedToolNames.has(toolName)) {\n\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t}\n\t\t}\n\t} else if (options?.includeAllExtensionTools) {\n\t\tfor (const tool of wrappedExtensionTools) {\n\t\t\tnextActiveToolNames.push(tool.name);\n\t\t}\n\t} else if (!options?.activeToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (previousRegistryNames.has(toolName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Deferred tools (e.g. MCP servers configured with deferredTools)\n\t\t\t// register but stay out of the default active set until tool_search\n\t\t\t// or an explicit activation names them.\n\t\t\tif (session._deferredToolPluginIds.has(session._baseToolSources.get(toolName)?.source ?? \"\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnextActiveToolNames.push(toolName);\n\t\t}\n\t}\n\n\tsession.setActiveToolsByName([...new Set(nextActiveToolNames)]);\n}\n\nexport function syncCapabilityTools(session: AgentSessionInternals): void {\n\tconst tools = session._capabilityRuntime?.listTools() ?? [];\n\tsession._baseToolDefinitions = new Map(tools.map(({ name, definition }) => [name, definition as ToolDefinition]));\n\tsession._baseToolSources = new Map(\n\t\ttools.map(({ name, source }) => [name, createSyntheticSourceInfo(`<plugin:${source}:${name}>`, { source })]),\n\t);\n}\n\nexport function getCapabilitySkills(session: AgentSessionInternals): Skill[] {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return [];\n\t// The skill contribution point is owned by the bootstrap-skills plugin. In\n\t// hosts that never install it (assistant suite, print mode) — or while that\n\t// owner is inactive — `listContributions` throws \"Contribution point is not\n\t// defined\". That state means \"no contributed skills\", not a failure: every\n\t// tool-registry change rebuilds the system prompt, so propagating the error\n\t// turned each rebuild into an error-level plugin.log record. Any other\n\t// failure still propagates.\n\tlet contributed: ReturnType<typeof runtime.listContributions>;\n\ttry {\n\t\tcontributed = runtime.listContributions(SKILL_CONTRIBUTION_POINT_ID, SKILL_CONTRIBUTION_POINT_VERSION);\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !error.message.startsWith(\"Contribution point is not defined\")) throw error;\n\t\treturn [];\n\t}\n\tconst contributedSkills = contributed\n\t\t.filter(\n\t\t\t(entry): entry is typeof entry & { value: Skill } =>\n\t\t\t\tentry.value !== null && typeof entry.value === \"object\" && \"name\" in entry.value,\n\t\t)\n\t\t.map((entry) => ({\n\t\t\t...entry.value,\n\t\t\tdisableModelInvocation: entry.value.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<contribution:${entry.owner}:${entry.id}>`, {\n\t\t\t\tsource: entry.owner,\n\t\t\t\tbaseDir: entry.value.baseDir,\n\t\t\t}),\n\t\t}));\n\tconst contributedNames = new Set(contributedSkills.map((skill) => skill.name));\n\tconst legacyFilter = session._capabilitySkillsFilter;\n\tconst legacy = runtime\n\t\t.listSkills()\n\t\t.filter(({ definition }) => !contributedNames.has(definition.name))\n\t\t.map(({ definition, source }) => ({\n\t\t\t...definition,\n\t\t\tdisableModelInvocation: definition.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<plugin:${source}:${definition.name}>`, {\n\t\t\t\tsource,\n\t\t\t\tbaseDir: definition.baseDir,\n\t\t\t}),\n\t\t}))\n\t\t// Suite association filtering (方案系统 M3): the assembler owns the\n\t\t// policy; the session only applies the injected function. The\n\t\t// bootstrap-skills contribution face is already loader-filtered and\n\t\t// must not be filtered twice.\n\t\t.filter((skill) => (legacyFilter ? legacyFilter([skill]).length > 0 : true));\n\treturn [...contributedSkills, ...legacy].sort(\n\t\t(left, right) => left.name.localeCompare(right.name) || left.sourceInfo.path.localeCompare(right.sourceInfo.path),\n\t);\n}\n\nexport function validateCapabilitySkillConflicts(session: AgentSessionInternals): void {\n\tconst resourceNames = new Set<string>();\n\tconst resourceFilePaths = new Set<string>();\n\tfor (const skill of session._resourceLoader.getSkills().skills) {\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill is duplicated in resources: {name}\", { name: skill.name }));\n\t\tresourceNames.add(skill.name);\n\t\tresourceFilePaths.add(skill.filePath);\n\t}\n\tfor (const skill of session._getCapabilitySkills()) {\n\t\t// bootstrap-skills mirrors the same on-disk SKILL.md into the capability\n\t\t// layer: same name AND same file is one skill seen through two channels,\n\t\t// not a conflict. Same name from a different file (e.g. an MCP server\n\t\t// contributing a skill that collides with a disk skill) is a real one.\n\t\tif (typeof skill.filePath === \"string\" && resourceFilePaths.has(skill.filePath)) continue;\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill conflicts with a resource skill: {name}\", { name: skill.name }));\n\t}\n}\n\nexport async function refreshBootstrapSkills(session: AgentSessionInternals): Promise<void> {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return;\n\tsession._validateCapabilitySkillConflicts();\n\tif (session._bootstrapSkillsHandle) {\n\t\tawait refreshSessionBootstrapSkills(runtime, session._resourceLoader.getSkills().skills);\n\t} else {\n\t\tsession._bootstrapSkillsHandle = installSessionBootstrapSkills(\n\t\t\truntime,\n\t\t\tsession._resourceLoader.getSkills().skills,\n\t\t);\n\t}\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(session.getActiveToolNames());\n\tsession.agent.state.systemPrompt = session._baseSystemPrompt;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-tools.js","sourceRoot":"","sources":["../../src/core/agent-session-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EACN,6BAA6B,EAC7B,6BAA6B,EAC7B,2BAA2B,EAC3B,gCAAgC,GAChC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,CAAC,EAAE,MAAM,iBAAiB,CAAC;AAEpC,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAEvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAExE,MAAM,UAAU,sBAAsB,CAAC,IAAwB,EAAsB;IACpF,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,MAAM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E,CAAC;IAC5C,IAAI,OAAO,CAAC,sBAAsB,EAAE,CAAC;QACpC,MAAM,6BAA6B,CAAC,OAAO,EAAE,OAAO,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,CAAC;IAC1F,CAAC;SAAM,CAAC;QACP,OAAO,CAAC,sBAAsB,GAAG,6BAA6B,CAC7D,OAAO,EACP,OAAO,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,MAAM,CAC1C,CAAC;IACH,CAAC;IACD,OAAO,CAAC,iBAAiB,GAAG,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAAC;IACvF,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,GAAG,OAAO,CAAC,iBAAiB,CAAC;AAAA,CAC7D","sourcesContent":["/**\n * Tool registry, capability skills, and system-prompt assembly for\n * AgentSession.\n *\n * Extracted from `agent-session.ts`. Every function here operates on the\n * internal session facade ({@link AgentSessionInternals}); `AgentSession`\n * keeps same-name delegates so call sites, dynamic dispatch, and test spies\n * keep working unchanged.\n */\n\nimport type { AgentTool } from \"@agent-forge/agent-core\";\nimport type { AgentSessionInternals, ToolDefinitionEntry } from \"./agent-session-internal.ts\";\nimport {\n\tinstallSessionBootstrapSkills,\n\trefreshSessionBootstrapSkills,\n\tSKILL_CONTRIBUTION_POINT_ID,\n\tSKILL_CONTRIBUTION_POINT_VERSION,\n} from \"./extensions/index.ts\";\nimport { t } from \"./i18n/index.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { createSyntheticSourceInfo } from \"./source-info.ts\";\nimport { buildSystemPrompt } from \"./system-prompt.ts\";\nimport type { ToolDefinition, ToolExecuteContext, ToolInfo } from \"./tools/tool-definition.ts\";\nimport { wrapToolDefinition } from \"./tools/tool-definition-wrapper.ts\";\n\nexport function normalizePromptSnippet(text: string | undefined): string | undefined {\n\tif (!text) return undefined;\n\tconst oneLine = text\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn oneLine.length > 0 ? oneLine : undefined;\n}\n\nexport function normalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\tif (!guidelines || guidelines.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst unique = new Set<string>();\n\tfor (const guideline of guidelines) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\tunique.add(normalized);\n\t\t}\n\t}\n\treturn Array.from(unique);\n}\n\n/**\n * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.\n */\nexport function getAllTools(session: AgentSessionInternals): ToolInfo[] {\n\treturn Array.from(session._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t\tsourceInfo,\n\t}));\n}\n\nexport function getToolDefinition(session: AgentSessionInternals, name: string): ToolDefinition | undefined {\n\treturn session._toolDefinitions.get(name)?.definition;\n}\n\n/**\n * Set active tools by name.\n * Only tools in the registry can be enabled. Unknown tool names are ignored.\n * Also rebuilds the system prompt to reflect the new tool set.\n * Changes take effect on the next agent turn.\n */\nexport function setActiveToolsByName(session: AgentSessionInternals, toolNames: string[]): void {\n\tconst tools: AgentTool[] = [];\n\tconst validToolNames: string[] = [];\n\tfor (const name of toolNames) {\n\t\tconst tool = session._toolRegistry.get(name);\n\t\tif (tool) {\n\t\t\ttools.push(tool);\n\t\t\tvalidToolNames.push(name);\n\t\t}\n\t}\n\tsession.agent.state.tools = tools;\n\n\t// Rebuild base system prompt with new tool set\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(validToolNames);\n\tsession.agent.state.systemPrompt = session._systemPromptOverride ?? session._baseSystemPrompt;\n}\n\nexport function rebuildSystemPrompt(session: AgentSessionInternals, toolNames: string[]): string {\n\tconst validToolNames = toolNames.filter((name) => session._toolRegistry.has(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tconst promptGuidelines: string[] = [];\n\tfor (const name of validToolNames) {\n\t\tconst snippet = session._toolPromptSnippets.get(name);\n\t\tif (snippet) {\n\t\t\ttoolSnippets[name] = snippet;\n\t\t}\n\n\t\tconst toolGuidelines = session._toolPromptGuidelines.get(name);\n\t\tif (toolGuidelines) {\n\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t}\n\t}\n\n\tconst loaderSystemPrompt = session._resourceLoader.getSystemPrompt();\n\tconst loaderAppendSystemPrompt = session._resourceLoader.getAppendSystemPrompt();\n\tconst appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join(\"\\n\\n\") : undefined;\n\tconst loadedSkills = session._getAvailableSkills();\n\tconst loadedContextFiles = session._resourceLoader.getAgentsFiles().agentsFiles;\n\n\tsession._baseSystemPromptOptions = {\n\t\tcwd: session._cwd,\n\t\tskills: loadedSkills,\n\t\tcontextFiles: loadedContextFiles,\n\t\tcustomPrompt: loaderSystemPrompt,\n\t\torientationPrompt: session._orientationPrompt,\n\t\tpreferenceCard: session._preferenceCard,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t};\n\treturn buildSystemPrompt(session._baseSystemPromptOptions);\n}\n\nexport function refreshToolRegistry(\n\tsession: AgentSessionInternals,\n\toptions?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean },\n): void {\n\tconst previousRegistryNames = new Set(session._toolRegistry.keys());\n\tconst previousActiveToolNames = session.getActiveToolNames();\n\tconst allowedToolNames = session._allowedToolNames;\n\tconst excludedToolNames = session._excludedToolNames;\n\tconst isAllowedTool = (name: string): boolean =>\n\t\t(!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);\n\n\tconst allCustomTools = session._customTools\n\t\t.map((definition) => ({\n\t\t\tdefinition,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: \"sdk\" }),\n\t\t}))\n\t\t.filter((tool) => isAllowedTool(tool.definition.name));\n\tconst definitionRegistry = new Map<string, ToolDefinitionEntry>(\n\t\tArray.from(session._baseToolDefinitions.entries())\n\t\t\t.filter(([name]) => isAllowedTool(name))\n\t\t\t.map(([name, definition]) => [\n\t\t\t\tname,\n\t\t\t\t{\n\t\t\t\t\tdefinition,\n\t\t\t\t\t// syncCapabilityTools populates _baseToolSources in lockstep with\n\t\t\t\t\t// _baseToolDefinitions, so this fallback is a desync guard only;\n\t\t\t\t\t// the default coding tools surface rides the coding-tools package\n\t\t\t\t\t// id since D-082 批 1.\n\t\t\t\t\tsourceInfo:\n\t\t\t\t\t\tsession._baseToolSources.get(name) ??\n\t\t\t\t\t\tcreateSyntheticSourceInfo(`<bootstrap:${name}>`, { source: \"agent-forge.plugin.coding-tools\" }),\n\t\t\t\t},\n\t\t\t]),\n\t);\n\tfor (const tool of allCustomTools) {\n\t\tdefinitionRegistry.set(tool.definition.name, {\n\t\t\tdefinition: tool.definition,\n\t\t\tsourceInfo: tool.sourceInfo,\n\t\t});\n\t}\n\tsession._toolDefinitions = definitionRegistry;\n\tsession._toolPromptSnippets = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst snippet = normalizePromptSnippet(definition.promptSnippet);\n\t\t\t\treturn snippet ? ([definition.name, snippet] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string] => entry !== undefined),\n\t);\n\tsession._toolPromptGuidelines = new Map(\n\t\tArray.from(definitionRegistry.values())\n\t\t\t.map(({ definition }) => {\n\t\t\t\tconst guidelines = normalizePromptGuidelines(definition.promptGuidelines);\n\t\t\t\treturn guidelines.length > 0 ? ([definition.name, guidelines] as const) : undefined;\n\t\t\t})\n\t\t\t.filter((entry): entry is readonly [string, string[]] => entry !== undefined),\n\t);\n\t// Session-resolved execute context and dynamic-tool tracking replace the\n\t// former runner-mediated wrapper: tools receive the same session facts and\n\t// a tool that activates more tools during execute still surfaces them via\n\t// addedToolNames.\n\tconst executeContext = (): ToolExecuteContext => ({\n\t\tcwd: session.sessionManager.getCwd(),\n\t\tmodel: session.model,\n\t\tsessionManager: session.sessionManager,\n\t\tthinkingLevel: session.thinkingLevel,\n\t});\n\tconst wrapWithDynamicToolTracking = ({ definition }: { definition: ToolDefinition }): AgentTool => {\n\t\tconst tool = wrapToolDefinition(definition, executeContext);\n\t\tconst execute = tool.execute;\n\t\treturn {\n\t\t\t...tool,\n\t\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\t\tconst activeBefore = session.getActiveToolNames();\n\t\t\t\tconst result = await execute(toolCallId, params, signal, onUpdate);\n\t\t\t\tconst activeAfter = session.getActiveToolNames();\n\t\t\t\tif (!activeBefore.every((name) => activeAfter.includes(name))) return result;\n\n\t\t\t\tconst beforeNames = new Set(activeBefore);\n\t\t\t\tconst addedToolNames = activeAfter.filter((name) => !beforeNames.has(name));\n\t\t\t\tif (addedToolNames.length === 0) return result;\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\taddedToolNames: [...new Set([...(result.addedToolNames ?? []), ...addedToolNames])],\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t};\n\tconst wrappedExtensionTools = allCustomTools.map(wrapWithDynamicToolTracking);\n\tconst wrappedBuiltInTools = Array.from(session._baseToolDefinitions.values())\n\t\t.filter((definition) => isAllowedTool(definition.name))\n\t\t.map((definition) => wrapWithDynamicToolTracking({ definition }));\n\n\tconst toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));\n\tfor (const tool of wrappedExtensionTools as AgentTool[]) {\n\t\ttoolRegistry.set(tool.name, tool);\n\t}\n\tsession._toolRegistry = toolRegistry;\n\n\tconst nextActiveToolNames = (\n\t\toptions?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]\n\t).filter((name) => isAllowedTool(name));\n\n\tif (allowedToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (allowedToolNames.has(toolName)) {\n\t\t\t\tnextActiveToolNames.push(toolName);\n\t\t\t}\n\t\t}\n\t} else if (options?.includeAllExtensionTools) {\n\t\tfor (const tool of wrappedExtensionTools) {\n\t\t\tnextActiveToolNames.push(tool.name);\n\t\t}\n\t} else if (!options?.activeToolNames) {\n\t\tfor (const toolName of session._toolRegistry.keys()) {\n\t\t\tif (previousRegistryNames.has(toolName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Deferred tools (e.g. MCP servers configured with deferredTools)\n\t\t\t// register but stay out of the default active set until tool_search\n\t\t\t// or an explicit activation names them.\n\t\t\tif (session._deferredToolPluginIds.has(session._baseToolSources.get(toolName)?.source ?? \"\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnextActiveToolNames.push(toolName);\n\t\t}\n\t}\n\n\tsession.setActiveToolsByName([...new Set(nextActiveToolNames)]);\n}\n\nexport function syncCapabilityTools(session: AgentSessionInternals): void {\n\tconst tools = session._capabilityRuntime?.listTools() ?? [];\n\tsession._baseToolDefinitions = new Map(tools.map(({ name, definition }) => [name, definition as ToolDefinition]));\n\tsession._baseToolSources = new Map(\n\t\ttools.map(({ name, source }) => [name, createSyntheticSourceInfo(`<plugin:${source}:${name}>`, { source })]),\n\t);\n}\n\nexport function getCapabilitySkills(session: AgentSessionInternals): Skill[] {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return [];\n\t// The skill contribution point is owned by the bootstrap-skills plugin. In\n\t// hosts that never install it (assistant suite, print mode) — or while that\n\t// owner is inactive — `listContributions` throws \"Contribution point is not\n\t// defined\". That state means \"no contributed skills\", not a failure: every\n\t// tool-registry change rebuilds the system prompt, so propagating the error\n\t// turned each rebuild into an error-level plugin.log record. Any other\n\t// failure still propagates.\n\tlet contributed: ReturnType<typeof runtime.listContributions>;\n\ttry {\n\t\tcontributed = runtime.listContributions(SKILL_CONTRIBUTION_POINT_ID, SKILL_CONTRIBUTION_POINT_VERSION);\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !error.message.startsWith(\"Contribution point is not defined\")) throw error;\n\t\treturn [];\n\t}\n\tconst contributedSkills = contributed\n\t\t.filter(\n\t\t\t(entry): entry is typeof entry & { value: Skill } =>\n\t\t\t\tentry.value !== null && typeof entry.value === \"object\" && \"name\" in entry.value,\n\t\t)\n\t\t.map((entry) => ({\n\t\t\t...entry.value,\n\t\t\tdisableModelInvocation: entry.value.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<contribution:${entry.owner}:${entry.id}>`, {\n\t\t\t\tsource: entry.owner,\n\t\t\t\tbaseDir: entry.value.baseDir,\n\t\t\t}),\n\t\t}));\n\tconst contributedNames = new Set(contributedSkills.map((skill) => skill.name));\n\tconst legacyFilter = session._capabilitySkillsFilter;\n\tconst legacy = runtime\n\t\t.listSkills()\n\t\t.filter(({ definition }) => !contributedNames.has(definition.name))\n\t\t.map(({ definition, source }) => ({\n\t\t\t...definition,\n\t\t\tdisableModelInvocation: definition.disableModelInvocation === true,\n\t\t\tsourceInfo: createSyntheticSourceInfo(`<plugin:${source}:${definition.name}>`, {\n\t\t\t\tsource,\n\t\t\t\tbaseDir: definition.baseDir,\n\t\t\t}),\n\t\t}))\n\t\t// Suite association filtering (方案系统 M3): the assembler owns the\n\t\t// policy; the session only applies the injected function. The\n\t\t// bootstrap-skills contribution face is already loader-filtered and\n\t\t// must not be filtered twice.\n\t\t.filter((skill) => (legacyFilter ? legacyFilter([skill]).length > 0 : true));\n\treturn [...contributedSkills, ...legacy].sort(\n\t\t(left, right) => left.name.localeCompare(right.name) || left.sourceInfo.path.localeCompare(right.sourceInfo.path),\n\t);\n}\n\nexport function validateCapabilitySkillConflicts(session: AgentSessionInternals): void {\n\tconst resourceNames = new Set<string>();\n\tconst resourceFilePaths = new Set<string>();\n\tfor (const skill of session._resourceLoader.getSkills().skills) {\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill is duplicated in resources: {name}\", { name: skill.name }));\n\t\tresourceNames.add(skill.name);\n\t\tresourceFilePaths.add(skill.filePath);\n\t}\n\tfor (const skill of session._getCapabilitySkills()) {\n\t\t// bootstrap-skills mirrors the same on-disk SKILL.md into the capability\n\t\t// layer: same name AND same file is one skill seen through two channels,\n\t\t// not a conflict. Same name from a different file (e.g. an MCP server\n\t\t// contributing a skill that collides with a disk skill) is a real one.\n\t\tif (typeof skill.filePath === \"string\" && resourceFilePaths.has(skill.filePath)) continue;\n\t\tif (resourceNames.has(skill.name))\n\t\t\tthrow new Error(t(\"Skill conflicts with a resource skill: {name}\", { name: skill.name }));\n\t}\n}\n\nexport async function refreshBootstrapSkills(session: AgentSessionInternals): Promise<void> {\n\tconst runtime = session._capabilityRuntime;\n\tif (!runtime) return;\n\tsession._validateCapabilitySkillConflicts();\n\tif (session._bootstrapSkillsHandle) {\n\t\tawait refreshSessionBootstrapSkills(runtime, session._resourceLoader.getSkills().skills);\n\t} else {\n\t\tsession._bootstrapSkillsHandle = installSessionBootstrapSkills(\n\t\t\truntime,\n\t\t\tsession._resourceLoader.getSkills().skills,\n\t\t);\n\t}\n\tsession._baseSystemPrompt = session._rebuildSystemPrompt(session.getActiveToolNames());\n\tsession.agent.state.systemPrompt = session._baseSystemPrompt;\n}\n"]}
|