@ashx-j/lunr-dev 0.2.16-dev.9.1 → 0.2.19-dev.10.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 +32 -1
- package/README.md +7 -1
- package/dist/builtin-extensions/ashxj-thinking.d.ts +1 -0
- package/dist/builtin-extensions/ashxj-thinking.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-thinking.js +44 -19
- package/dist/builtin-extensions/ashxj-thinking.js.map +1 -1
- package/dist/builtin-extensions/index.d.ts.map +1 -1
- package/dist/builtin-extensions/index.js +1 -0
- package/dist/builtin-extensions/index.js.map +1 -1
- package/dist/builtin-extensions/lunr-computer-use.d.ts +3 -0
- package/dist/builtin-extensions/lunr-computer-use.d.ts.map +1 -0
- package/dist/builtin-extensions/lunr-computer-use.js +157 -0
- package/dist/builtin-extensions/lunr-computer-use.js.map +1 -0
- package/dist/builtin-extensions/pi-lsp-extension/src/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-lsp-extension/src/index.js +10 -3
- package/dist/builtin-extensions/pi-lsp-extension/src/index.js.map +1 -1
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts +5 -1
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js +26 -4
- package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.js +37 -27
- package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.d.ts +6 -1
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.js +33 -8
- package/dist/builtin-extensions/pi-mcp-adapter/server-manager.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js +52 -23
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +6 -2
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js +5 -2
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.d.ts +10 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.js +38 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.js.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +3 -16
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +1 -0
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js +70 -30
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
- package/dist/builtin-extensions/pi-web-access/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-web-access/index.js +103 -102
- package/dist/builtin-extensions/pi-web-access/index.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -1
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/computer-use/adapter.d.ts +23 -0
- package/dist/core/computer-use/adapter.d.ts.map +1 -0
- package/dist/core/computer-use/adapter.js +116 -0
- package/dist/core/computer-use/adapter.js.map +1 -0
- package/dist/core/computer-use/lease.d.ts +18 -0
- package/dist/core/computer-use/lease.d.ts.map +1 -0
- package/dist/core/computer-use/lease.js +129 -0
- package/dist/core/computer-use/lease.js.map +1 -0
- package/dist/core/computer-use/macos-runtime.d.ts +14 -0
- package/dist/core/computer-use/macos-runtime.d.ts.map +1 -0
- package/dist/core/computer-use/macos-runtime.js +148 -0
- package/dist/core/computer-use/macos-runtime.js.map +1 -0
- package/dist/core/computer-use/policy.d.ts +19 -0
- package/dist/core/computer-use/policy.d.ts.map +1 -0
- package/dist/core/computer-use/policy.js +66 -0
- package/dist/core/computer-use/policy.js.map +1 -0
- package/dist/core/computer-use/release.generated.d.ts +31 -0
- package/dist/core/computer-use/release.generated.d.ts.map +1 -0
- package/dist/core/computer-use/release.generated.js +36 -0
- package/dist/core/computer-use/release.generated.js.map +1 -0
- package/dist/core/computer-use/runtime.d.ts +13 -0
- package/dist/core/computer-use/runtime.d.ts.map +1 -0
- package/dist/core/computer-use/runtime.js +158 -0
- package/dist/core/computer-use/runtime.js.map +1 -0
- package/dist/core/computer-use/schemas.d.ts +88 -0
- package/dist/core/computer-use/schemas.d.ts.map +1 -0
- package/dist/core/computer-use/schemas.js +80 -0
- package/dist/core/computer-use/schemas.js.map +1 -0
- package/dist/core/computer-use/windows-desktop.d.ts +3 -0
- package/dist/core/computer-use/windows-desktop.d.ts.map +1 -0
- package/dist/core/computer-use/windows-desktop.js +48 -0
- package/dist/core/computer-use/windows-desktop.js.map +1 -0
- package/dist/core/computer-use/workflow.d.ts +24 -0
- package/dist/core/computer-use/workflow.d.ts.map +1 -0
- package/dist/core/computer-use/workflow.js +330 -0
- package/dist/core/computer-use/workflow.js.map +1 -0
- package/dist/core/keybindings.d.ts +2 -2
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +2 -2
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-runtime.d.ts +0 -3
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +1 -10
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +1 -1
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/permissions.d.ts +1 -1
- package/dist/core/permissions.d.ts.map +1 -1
- package/dist/core/permissions.js +23 -7
- package/dist/core/permissions.js.map +1 -1
- package/dist/core/plan-mode.d.ts.map +1 -1
- package/dist/core/plan-mode.js +9 -0
- package/dist/core/plan-mode.js.map +1 -1
- package/dist/core/rollback.d.ts.map +1 -1
- package/dist/core/rollback.js +13 -90
- package/dist/core/rollback.js.map +1 -1
- package/dist/core/session-manager.d.ts +0 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +21 -79
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +6 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +19 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/dev-cli.js +0 -0
- package/dist/gateway/agent-bridge.d.ts +6 -1
- package/dist/gateway/agent-bridge.d.ts.map +1 -1
- package/dist/gateway/agent-bridge.js +23 -6
- package/dist/gateway/agent-bridge.js.map +1 -1
- package/dist/gateway/cron.d.ts +1 -1
- package/dist/gateway/cron.d.ts.map +1 -1
- package/dist/gateway/cron.js +23 -7
- package/dist/gateway/cron.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +4 -2
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +23 -32
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/processes-selector.d.ts +2 -3
- package/dist/modes/interactive/components/processes-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/processes-selector.js +5 -10
- package/dist/modes/interactive/components/processes-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +20 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +18 -8
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/thinking-level-slash.d.ts +4 -0
- package/dist/modes/interactive/thinking-level-slash.d.ts.map +1 -0
- package/dist/modes/interactive/thinking-level-slash.js +23 -0
- package/dist/modes/interactive/thinking-level-slash.js.map +1 -0
- package/dist/node-runtime/adapter-AZMY335J.js +279 -0
- package/dist/node-runtime/{agent-session-services-IFJMSX7Z.js → agent-session-services-RSGP5GDN.js} +15 -12
- package/dist/node-runtime/{builtin-extensions-LYZ3BFWQ.js → builtin-extensions-7STLFW3A.js} +4 -3
- package/dist/node-runtime/chunk-2IDTZAG5.js +1415 -0
- package/dist/node-runtime/{chunk-7NBZ5P7I.js → chunk-4SJWFTUP.js} +1 -1
- package/dist/node-runtime/{chunk-AJX357CL.js → chunk-5NWQCSKR.js} +20 -1013
- package/dist/node-runtime/chunk-5OLJGVCB.js +68 -0
- package/dist/node-runtime/chunk-5Q45AVQG.js +108 -0
- package/dist/node-runtime/{chunk-TQNSPERU.js → chunk-5SQDLSZJ.js} +1 -1
- package/dist/node-runtime/{chunk-F4VQFJI2.js → chunk-6SPPH4FY.js} +4 -4
- package/dist/node-runtime/{chunk-PBC2Y6GS.js → chunk-6UB6NKA3.js} +29 -72
- package/dist/node-runtime/{chunk-A2KQXUJD.js → chunk-7AFOFSDY.js} +1 -1
- package/dist/node-runtime/chunk-BKAZ6BKX.js +2185 -0
- package/dist/node-runtime/{chunk-AHSTJBIB.js → chunk-EH2LJQPM.js} +4 -4
- package/dist/node-runtime/{chunk-N77MY65L.js → chunk-FLYMHKCS.js} +25 -25
- package/dist/node-runtime/{chunk-5P7PZMRU.js → chunk-HRS4HMDX.js} +1 -1
- package/dist/node-runtime/{chunk-IPA627GP.js → chunk-ISQDQIZN.js} +4 -4
- package/dist/node-runtime/{chunk-WJVFOIB5.js → chunk-J7QGQD45.js} +1 -1
- package/dist/node-runtime/{chunk-WOVTOV5P.js → chunk-JT6YCS5B.js} +29 -34
- package/dist/node-runtime/chunk-JZHEUQRL.js +180 -0
- package/dist/node-runtime/{chunk-ZKMFUD3Q.js → chunk-K72NVGUB.js} +3 -3
- package/dist/node-runtime/{chunk-ECD5L7YI.js → chunk-LCACDWHJ.js} +389 -15
- package/dist/node-runtime/{chunk-2QKLKMKC.js → chunk-LTXUQJI4.js} +1 -1
- package/dist/node-runtime/{chunk-MKKH27PH.js → chunk-LWJXTA6Z.js} +274 -2416
- package/dist/node-runtime/{chunk-EDBJNRSM.js → chunk-MGSB2C3M.js} +1 -1
- package/dist/node-runtime/{chunk-CDFZEWPU.js → chunk-MUMMMTW4.js} +6 -2
- package/dist/node-runtime/{chunk-YF63P5ZT.js → chunk-OTT6JMPU.js} +10 -67
- package/dist/node-runtime/{chunk-PGAJ5MO5.js → chunk-T5GM5BFH.js} +1 -1
- package/dist/node-runtime/{chunk-PCGNAY2O.js → chunk-TAP7QTUT.js} +38 -16
- package/dist/node-runtime/{chunk-4TLO4PO2.js → chunk-U6C7VTR5.js} +7 -1401
- package/dist/node-runtime/chunk-URD2SLIT.js +1019 -0
- package/dist/node-runtime/{chunk-QH42CDX3.js → chunk-W7S2REEG.js} +111 -84
- package/dist/node-runtime/{chunk-LZAW4ZX3.js → chunk-ZRDIMBEQ.js} +27 -9
- package/dist/node-runtime/{chunk-AD6VXAO7.js → chunk-ZSEZY3II.js} +5 -100
- package/dist/node-runtime/cli-runtime.js +1 -1
- package/dist/node-runtime/{command-L3LAHDIH.js → command-6UXQ6XZN.js} +1 -1
- package/dist/node-runtime/{commands-RL5YBW5I.js → commands-LGR5VT5X.js} +6 -4
- package/dist/node-runtime/{direct-tool-executor-JVDXTO7A.js → direct-tool-executor-TDJS7TBD.js} +9 -6
- package/dist/node-runtime/{export-html-KR26FOUZ.js → export-html-E4DT6ZJQ.js} +1 -1
- package/dist/node-runtime/{extract-XLQSJN4V.js → extract-IUCVZCWC.js} +2 -2
- package/dist/node-runtime/{gateway-X2TI5X7F.js → gateway-3OLC4GQN.js} +22 -367
- package/dist/node-runtime/{gemini-search-U7SUMPQA.js → gemini-search-NCIDF7NE.js} +1 -1
- package/dist/node-runtime/{gemini-url-context-PXWCBQHK.js → gemini-url-context-OKIN7AIP.js} +2 -2
- package/dist/node-runtime/image-resize-6ZPBFMWW.js +11 -0
- package/dist/node-runtime/index.js +53 -49
- package/dist/node-runtime/{init-NJV2T55N.js → init-EKE277AG.js} +6 -4
- package/dist/node-runtime/{interactive-mode-KOM35YF2.js → interactive-mode-S5M26CQ7.js} +20 -17
- package/dist/node-runtime/{interactive-view-U6OILKF3.js → interactive-view-N6F4KUIT.js} +3 -5
- package/dist/node-runtime/lunr-computer-use-4X3KUNF4.js +206 -0
- package/dist/node-runtime/{lunr-cron-YJ5UHYRD.js → lunr-cron-KKBOGAEF.js} +7 -1
- package/dist/node-runtime/main.js +24 -21
- package/dist/node-runtime/{mcp-auth-flow-QIXHW6QN.js → mcp-auth-flow-YL6RWPYG.js} +2 -1
- package/dist/node-runtime/{package-manager-cli-TZZHJCVI.js → package-manager-cli-C4EJOO5Q.js} +8 -6
- package/dist/node-runtime/{pi-mcp-adapter-QFB37AVN.js → pi-mcp-adapter-DPTJGAAL.js} +33 -27
- package/dist/node-runtime/{pi-subagents-7XJ4H53P.js → pi-subagents-VKCLYIBY.js} +103 -76
- package/dist/node-runtime/{pi-web-access-DPGAVKOA.js → pi-web-access-BV6DSZOP.js} +72 -69
- package/dist/node-runtime/{proxy-modes-HEEFK4KC.js → proxy-modes-R64LU6WZ.js} +12 -9
- package/dist/node-runtime/rpc-entry.js +24 -21
- package/dist/node-runtime/runtime-3SB5ATHQ.js +21 -0
- package/dist/node-runtime/{runtime-bridges-PPHNBFWL.js → runtime-bridges-UJ5WJJLN.js} +3 -3
- package/dist/node-runtime/{session-manager-MQNBYACL.js → session-manager-QEMZBMTM.js} +3 -5
- package/dist/node-runtime/{session-selector-5AZLJS6U.js → session-selector-URVJLOTK.js} +2 -2
- package/dist/node-runtime/{settings-manager-5LF2VQWC.js → settings-manager-K6IPIQTI.js} +3 -1
- package/dist/node-runtime/{src-Y7JSCK64.js → src-GPFAU3N6.js} +30 -10
- package/dist/node-runtime/{subagent-executor-5RNDEPIJ.js → subagent-executor-EFLTO32A.js} +39 -21
- package/dist/node-runtime/{update-cli-A253SZ7P.js → update-cli-I6OVDRPL.js} +3 -1
- package/dist/node-runtime/{video-extract-OYT5WKS5.js → video-extract-ETA5RA7U.js} +2 -2
- package/dist/node-runtime/workflow-SA34S4VX.js +325 -0
- package/dist/node-runtime/{youtube-extract-TQYKGFGS.js → youtube-extract-SRVGNN26.js} +2 -2
- package/dist/rpc.d.ts +3 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +18 -0
- package/dist/rpc.js.map +1 -0
- package/dist/startup/interactive-view.d.ts.map +1 -1
- package/dist/startup/interactive-view.js +1 -2
- package/dist/startup/interactive-view.js.map +1 -1
- package/docs/computer-use.md +277 -0
- package/docs/development.md +0 -32
- package/docs/features.md +2 -2
- package/docs/interactive-startup.md +10 -3
- package/docs/keybindings.md +2 -2
- package/docs/terminal-setup.md +1 -1
- package/docs/usage.md +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/hidden-thinking-label.ts +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/install-lock/package-lock.json +3827 -0
- package/install-lock/package.json +18 -0
- package/native/computer-use/LICENSE.md +21 -0
- package/npm-shrinkwrap.json +3808 -0
- package/package.json +16 -10
- package/dist/startup/interactive-shell.d.ts +0 -55
- package/dist/startup/interactive-shell.d.ts.map +0 -1
- package/dist/startup/interactive-shell.js +0 -264
- package/dist/startup/interactive-shell.js.map +0 -1
- package/dist/node-runtime/{chunk-YSKSB3BJ.js → chunk-CH6OL6P2.js} +2 -2
- package/dist/node-runtime/{chunk-VSELYKWU.js → chunk-EHMBW7FA.js} +3 -3
|
@@ -1,47 +1,22 @@
|
|
|
1
1
|
import { createRequire as __lunrRequire } from "node:module"; const require = __lunrRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
abortable,
|
|
4
|
-
computeServerHash,
|
|
5
|
-
extractToolUiStreamMode,
|
|
6
|
-
getMetadataCachePath,
|
|
7
|
-
getMissingConfiguredDirectToolServers,
|
|
8
|
-
interpolateEnvRecord,
|
|
9
|
-
isServerCacheValid,
|
|
10
|
-
loadMcpConfig,
|
|
11
|
-
loadMetadataCache,
|
|
12
|
-
openUrl,
|
|
13
|
-
parallelLimit,
|
|
14
|
-
reconstructToolMetadata,
|
|
15
|
-
resolveBearerToken,
|
|
16
|
-
resolveConfigPath,
|
|
17
|
-
saveMetadataCache,
|
|
18
|
-
serializeResources,
|
|
19
|
-
serializeTools,
|
|
20
|
-
throwIfAborted,
|
|
21
|
-
truncateAtWord
|
|
22
|
-
} from "./chunk-VSELYKWU.js";
|
|
23
2
|
import {
|
|
24
3
|
CallToolResultSchema,
|
|
25
4
|
CancelTaskRequestSchema,
|
|
26
5
|
CancelTaskResultSchema,
|
|
27
6
|
CancelledNotificationSchema,
|
|
28
7
|
CompleteResultSchema,
|
|
29
|
-
ContentBlockSchema,
|
|
30
8
|
CreateMessageRequestSchema,
|
|
31
9
|
CreateMessageResultSchema,
|
|
32
10
|
CreateMessageResultWithToolsSchema,
|
|
33
11
|
CreateTaskResultSchema,
|
|
34
12
|
ElicitRequestSchema,
|
|
35
13
|
ElicitResultSchema,
|
|
36
|
-
ElicitationCompleteNotificationSchema,
|
|
37
|
-
EmbeddedResourceSchema,
|
|
38
14
|
EmptyResultSchema,
|
|
39
15
|
ErrorCode,
|
|
40
16
|
GetPromptResultSchema,
|
|
41
17
|
GetTaskPayloadRequestSchema,
|
|
42
18
|
GetTaskRequestSchema,
|
|
43
19
|
GetTaskResultSchema,
|
|
44
|
-
ImplementationSchema,
|
|
45
20
|
InitializeResultSchema,
|
|
46
21
|
JSONRPCMessageSchema,
|
|
47
22
|
LATEST_PROTOCOL_VERSION,
|
|
@@ -53,54 +28,29 @@ import {
|
|
|
53
28
|
ListTasksResultSchema,
|
|
54
29
|
ListToolsResultSchema,
|
|
55
30
|
McpError,
|
|
56
|
-
McpOAuthProvider,
|
|
57
31
|
PingRequestSchema,
|
|
58
32
|
ProgressNotificationSchema,
|
|
59
33
|
PromptListChangedNotificationSchema,
|
|
60
34
|
RELATED_TASK_META_KEY,
|
|
61
35
|
ReadResourceResultSchema,
|
|
62
|
-
RequestIdSchema,
|
|
63
|
-
ResourceLinkSchema,
|
|
64
36
|
ResourceListChangedNotificationSchema,
|
|
65
37
|
SUPPORTED_PROTOCOL_VERSIONS,
|
|
66
|
-
StreamableHTTPClientTransport,
|
|
67
38
|
TaskStatusNotificationSchema,
|
|
68
39
|
ToolListChangedNotificationSchema,
|
|
69
|
-
ToolSchema,
|
|
70
|
-
UnauthorizedError,
|
|
71
|
-
UrlElicitationRequiredError,
|
|
72
|
-
auth,
|
|
73
|
-
createFetchWithInit,
|
|
74
|
-
createParser,
|
|
75
|
-
extractOAuthConfig,
|
|
76
|
-
extractWWWAuthenticateParams,
|
|
77
40
|
isJSONRPCErrorResponse,
|
|
78
41
|
isJSONRPCNotification,
|
|
79
42
|
isJSONRPCRequest,
|
|
80
43
|
isJSONRPCResultResponse,
|
|
81
|
-
isTaskAugmentedRequestParams
|
|
82
|
-
|
|
83
|
-
supportsOAuth
|
|
84
|
-
} from "./chunk-4TLO4PO2.js";
|
|
85
|
-
import {
|
|
86
|
-
getAgentPath
|
|
87
|
-
} from "./chunk-4HXHDDCF.js";
|
|
44
|
+
isTaskAugmentedRequestParams
|
|
45
|
+
} from "./chunk-2IDTZAG5.js";
|
|
88
46
|
import {
|
|
89
|
-
external_exports,
|
|
90
47
|
safeParse
|
|
91
48
|
} from "./chunk-BI3DHYCN.js";
|
|
92
|
-
import {
|
|
93
|
-
formatToolName,
|
|
94
|
-
isToolExcluded,
|
|
95
|
-
resourceNameToToolName,
|
|
96
|
-
serverStreamResultPatchNotificationSchema
|
|
97
|
-
} from "./chunk-ARC4KOTI.js";
|
|
98
49
|
import {
|
|
99
50
|
require_cross_spawn
|
|
100
51
|
} from "./chunk-Q4Q6D4IY.js";
|
|
101
52
|
import {
|
|
102
53
|
__commonJS,
|
|
103
|
-
__require,
|
|
104
54
|
__toESM
|
|
105
55
|
} from "./chunk-BRJX2PRC.js";
|
|
106
56
|
|
|
@@ -115,10 +65,10 @@ var require_code = __commonJS({
|
|
|
115
65
|
exports._CodeOrName = _CodeOrName;
|
|
116
66
|
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
|
|
117
67
|
var Name = class extends _CodeOrName {
|
|
118
|
-
constructor(
|
|
119
|
-
if (super(), !exports.IDENTIFIER.test(
|
|
68
|
+
constructor(s) {
|
|
69
|
+
if (super(), !exports.IDENTIFIER.test(s))
|
|
120
70
|
throw new Error("CodeGen: name must be a valid identifier");
|
|
121
|
-
this.str =
|
|
71
|
+
this.str = s;
|
|
122
72
|
}
|
|
123
73
|
toString() {
|
|
124
74
|
return this.str;
|
|
@@ -146,7 +96,7 @@ var require_code = __commonJS({
|
|
|
146
96
|
}
|
|
147
97
|
get str() {
|
|
148
98
|
var _a;
|
|
149
|
-
return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((
|
|
99
|
+
return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
|
|
150
100
|
}
|
|
151
101
|
get names() {
|
|
152
102
|
var _a;
|
|
@@ -156,17 +106,17 @@ var require_code = __commonJS({
|
|
|
156
106
|
exports._Code = _Code;
|
|
157
107
|
exports.nil = new _Code("");
|
|
158
108
|
function _(strs, ...args) {
|
|
159
|
-
let code = [strs[0]],
|
|
160
|
-
for (;
|
|
161
|
-
addCodeArg(code, args[
|
|
109
|
+
let code = [strs[0]], i = 0;
|
|
110
|
+
for (; i < args.length; )
|
|
111
|
+
addCodeArg(code, args[i]), code.push(strs[++i]);
|
|
162
112
|
return new _Code(code);
|
|
163
113
|
}
|
|
164
114
|
exports._ = _;
|
|
165
115
|
var plus = new _Code("+");
|
|
166
116
|
function str(strs, ...args) {
|
|
167
|
-
let expr = [safeStringify(strs[0])],
|
|
168
|
-
for (;
|
|
169
|
-
expr.push(plus), addCodeArg(expr, args[
|
|
117
|
+
let expr = [safeStringify(strs[0])], i = 0;
|
|
118
|
+
for (; i < args.length; )
|
|
119
|
+
expr.push(plus), addCodeArg(expr, args[i]), expr.push(plus, safeStringify(strs[++i]));
|
|
170
120
|
return optimize(expr), new _Code(expr);
|
|
171
121
|
}
|
|
172
122
|
exports.str = str;
|
|
@@ -175,42 +125,42 @@ var require_code = __commonJS({
|
|
|
175
125
|
}
|
|
176
126
|
exports.addCodeArg = addCodeArg;
|
|
177
127
|
function optimize(expr) {
|
|
178
|
-
let
|
|
179
|
-
for (;
|
|
180
|
-
if (expr[
|
|
181
|
-
let res = mergeExprItems(expr[
|
|
128
|
+
let i = 1;
|
|
129
|
+
for (; i < expr.length - 1; ) {
|
|
130
|
+
if (expr[i] === plus) {
|
|
131
|
+
let res = mergeExprItems(expr[i - 1], expr[i + 1]);
|
|
182
132
|
if (res !== void 0) {
|
|
183
|
-
expr.splice(
|
|
133
|
+
expr.splice(i - 1, 3, res);
|
|
184
134
|
continue;
|
|
185
135
|
}
|
|
186
|
-
expr[
|
|
136
|
+
expr[i++] = "+";
|
|
187
137
|
}
|
|
188
|
-
|
|
138
|
+
i++;
|
|
189
139
|
}
|
|
190
140
|
}
|
|
191
|
-
function mergeExprItems(
|
|
192
|
-
if (
|
|
193
|
-
return
|
|
194
|
-
if (
|
|
195
|
-
return
|
|
196
|
-
if (typeof
|
|
197
|
-
return
|
|
198
|
-
if (typeof
|
|
199
|
-
return `"${
|
|
141
|
+
function mergeExprItems(a, b) {
|
|
142
|
+
if (b === '""')
|
|
143
|
+
return a;
|
|
144
|
+
if (a === '""')
|
|
145
|
+
return b;
|
|
146
|
+
if (typeof a == "string")
|
|
147
|
+
return b instanceof Name || a[a.length - 1] !== '"' ? void 0 : typeof b != "string" ? `${a.slice(0, -1)}${b}"` : b[0] === '"' ? a.slice(0, -1) + b.slice(1) : void 0;
|
|
148
|
+
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
|
|
149
|
+
return `"${a}${b.slice(1)}`;
|
|
200
150
|
}
|
|
201
151
|
function strConcat(c1, c2) {
|
|
202
152
|
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
|
|
203
153
|
}
|
|
204
154
|
exports.strConcat = strConcat;
|
|
205
|
-
function interpolate(
|
|
206
|
-
return typeof
|
|
155
|
+
function interpolate(x) {
|
|
156
|
+
return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
|
|
207
157
|
}
|
|
208
|
-
function stringify(
|
|
209
|
-
return new _Code(safeStringify(
|
|
158
|
+
function stringify(x) {
|
|
159
|
+
return new _Code(safeStringify(x));
|
|
210
160
|
}
|
|
211
161
|
exports.stringify = stringify;
|
|
212
|
-
function safeStringify(
|
|
213
|
-
return JSON.stringify(
|
|
162
|
+
function safeStringify(x) {
|
|
163
|
+
return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
214
164
|
}
|
|
215
165
|
exports.safeStringify = safeStringify;
|
|
216
166
|
function getProperty(key) {
|
|
@@ -302,8 +252,8 @@ var require_scope = __commonJS({
|
|
|
302
252
|
} else
|
|
303
253
|
vs = this._values[prefix] = /* @__PURE__ */ new Map();
|
|
304
254
|
vs.set(valueKey, name);
|
|
305
|
-
let
|
|
306
|
-
return
|
|
255
|
+
let s = this._scope[prefix] || (this._scope[prefix] = []), itemIndex = s.length;
|
|
256
|
+
return s[itemIndex] = value.ref, name.setValue(value, { property: prefix, itemIndex }), name;
|
|
307
257
|
}
|
|
308
258
|
getValue(prefix, keyOrRef) {
|
|
309
259
|
let vs = this._values[prefix];
|
|
@@ -501,18 +451,18 @@ var require_codegen = __commonJS({
|
|
|
501
451
|
return this.nodes.reduce((code, n) => code + n.render(opts), "");
|
|
502
452
|
}
|
|
503
453
|
optimizeNodes() {
|
|
504
|
-
let { nodes } = this,
|
|
505
|
-
for (;
|
|
506
|
-
let n = nodes[
|
|
507
|
-
Array.isArray(n) ? nodes.splice(
|
|
454
|
+
let { nodes } = this, i = nodes.length;
|
|
455
|
+
for (; i--; ) {
|
|
456
|
+
let n = nodes[i].optimizeNodes();
|
|
457
|
+
Array.isArray(n) ? nodes.splice(i, 1, ...n) : n ? nodes[i] = n : nodes.splice(i, 1);
|
|
508
458
|
}
|
|
509
459
|
return nodes.length > 0 ? this : void 0;
|
|
510
460
|
}
|
|
511
461
|
optimizeNames(names, constants) {
|
|
512
|
-
let { nodes } = this,
|
|
513
|
-
for (;
|
|
514
|
-
let n = nodes[
|
|
515
|
-
n.optimizeNames(names, constants) || (subtractNames(names, n.names), nodes.splice(
|
|
462
|
+
let { nodes } = this, i = nodes.length;
|
|
463
|
+
for (; i--; ) {
|
|
464
|
+
let n = nodes[i];
|
|
465
|
+
n.optimizeNames(names, constants) || (subtractNames(names, n.names), nodes.splice(i, 1));
|
|
516
466
|
}
|
|
517
467
|
return nodes.length > 0 ? this : void 0;
|
|
518
468
|
}
|
|
@@ -540,13 +490,13 @@ var require_codegen = __commonJS({
|
|
|
540
490
|
let cond = this.condition;
|
|
541
491
|
if (cond === !0)
|
|
542
492
|
return this.nodes;
|
|
543
|
-
let
|
|
544
|
-
if (
|
|
545
|
-
let ns =
|
|
546
|
-
|
|
493
|
+
let e = this.else;
|
|
494
|
+
if (e) {
|
|
495
|
+
let ns = e.optimizeNodes();
|
|
496
|
+
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
|
|
547
497
|
}
|
|
548
|
-
if (
|
|
549
|
-
return cond === !1 ?
|
|
498
|
+
if (e)
|
|
499
|
+
return cond === !1 ? e instanceof _If ? e : e.nodes : this.nodes.length ? this : new _If(not(cond), e instanceof _If ? [e] : e.nodes);
|
|
550
500
|
if (!(cond === !1 || !this.nodes.length))
|
|
551
501
|
return this;
|
|
552
502
|
}
|
|
@@ -757,8 +707,8 @@ var require_codegen = __commonJS({
|
|
|
757
707
|
let name = this._scope.toName(nameOrPrefix);
|
|
758
708
|
if (this.opts.es5) {
|
|
759
709
|
let arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
|
|
760
|
-
return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (
|
|
761
|
-
this.var(name, (0, code_1._)`${arr}[${
|
|
710
|
+
return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => {
|
|
711
|
+
this.var(name, (0, code_1._)`${arr}[${i}]`), forBody(name);
|
|
762
712
|
});
|
|
763
713
|
}
|
|
764
714
|
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
|
|
@@ -880,16 +830,16 @@ var require_codegen = __commonJS({
|
|
|
880
830
|
let c = constants[n.str];
|
|
881
831
|
return c === void 0 || names[n.str] !== 1 ? n : (delete names[n.str], c);
|
|
882
832
|
}
|
|
883
|
-
function canOptimize(
|
|
884
|
-
return
|
|
833
|
+
function canOptimize(e) {
|
|
834
|
+
return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
|
|
885
835
|
}
|
|
886
836
|
}
|
|
887
837
|
function subtractNames(names, from) {
|
|
888
838
|
for (let n in from)
|
|
889
839
|
names[n] = (names[n] || 0) - (from[n] || 0);
|
|
890
840
|
}
|
|
891
|
-
function not(
|
|
892
|
-
return typeof
|
|
841
|
+
function not(x) {
|
|
842
|
+
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
|
|
893
843
|
}
|
|
894
844
|
exports.not = not;
|
|
895
845
|
var andCode = mappend(exports.operators.AND);
|
|
@@ -903,10 +853,10 @@ var require_codegen = __commonJS({
|
|
|
903
853
|
}
|
|
904
854
|
exports.or = or;
|
|
905
855
|
function mappend(op) {
|
|
906
|
-
return (
|
|
856
|
+
return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;
|
|
907
857
|
}
|
|
908
|
-
function par(
|
|
909
|
-
return
|
|
858
|
+
function par(x) {
|
|
859
|
+
return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
|
|
910
860
|
}
|
|
911
861
|
}
|
|
912
862
|
});
|
|
@@ -982,12 +932,12 @@ var require_util = __commonJS({
|
|
|
982
932
|
return str.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
983
933
|
}
|
|
984
934
|
exports.unescapeJsonPointer = unescapeJsonPointer;
|
|
985
|
-
function eachItem(xs,
|
|
935
|
+
function eachItem(xs, f) {
|
|
986
936
|
if (Array.isArray(xs))
|
|
987
|
-
for (let
|
|
988
|
-
|
|
937
|
+
for (let x of xs)
|
|
938
|
+
f(x);
|
|
989
939
|
else
|
|
990
|
-
|
|
940
|
+
f(xs);
|
|
991
941
|
}
|
|
992
942
|
exports.eachItem = eachItem;
|
|
993
943
|
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) {
|
|
@@ -1026,10 +976,10 @@ var require_util = __commonJS({
|
|
|
1026
976
|
}
|
|
1027
977
|
exports.setEvaluated = setEvaluated;
|
|
1028
978
|
var snippets = {};
|
|
1029
|
-
function useFunc(gen,
|
|
979
|
+
function useFunc(gen, f) {
|
|
1030
980
|
return gen.scopeValue("func", {
|
|
1031
|
-
ref:
|
|
1032
|
-
code: snippets[
|
|
981
|
+
ref: f,
|
|
982
|
+
code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))
|
|
1033
983
|
});
|
|
1034
984
|
}
|
|
1035
985
|
exports.useFunc = useFunc;
|
|
@@ -1125,8 +1075,8 @@ var require_errors = __commonJS({
|
|
|
1125
1075
|
if (errsCount === void 0)
|
|
1126
1076
|
throw new Error("ajv implementation error");
|
|
1127
1077
|
let err = gen.name("err");
|
|
1128
|
-
gen.forRange("i", errsCount, names_1.default.errors, (
|
|
1129
|
-
gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${
|
|
1078
|
+
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
|
|
1079
|
+
gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`), gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))), gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`), it.opts.verbose && (gen.assign((0, codegen_1._)`${err}.schema`, schemaValue), gen.assign((0, codegen_1._)`${err}.data`, data));
|
|
1130
1080
|
});
|
|
1131
1081
|
}
|
|
1132
1082
|
exports.extendErrors = extendErrors;
|
|
@@ -1216,8 +1166,8 @@ var require_rules = __commonJS({
|
|
|
1216
1166
|
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
1217
1167
|
exports.getRules = exports.isJSONType = void 0;
|
|
1218
1168
|
var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"], jsonTypes = new Set(_jsonTypes);
|
|
1219
|
-
function isJSONType(
|
|
1220
|
-
return typeof
|
|
1169
|
+
function isJSONType(x) {
|
|
1170
|
+
return typeof x == "string" && jsonTypes.has(x);
|
|
1221
1171
|
}
|
|
1222
1172
|
exports.isJSONType = isJSONType;
|
|
1223
1173
|
function getRules() {
|
|
@@ -1305,18 +1255,18 @@ var require_dataType = __commonJS({
|
|
|
1305
1255
|
exports.coerceAndCheckDataType = coerceAndCheckDataType;
|
|
1306
1256
|
var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
|
|
1307
1257
|
function coerceToTypes(types, coerceTypes) {
|
|
1308
|
-
return coerceTypes ? types.filter((
|
|
1258
|
+
return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];
|
|
1309
1259
|
}
|
|
1310
1260
|
function coerceData(it, types, coerceTo) {
|
|
1311
1261
|
let { gen, data, opts } = it, dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`), coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
|
|
1312
1262
|
opts.coerceTypes === "array" && gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))), gen.if((0, codegen_1._)`${coerced} !== undefined`);
|
|
1313
|
-
for (let
|
|
1314
|
-
(COERCIBLE.has(
|
|
1263
|
+
for (let t of coerceTo)
|
|
1264
|
+
(COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") && coerceSpecificType(t);
|
|
1315
1265
|
gen.else(), reportTypeError(it), gen.endIf(), gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
|
|
1316
1266
|
gen.assign(data, coerced), assignParentData(it, coerced);
|
|
1317
1267
|
});
|
|
1318
|
-
function coerceSpecificType(
|
|
1319
|
-
switch (
|
|
1268
|
+
function coerceSpecificType(t) {
|
|
1269
|
+
switch (t) {
|
|
1320
1270
|
case "string":
|
|
1321
1271
|
gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);
|
|
1322
1272
|
return;
|
|
@@ -1379,8 +1329,8 @@ var require_dataType = __commonJS({
|
|
|
1379
1329
|
} else
|
|
1380
1330
|
cond = codegen_1.nil;
|
|
1381
1331
|
types.number && delete types.integer;
|
|
1382
|
-
for (let
|
|
1383
|
-
cond = (0, codegen_1.and)(cond, checkDataType(
|
|
1332
|
+
for (let t in types)
|
|
1333
|
+
cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
|
|
1384
1334
|
return cond;
|
|
1385
1335
|
}
|
|
1386
1336
|
exports.checkDataTypes = checkDataTypes;
|
|
@@ -1422,7 +1372,7 @@ var require_defaults = __commonJS({
|
|
|
1422
1372
|
if (ty === "object" && properties)
|
|
1423
1373
|
for (let key in properties)
|
|
1424
1374
|
assignDefault(it, key, properties[key].default);
|
|
1425
|
-
else ty === "array" && Array.isArray(items) && items.forEach((sch,
|
|
1375
|
+
else ty === "array" && Array.isArray(items) && items.forEach((sch, i) => assignDefault(it, i, sch.default));
|
|
1426
1376
|
}
|
|
1427
1377
|
exports.assignDefaults = assignDefaults;
|
|
1428
1378
|
function assignDefault(it, prop, defaultValue) {
|
|
@@ -1506,11 +1456,11 @@ var require_code2 = __commonJS({
|
|
|
1506
1456
|
exports.callValidateCode = callValidateCode;
|
|
1507
1457
|
var newRegExp = (0, codegen_1._)`new RegExp`;
|
|
1508
1458
|
function usePattern({ gen, it: { opts } }, pattern) {
|
|
1509
|
-
let
|
|
1459
|
+
let u = opts.unicodeRegExp ? "u" : "", { regExp } = opts.code, rx = regExp(pattern, u);
|
|
1510
1460
|
return gen.scopeValue("pattern", {
|
|
1511
1461
|
key: rx.toString(),
|
|
1512
1462
|
ref: rx,
|
|
1513
|
-
code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${
|
|
1463
|
+
code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`
|
|
1514
1464
|
});
|
|
1515
1465
|
}
|
|
1516
1466
|
exports.usePattern = usePattern;
|
|
@@ -1523,10 +1473,10 @@ var require_code2 = __commonJS({
|
|
|
1523
1473
|
return gen.var(valid, !0), validateItems(() => gen.break()), valid;
|
|
1524
1474
|
function validateItems(notValid) {
|
|
1525
1475
|
let len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
1526
|
-
gen.forRange("i", 0, len, (
|
|
1476
|
+
gen.forRange("i", 0, len, (i) => {
|
|
1527
1477
|
cxt.subschema({
|
|
1528
1478
|
keyword,
|
|
1529
|
-
dataProp:
|
|
1479
|
+
dataProp: i,
|
|
1530
1480
|
dataPropType: util_1.Type.Num
|
|
1531
1481
|
}, valid), gen.if((0, codegen_1.not)(valid), notValid);
|
|
1532
1482
|
});
|
|
@@ -1540,10 +1490,10 @@ var require_code2 = __commonJS({
|
|
|
1540
1490
|
if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated)
|
|
1541
1491
|
return;
|
|
1542
1492
|
let valid = gen.let("valid", !1), schValid = gen.name("_valid");
|
|
1543
|
-
gen.block(() => schema.forEach((_sch,
|
|
1493
|
+
gen.block(() => schema.forEach((_sch, i) => {
|
|
1544
1494
|
let schCxt = cxt.subschema({
|
|
1545
1495
|
keyword,
|
|
1546
|
-
schemaProp:
|
|
1496
|
+
schemaProp: i,
|
|
1547
1497
|
compositeRule: !0
|
|
1548
1498
|
}, schValid);
|
|
1549
1499
|
gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`), cxt.mergeValidEvaluated(schCxt, schValid) || gen.if((0, codegen_1.not)(valid));
|
|
@@ -1589,7 +1539,7 @@ var require_keyword = __commonJS({
|
|
|
1589
1539
|
}
|
|
1590
1540
|
function validateAsync() {
|
|
1591
1541
|
let ruleErrs = gen.let("ruleErrs", null);
|
|
1592
|
-
return gen.try(() => assignValid((0, codegen_1._)`await `), (
|
|
1542
|
+
return gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, !1).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))), ruleErrs;
|
|
1593
1543
|
}
|
|
1594
1544
|
function validateSync() {
|
|
1595
1545
|
let validateErrs = (0, codegen_1._)`${validateRef}.errors`;
|
|
@@ -1710,30 +1660,30 @@ var require_subschema = __commonJS({
|
|
|
1710
1660
|
var require_fast_deep_equal = __commonJS({
|
|
1711
1661
|
"node_modules/fast-deep-equal/index.js"(exports, module) {
|
|
1712
1662
|
"use strict";
|
|
1713
|
-
module.exports = function equal(
|
|
1714
|
-
if (
|
|
1715
|
-
if (
|
|
1716
|
-
if (
|
|
1717
|
-
var length,
|
|
1718
|
-
if (Array.isArray(
|
|
1719
|
-
if (length =
|
|
1720
|
-
for (
|
|
1721
|
-
if (!equal(
|
|
1663
|
+
module.exports = function equal(a, b) {
|
|
1664
|
+
if (a === b) return !0;
|
|
1665
|
+
if (a && b && typeof a == "object" && typeof b == "object") {
|
|
1666
|
+
if (a.constructor !== b.constructor) return !1;
|
|
1667
|
+
var length, i, keys;
|
|
1668
|
+
if (Array.isArray(a)) {
|
|
1669
|
+
if (length = a.length, length != b.length) return !1;
|
|
1670
|
+
for (i = length; i-- !== 0; )
|
|
1671
|
+
if (!equal(a[i], b[i])) return !1;
|
|
1722
1672
|
return !0;
|
|
1723
1673
|
}
|
|
1724
|
-
if (
|
|
1725
|
-
if (
|
|
1726
|
-
if (
|
|
1727
|
-
if (keys = Object.keys(
|
|
1728
|
-
for (
|
|
1729
|
-
if (!Object.prototype.hasOwnProperty.call(
|
|
1730
|
-
for (
|
|
1731
|
-
var key = keys[
|
|
1732
|
-
if (!equal(
|
|
1674
|
+
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
|
|
1675
|
+
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
|
|
1676
|
+
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
|
|
1677
|
+
if (keys = Object.keys(a), length = keys.length, length !== Object.keys(b).length) return !1;
|
|
1678
|
+
for (i = length; i-- !== 0; )
|
|
1679
|
+
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return !1;
|
|
1680
|
+
for (i = length; i-- !== 0; ) {
|
|
1681
|
+
var key = keys[i];
|
|
1682
|
+
if (!equal(a[key], b[key])) return !1;
|
|
1733
1683
|
}
|
|
1734
1684
|
return !0;
|
|
1735
1685
|
}
|
|
1736
|
-
return
|
|
1686
|
+
return a !== a && b !== b;
|
|
1737
1687
|
};
|
|
1738
1688
|
}
|
|
1739
1689
|
});
|
|
@@ -1800,8 +1750,8 @@ var require_json_schema_traverse = __commonJS({
|
|
|
1800
1750
|
var sch = schema[key];
|
|
1801
1751
|
if (Array.isArray(sch)) {
|
|
1802
1752
|
if (key in traverse.arrayKeywords)
|
|
1803
|
-
for (var
|
|
1804
|
-
_traverse(opts, pre, post, sch[
|
|
1753
|
+
for (var i = 0; i < sch.length; i++)
|
|
1754
|
+
_traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
|
|
1805
1755
|
} else if (key in traverse.propsKeywords) {
|
|
1806
1756
|
if (sch && typeof sch == "object")
|
|
1807
1757
|
for (var prop in sch)
|
|
@@ -2069,8 +2019,8 @@ var require_validate = __commonJS({
|
|
|
2069
2019
|
it.dataTypes = types;
|
|
2070
2020
|
return;
|
|
2071
2021
|
}
|
|
2072
|
-
types.forEach((
|
|
2073
|
-
includesType(it.dataTypes,
|
|
2022
|
+
types.forEach((t) => {
|
|
2023
|
+
includesType(it.dataTypes, t) || strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
|
|
2074
2024
|
}), narrowSchemaTypes(it, types);
|
|
2075
2025
|
}
|
|
2076
2026
|
}
|
|
@@ -2083,20 +2033,20 @@ var require_validate = __commonJS({
|
|
|
2083
2033
|
let rule = rules[keyword];
|
|
2084
2034
|
if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
|
|
2085
2035
|
let { type } = rule.definition;
|
|
2086
|
-
type.length && !type.some((
|
|
2036
|
+
type.length && !type.some((t) => hasApplicableType(ts, t)) && strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
|
|
2087
2037
|
}
|
|
2088
2038
|
}
|
|
2089
2039
|
}
|
|
2090
2040
|
function hasApplicableType(schTs, kwdT) {
|
|
2091
2041
|
return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
|
|
2092
2042
|
}
|
|
2093
|
-
function includesType(ts,
|
|
2094
|
-
return ts.includes(
|
|
2043
|
+
function includesType(ts, t) {
|
|
2044
|
+
return ts.includes(t) || t === "integer" && ts.includes("number");
|
|
2095
2045
|
}
|
|
2096
2046
|
function narrowSchemaTypes(it, withTypes) {
|
|
2097
2047
|
let ts = [];
|
|
2098
|
-
for (let
|
|
2099
|
-
includesType(withTypes,
|
|
2048
|
+
for (let t of it.dataTypes)
|
|
2049
|
+
includesType(withTypes, t) ? ts.push(t) : withTypes.includes("integer") && t === "number" && ts.push("integer");
|
|
2100
2050
|
it.dataTypes = ts;
|
|
2101
2051
|
}
|
|
2102
2052
|
function strictTypesError(it, msg) {
|
|
@@ -2339,8 +2289,8 @@ var require_compile = __commonJS({
|
|
|
2339
2289
|
}, validate.source && (validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated));
|
|
2340
2290
|
}
|
|
2341
2291
|
return sch.validate = validate, sch;
|
|
2342
|
-
} catch (
|
|
2343
|
-
throw delete sch.validate, delete sch.validateName, sourceCode && this.logger.error("Error compiling schema, function code:", sourceCode),
|
|
2292
|
+
} catch (e) {
|
|
2293
|
+
throw delete sch.validate, delete sch.validateName, sourceCode && this.logger.error("Error compiling schema, function code:", sourceCode), e;
|
|
2344
2294
|
} finally {
|
|
2345
2295
|
this._compilations.delete(sch);
|
|
2346
2296
|
}
|
|
@@ -2352,7 +2302,7 @@ var require_compile = __commonJS({
|
|
|
2352
2302
|
let schOrFunc = root.refs[ref];
|
|
2353
2303
|
if (schOrFunc)
|
|
2354
2304
|
return schOrFunc;
|
|
2355
|
-
let _sch =
|
|
2305
|
+
let _sch = resolve.call(this, root, ref);
|
|
2356
2306
|
if (_sch === void 0) {
|
|
2357
2307
|
let schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref], { schemaId } = this.opts;
|
|
2358
2308
|
schema && (_sch = new SchemaEnv({ schema, schemaId, root, baseId }));
|
|
@@ -2373,7 +2323,7 @@ var require_compile = __commonJS({
|
|
|
2373
2323
|
function sameSchemaEnv(s1, s2) {
|
|
2374
2324
|
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
|
2375
2325
|
}
|
|
2376
|
-
function
|
|
2326
|
+
function resolve(root, ref) {
|
|
2377
2327
|
let sch;
|
|
2378
2328
|
for (; typeof (sch = this.refs[ref]) == "string"; )
|
|
2379
2329
|
ref = sch;
|
|
@@ -2455,18 +2405,18 @@ var require_utils = __commonJS({
|
|
|
2455
2405
|
"use strict";
|
|
2456
2406
|
var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu), isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u), isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu), isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu), isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);
|
|
2457
2407
|
function stringArrayToHexStripped(input) {
|
|
2458
|
-
let acc = "", code = 0,
|
|
2459
|
-
for (
|
|
2460
|
-
if (code = input[
|
|
2408
|
+
let acc = "", code = 0, i = 0;
|
|
2409
|
+
for (i = 0; i < input.length; i++)
|
|
2410
|
+
if (code = input[i].charCodeAt(0), code !== 48) {
|
|
2461
2411
|
if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102))
|
|
2462
2412
|
return "";
|
|
2463
|
-
acc += input[
|
|
2413
|
+
acc += input[i];
|
|
2464
2414
|
break;
|
|
2465
2415
|
}
|
|
2466
|
-
for (
|
|
2467
|
-
if (code = input[
|
|
2416
|
+
for (i += 1; i < input.length; i++) {
|
|
2417
|
+
if (code = input[i].charCodeAt(0), !(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102))
|
|
2468
2418
|
return "";
|
|
2469
|
-
acc += input[
|
|
2419
|
+
acc += input[i];
|
|
2470
2420
|
}
|
|
2471
2421
|
return acc;
|
|
2472
2422
|
}
|
|
@@ -2487,8 +2437,8 @@ var require_utils = __commonJS({
|
|
|
2487
2437
|
}
|
|
2488
2438
|
function getIPV6(input) {
|
|
2489
2439
|
let tokenCount = 0, output = { error: !1, address: "", zone: "" }, address = [], buffer = [], endipv6Encountered = !1, endIpv6 = !1, consume = consumeHextets;
|
|
2490
|
-
for (let
|
|
2491
|
-
let cursor = input[
|
|
2440
|
+
for (let i = 0; i < input.length; i++) {
|
|
2441
|
+
let cursor = input[i];
|
|
2492
2442
|
if (!(cursor === "[" || cursor === "]"))
|
|
2493
2443
|
if (cursor === ":") {
|
|
2494
2444
|
if (endipv6Encountered === !0 && (endIpv6 = !0), !consume(buffer, address, output))
|
|
@@ -2497,7 +2447,7 @@ var require_utils = __commonJS({
|
|
|
2497
2447
|
output.error = !0;
|
|
2498
2448
|
break;
|
|
2499
2449
|
}
|
|
2500
|
-
|
|
2450
|
+
i > 0 && input[i - 1] === ":" && (endipv6Encountered = !0), address.push(":");
|
|
2501
2451
|
continue;
|
|
2502
2452
|
} else if (cursor === "%") {
|
|
2503
2453
|
if (!consume(buffer, address, output))
|
|
@@ -2523,8 +2473,8 @@ var require_utils = __commonJS({
|
|
|
2523
2473
|
}
|
|
2524
2474
|
function findToken(str, token) {
|
|
2525
2475
|
let ind = 0;
|
|
2526
|
-
for (let
|
|
2527
|
-
str[
|
|
2476
|
+
for (let i = 0; i < str.length; i++)
|
|
2477
|
+
str[i] === token && ind++;
|
|
2528
2478
|
return ind;
|
|
2529
2479
|
}
|
|
2530
2480
|
function removeDotSegments(path) {
|
|
@@ -2592,45 +2542,45 @@ var require_utils = __commonJS({
|
|
|
2592
2542
|
if (input.indexOf("%") === -1)
|
|
2593
2543
|
return input;
|
|
2594
2544
|
let output = "";
|
|
2595
|
-
for (let
|
|
2596
|
-
if (input[
|
|
2597
|
-
let hex = input.slice(
|
|
2545
|
+
for (let i = 0; i < input.length; i++) {
|
|
2546
|
+
if (input[i] === "%" && i + 2 < input.length) {
|
|
2547
|
+
let hex = input.slice(i + 1, i + 3);
|
|
2598
2548
|
if (isHexPair(hex)) {
|
|
2599
2549
|
let normalizedHex = hex.toUpperCase(), decoded = String.fromCharCode(parseInt(normalizedHex, 16));
|
|
2600
|
-
decodeUnreserved && isUnreserved(decoded) ? output += decoded : output += "%" + normalizedHex,
|
|
2550
|
+
decodeUnreserved && isUnreserved(decoded) ? output += decoded : output += "%" + normalizedHex, i += 2;
|
|
2601
2551
|
continue;
|
|
2602
2552
|
}
|
|
2603
2553
|
}
|
|
2604
|
-
output += input[
|
|
2554
|
+
output += input[i];
|
|
2605
2555
|
}
|
|
2606
2556
|
return output;
|
|
2607
2557
|
}
|
|
2608
2558
|
function normalizePathEncoding(input) {
|
|
2609
2559
|
let output = "";
|
|
2610
|
-
for (let
|
|
2611
|
-
if (input[
|
|
2612
|
-
let hex = input.slice(
|
|
2560
|
+
for (let i = 0; i < input.length; i++) {
|
|
2561
|
+
if (input[i] === "%" && i + 2 < input.length) {
|
|
2562
|
+
let hex = input.slice(i + 1, i + 3);
|
|
2613
2563
|
if (isHexPair(hex)) {
|
|
2614
2564
|
let normalizedHex = hex.toUpperCase(), decoded = String.fromCharCode(parseInt(normalizedHex, 16));
|
|
2615
|
-
decoded !== "." && isUnreserved(decoded) ? output += decoded : output += "%" + normalizedHex,
|
|
2565
|
+
decoded !== "." && isUnreserved(decoded) ? output += decoded : output += "%" + normalizedHex, i += 2;
|
|
2616
2566
|
continue;
|
|
2617
2567
|
}
|
|
2618
2568
|
}
|
|
2619
|
-
isPathCharacter(input[
|
|
2569
|
+
isPathCharacter(input[i]) ? output += input[i] : output += escape(input[i]);
|
|
2620
2570
|
}
|
|
2621
2571
|
return output;
|
|
2622
2572
|
}
|
|
2623
2573
|
function escapePreservingEscapes(input) {
|
|
2624
2574
|
let output = "";
|
|
2625
|
-
for (let
|
|
2626
|
-
if (input[
|
|
2627
|
-
let hex = input.slice(
|
|
2575
|
+
for (let i = 0; i < input.length; i++) {
|
|
2576
|
+
if (input[i] === "%" && i + 2 < input.length) {
|
|
2577
|
+
let hex = input.slice(i + 1, i + 3);
|
|
2628
2578
|
if (isHexPair(hex)) {
|
|
2629
|
-
output += "%" + hex.toUpperCase(),
|
|
2579
|
+
output += "%" + hex.toUpperCase(), i += 2;
|
|
2630
2580
|
continue;
|
|
2631
2581
|
}
|
|
2632
2582
|
}
|
|
2633
|
-
output += escape(input[
|
|
2583
|
+
output += escape(input[i]);
|
|
2634
2584
|
}
|
|
2635
2585
|
return output;
|
|
2636
2586
|
}
|
|
@@ -2820,7 +2770,7 @@ var require_fast_uri = __commonJS({
|
|
|
2820
2770
|
normalizeString(uri, options) : typeof uri == "object" && (uri = /** @type {T} */
|
|
2821
2771
|
parse2(serialize(uri, options), options)), uri;
|
|
2822
2772
|
}
|
|
2823
|
-
function
|
|
2773
|
+
function resolve(baseURI, relativeURI, options) {
|
|
2824
2774
|
let schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }, resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, !0);
|
|
2825
2775
|
return schemelessOptions.skipEscape = !0, serialize(resolved, schemelessOptions);
|
|
2826
2776
|
}
|
|
@@ -2852,8 +2802,8 @@ var require_fast_uri = __commonJS({
|
|
|
2852
2802
|
schemeHandler && schemeHandler.serialize && schemeHandler.serialize(component, options), component.path !== void 0 && (options.skipEscape ? component.path = normalizePercentEncoding(component.path) : (component.path = escapePreservingEscapes(component.path), component.scheme !== void 0 && (component.path = component.path.split("%3A").join(":")))), options.reference !== "suffix" && component.scheme && uriTokens.push(component.scheme, ":");
|
|
2853
2803
|
let authority = recomposeAuthority(component);
|
|
2854
2804
|
if (authority !== void 0 && (options.reference !== "suffix" && uriTokens.push("//"), uriTokens.push(authority), component.path && component.path[0] !== "/" && uriTokens.push("/")), component.path !== void 0) {
|
|
2855
|
-
let
|
|
2856
|
-
!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath) && (
|
|
2805
|
+
let s = component.path;
|
|
2806
|
+
!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath) && (s = removeDotSegments(s)), authority === void 0 && s[0] === "/" && s[1] === "/" && (s = "/%2F" + s.slice(2)), uriTokens.push(s);
|
|
2857
2807
|
}
|
|
2858
2808
|
return component.query !== void 0 && uriTokens.push("?", component.query), component.fragment !== void 0 && uriTokens.push("#", component.fragment), uriTokens.join("");
|
|
2859
2809
|
}
|
|
@@ -2890,8 +2840,8 @@ var require_fast_uri = __commonJS({
|
|
|
2890
2840
|
if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === !1 && nonSimpleDomain(parsed.host))
|
|
2891
2841
|
try {
|
|
2892
2842
|
parsed.host = new URL("http://" + parsed.host).hostname;
|
|
2893
|
-
} catch (
|
|
2894
|
-
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " +
|
|
2843
|
+
} catch (e) {
|
|
2844
|
+
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
|
|
2895
2845
|
}
|
|
2896
2846
|
if ((!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) && (uri.indexOf("%") !== -1 && (parsed.scheme !== void 0 && (parsed.scheme = unescape(parsed.scheme)), parsed.host !== void 0 && (parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP))), parsed.path && (parsed.path = normalizePathEncoding(parsed.path)), parsed.fragment))
|
|
2897
2847
|
try {
|
|
@@ -2928,7 +2878,7 @@ var require_fast_uri = __commonJS({
|
|
|
2928
2878
|
var fastUri = {
|
|
2929
2879
|
SCHEMES,
|
|
2930
2880
|
normalize,
|
|
2931
|
-
resolve
|
|
2881
|
+
resolve,
|
|
2932
2882
|
resolveComponent,
|
|
2933
2883
|
equal,
|
|
2934
2884
|
serialize,
|
|
@@ -3017,27 +2967,27 @@ var require_core = __commonJS({
|
|
|
3017
2967
|
jsPropertySyntax: "",
|
|
3018
2968
|
unicode: '"minLength"/"maxLength" account for unicode characters by default.'
|
|
3019
2969
|
}, MAX_EXPRESSION = 200;
|
|
3020
|
-
function requiredOptions(
|
|
2970
|
+
function requiredOptions(o) {
|
|
3021
2971
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
|
|
3022
|
-
let
|
|
2972
|
+
let s = o.strict, _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize, optimize = _optz === !0 || _optz === void 0 ? 1 : _optz || 0, regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp, uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
|
|
3023
2973
|
return {
|
|
3024
|
-
strictSchema: (_f = (_e =
|
|
3025
|
-
strictNumbers: (_h = (_g =
|
|
3026
|
-
strictTypes: (_k = (_j =
|
|
3027
|
-
strictTuples: (_m = (_l =
|
|
3028
|
-
strictRequired: (_p = (_o =
|
|
3029
|
-
code:
|
|
3030
|
-
loopRequired: (_q =
|
|
3031
|
-
loopEnum: (_r =
|
|
3032
|
-
meta: (_s =
|
|
3033
|
-
messages: (_t =
|
|
3034
|
-
inlineRefs: (_u =
|
|
3035
|
-
schemaId: (_v =
|
|
3036
|
-
addUsedSchema: (_w =
|
|
3037
|
-
validateSchema: (_x =
|
|
3038
|
-
validateFormats: (_y =
|
|
3039
|
-
unicodeRegExp: (_z =
|
|
3040
|
-
int32range: (_0 =
|
|
2974
|
+
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : !0,
|
|
2975
|
+
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : !0,
|
|
2976
|
+
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
|
|
2977
|
+
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
|
|
2978
|
+
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : !1,
|
|
2979
|
+
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
|
|
2980
|
+
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
|
|
2981
|
+
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
|
|
2982
|
+
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : !0,
|
|
2983
|
+
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : !0,
|
|
2984
|
+
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : !0,
|
|
2985
|
+
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
|
|
2986
|
+
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : !0,
|
|
2987
|
+
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : !0,
|
|
2988
|
+
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : !0,
|
|
2989
|
+
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : !0,
|
|
2990
|
+
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : !0,
|
|
3041
2991
|
uriResolver
|
|
3042
2992
|
};
|
|
3043
2993
|
}
|
|
@@ -3061,14 +3011,14 @@ var require_core = __commonJS({
|
|
|
3061
3011
|
return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
|
|
3062
3012
|
}
|
|
3063
3013
|
validate(schemaKeyRef, data) {
|
|
3064
|
-
let
|
|
3014
|
+
let v;
|
|
3065
3015
|
if (typeof schemaKeyRef == "string") {
|
|
3066
|
-
if (
|
|
3016
|
+
if (v = this.getSchema(schemaKeyRef), !v)
|
|
3067
3017
|
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
|
|
3068
3018
|
} else
|
|
3069
|
-
|
|
3070
|
-
let valid =
|
|
3071
|
-
return "$async" in
|
|
3019
|
+
v = this.compile(schemaKeyRef);
|
|
3020
|
+
let valid = v(data);
|
|
3021
|
+
return "$async" in v || (this.errors = v.errors), valid;
|
|
3072
3022
|
}
|
|
3073
3023
|
compile(schema, _meta) {
|
|
3074
3024
|
let sch = this._addSchema(schema, _meta);
|
|
@@ -3090,10 +3040,10 @@ var require_core = __commonJS({
|
|
|
3090
3040
|
async function _compileAsync(sch) {
|
|
3091
3041
|
try {
|
|
3092
3042
|
return this._compileSchemaEnv(sch);
|
|
3093
|
-
} catch (
|
|
3094
|
-
if (!(
|
|
3095
|
-
throw
|
|
3096
|
-
return checkLoaded.call(this,
|
|
3043
|
+
} catch (e) {
|
|
3044
|
+
if (!(e instanceof ref_error_1.default))
|
|
3045
|
+
throw e;
|
|
3046
|
+
return checkLoaded.call(this, e), await loadMissingSchema.call(this, e.missingSchema), _compileAsync.call(this, sch);
|
|
3097
3047
|
}
|
|
3098
3048
|
}
|
|
3099
3049
|
function checkLoaded({ missingSchema: ref, missingRef }) {
|
|
@@ -3215,7 +3165,7 @@ var require_core = __commonJS({
|
|
|
3215
3165
|
type: (0, dataType_1.getJSONTypes)(def.type),
|
|
3216
3166
|
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
|
|
3217
3167
|
};
|
|
3218
|
-
return (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (
|
|
3168
|
+
return (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))), this;
|
|
3219
3169
|
}
|
|
3220
3170
|
getKeyword(keyword) {
|
|
3221
3171
|
let rule = this.RULES.all[keyword];
|
|
@@ -3226,8 +3176,8 @@ var require_core = __commonJS({
|
|
|
3226
3176
|
let { RULES } = this;
|
|
3227
3177
|
delete RULES.keywords[keyword], delete RULES.all[keyword];
|
|
3228
3178
|
for (let group of RULES.rules) {
|
|
3229
|
-
let
|
|
3230
|
-
|
|
3179
|
+
let i = group.rules.findIndex((rule) => rule.keyword === keyword);
|
|
3180
|
+
i >= 0 && group.rules.splice(i, 1);
|
|
3231
3181
|
}
|
|
3232
3182
|
return this;
|
|
3233
3183
|
}
|
|
@@ -3236,7 +3186,7 @@ var require_core = __commonJS({
|
|
|
3236
3186
|
return typeof format == "string" && (format = new RegExp(format)), this.formats[name] = format, this;
|
|
3237
3187
|
}
|
|
3238
3188
|
errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
|
|
3239
|
-
return !errors || errors.length === 0 ? "No errors" : errors.map((
|
|
3189
|
+
return !errors || errors.length === 0 ? "No errors" : errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);
|
|
3240
3190
|
}
|
|
3241
3191
|
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
|
|
3242
3192
|
let rules = this.RULES.all;
|
|
@@ -3345,13 +3295,13 @@ var require_core = __commonJS({
|
|
|
3345
3295
|
}, warn() {
|
|
3346
3296
|
}, error() {
|
|
3347
3297
|
} };
|
|
3348
|
-
function getLogger(
|
|
3349
|
-
if (
|
|
3298
|
+
function getLogger(logger) {
|
|
3299
|
+
if (logger === !1)
|
|
3350
3300
|
return noLogs;
|
|
3351
|
-
if (
|
|
3301
|
+
if (logger === void 0)
|
|
3352
3302
|
return console;
|
|
3353
|
-
if (
|
|
3354
|
-
return
|
|
3303
|
+
if (logger.log && logger.warn && logger.error)
|
|
3304
|
+
return logger;
|
|
3355
3305
|
throw new Error("logger must implement log, warn and error methods");
|
|
3356
3306
|
}
|
|
3357
3307
|
var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
|
@@ -3370,7 +3320,7 @@ var require_core = __commonJS({
|
|
|
3370
3320
|
let post = definition?.post;
|
|
3371
3321
|
if (dataType && post)
|
|
3372
3322
|
throw new Error('keyword with "post" flag cannot have "type"');
|
|
3373
|
-
let { RULES } = this, ruleGroup = post ? RULES.post : RULES.rules.find(({ type:
|
|
3323
|
+
let { RULES } = this, ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
|
|
3374
3324
|
if (ruleGroup || (ruleGroup = { type: dataType, rules: [] }, RULES.rules.push(ruleGroup)), RULES.keywords[keyword] = !0, !definition)
|
|
3375
3325
|
return;
|
|
3376
3326
|
let rule = {
|
|
@@ -3384,8 +3334,8 @@ var require_core = __commonJS({
|
|
|
3384
3334
|
definition.before ? addBeforeRule.call(this, ruleGroup, rule, definition.before) : ruleGroup.rules.push(rule), RULES.all[keyword] = rule, (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd));
|
|
3385
3335
|
}
|
|
3386
3336
|
function addBeforeRule(ruleGroup, rule, before) {
|
|
3387
|
-
let
|
|
3388
|
-
|
|
3337
|
+
let i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
|
|
3338
|
+
i >= 0 ? ruleGroup.rules.splice(i, 0, rule) : (ruleGroup.rules.push(rule), this.logger.warn(`rule ${before} is not defined`));
|
|
3389
3339
|
}
|
|
3390
3340
|
function keywordMetaschema(def) {
|
|
3391
3341
|
let { metaSchema } = def;
|
|
@@ -3441,8 +3391,8 @@ var require_ref = __commonJS({
|
|
|
3441
3391
|
return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
|
|
3442
3392
|
}
|
|
3443
3393
|
function callValidate(sch) {
|
|
3444
|
-
let
|
|
3445
|
-
callRef(cxt,
|
|
3394
|
+
let v = getValidate(cxt, sch);
|
|
3395
|
+
callRef(cxt, v, sch, sch.$async);
|
|
3446
3396
|
}
|
|
3447
3397
|
function inlineRefSchema(sch) {
|
|
3448
3398
|
let schName = gen.scopeValue("schema", opts.code.source === !0 ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }), valid = gen.name("valid"), schCxt = cxt.subschema({
|
|
@@ -3461,7 +3411,7 @@ var require_ref = __commonJS({
|
|
|
3461
3411
|
return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
|
|
3462
3412
|
}
|
|
3463
3413
|
exports.getValidate = getValidate;
|
|
3464
|
-
function callRef(cxt,
|
|
3414
|
+
function callRef(cxt, v, sch, $async) {
|
|
3465
3415
|
let { gen, it } = cxt, { allErrors, schemaEnv: env, opts } = it, passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
|
|
3466
3416
|
$async ? callAsyncRef() : callSyncRef();
|
|
3467
3417
|
function callAsyncRef() {
|
|
@@ -3469,13 +3419,13 @@ var require_ref = __commonJS({
|
|
|
3469
3419
|
throw new Error("async schema referenced by sync schema");
|
|
3470
3420
|
let valid = gen.let("valid");
|
|
3471
3421
|
gen.try(() => {
|
|
3472
|
-
gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt,
|
|
3473
|
-
}, (
|
|
3474
|
-
gen.if((0, codegen_1._)`!(${
|
|
3422
|
+
gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`), addEvaluatedFrom(v), allErrors || gen.assign(valid, !0);
|
|
3423
|
+
}, (e) => {
|
|
3424
|
+
gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)), addErrorsFrom(e), allErrors || gen.assign(valid, !1);
|
|
3475
3425
|
}), cxt.ok(valid);
|
|
3476
3426
|
}
|
|
3477
3427
|
function callSyncRef() {
|
|
3478
|
-
cxt.result((0, code_1.callValidateCode)(cxt,
|
|
3428
|
+
cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
|
|
3479
3429
|
}
|
|
3480
3430
|
function addErrorsFrom(source) {
|
|
3481
3431
|
let errs = (0, codegen_1._)`${source}.errors`;
|
|
@@ -3634,10 +3584,10 @@ var require_pattern = __commonJS({
|
|
|
3634
3584
|
$data: !0,
|
|
3635
3585
|
error,
|
|
3636
3586
|
code(cxt) {
|
|
3637
|
-
let { gen, data, $data, schema, schemaCode, it } = cxt,
|
|
3587
|
+
let { gen, data, $data, schema, schemaCode, it } = cxt, u = it.opts.unicodeRegExp ? "u" : "";
|
|
3638
3588
|
if ($data) {
|
|
3639
3589
|
let { regExp } = it.opts.code, regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp), valid = gen.let("valid");
|
|
3640
|
-
gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${
|
|
3590
|
+
gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, !1)), cxt.fail$data((0, codegen_1._)`!${valid}`);
|
|
3641
3591
|
} else {
|
|
3642
3592
|
let regExp = (0, code_1.usePattern)(cxt, schema);
|
|
3643
3593
|
cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
|
|
@@ -3777,8 +3727,8 @@ var require_uniqueItems = __commonJS({
|
|
|
3777
3727
|
"use strict";
|
|
3778
3728
|
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
3779
3729
|
var dataType_1 = require_dataType(), codegen_1 = require_codegen(), util_1 = require_util(), equal_1 = require_equal(), error = {
|
|
3780
|
-
message: ({ params: { i
|
|
3781
|
-
params: ({ params: { i
|
|
3730
|
+
message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
|
|
3731
|
+
params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`
|
|
3782
3732
|
}, def = {
|
|
3783
3733
|
keyword: "uniqueItems",
|
|
3784
3734
|
type: "array",
|
|
@@ -3792,23 +3742,23 @@ var require_uniqueItems = __commonJS({
|
|
|
3792
3742
|
let valid = gen.let("valid"), itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
|
|
3793
3743
|
cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`), cxt.ok(valid);
|
|
3794
3744
|
function validateUniqueItems() {
|
|
3795
|
-
let
|
|
3796
|
-
cxt.setParams({ i
|
|
3745
|
+
let i = gen.let("i", (0, codegen_1._)`${data}.length`), j = gen.let("j");
|
|
3746
|
+
cxt.setParams({ i, j }), gen.assign(valid, !0), gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
|
|
3797
3747
|
}
|
|
3798
3748
|
function canOptimize() {
|
|
3799
|
-
return itemTypes.length > 0 && !itemTypes.some((
|
|
3749
|
+
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
|
|
3800
3750
|
}
|
|
3801
|
-
function loopN(
|
|
3751
|
+
function loopN(i, j) {
|
|
3802
3752
|
let item = gen.name("item"), wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong), indices = gen.const("indices", (0, codegen_1._)`{}`);
|
|
3803
|
-
gen.for((0, codegen_1._)`;${
|
|
3804
|
-
gen.let(item, (0, codegen_1._)`${data}[${
|
|
3753
|
+
gen.for((0, codegen_1._)`;${i}--;`, () => {
|
|
3754
|
+
gen.let(item, (0, codegen_1._)`${data}[${i}]`), gen.if(wrongType, (0, codegen_1._)`continue`), itemTypes.length > 1 && gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`), gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
|
|
3805
3755
|
gen.assign(j, (0, codegen_1._)`${indices}[${item}]`), cxt.error(), gen.assign(valid, !1).break();
|
|
3806
|
-
}).code((0, codegen_1._)`${indices}[${item}] = ${
|
|
3756
|
+
}).code((0, codegen_1._)`${indices}[${item}] = ${i}`);
|
|
3807
3757
|
});
|
|
3808
3758
|
}
|
|
3809
|
-
function loopN2(
|
|
3759
|
+
function loopN2(i, j) {
|
|
3810
3760
|
let eql = (0, util_1.useFunc)(gen, equal_1.default), outer = gen.name("outer");
|
|
3811
|
-
gen.label(outer).for((0, codegen_1._)`;${
|
|
3761
|
+
gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
|
|
3812
3762
|
cxt.error(), gen.assign(valid, !1).break(outer);
|
|
3813
3763
|
})));
|
|
3814
3764
|
}
|
|
@@ -3863,15 +3813,15 @@ var require_enum = __commonJS({
|
|
|
3863
3813
|
if (!Array.isArray(schema))
|
|
3864
3814
|
throw new Error("ajv implementation error");
|
|
3865
3815
|
let vSchema = gen.const("vSchema", schemaCode);
|
|
3866
|
-
valid = (0, codegen_1.or)(...schema.map((_x,
|
|
3816
|
+
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
|
|
3867
3817
|
}
|
|
3868
3818
|
cxt.pass(valid);
|
|
3869
3819
|
function loopEnum() {
|
|
3870
|
-
gen.assign(valid, !1), gen.forOf("v", schemaCode, (
|
|
3820
|
+
gen.assign(valid, !1), gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, !0).break()));
|
|
3871
3821
|
}
|
|
3872
|
-
function equalCode(vSchema,
|
|
3873
|
-
let sch = schema[
|
|
3874
|
-
return typeof sch == "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${
|
|
3822
|
+
function equalCode(vSchema, i) {
|
|
3823
|
+
let sch = schema[i];
|
|
3824
|
+
return typeof sch == "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
|
|
3875
3825
|
}
|
|
3876
3826
|
}
|
|
3877
3827
|
};
|
|
@@ -3942,8 +3892,8 @@ var require_additionalItems = __commonJS({
|
|
|
3942
3892
|
gen.if((0, codegen_1.not)(valid), () => validateItems(valid)), cxt.ok(valid);
|
|
3943
3893
|
}
|
|
3944
3894
|
function validateItems(valid) {
|
|
3945
|
-
gen.forRange("i", items.length, len, (
|
|
3946
|
-
cxt.subschema({ keyword, dataProp:
|
|
3895
|
+
gen.forRange("i", items.length, len, (i) => {
|
|
3896
|
+
cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid), it.allErrors || gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
3947
3897
|
});
|
|
3948
3898
|
}
|
|
3949
3899
|
}
|
|
@@ -3974,11 +3924,11 @@ var require_items = __commonJS({
|
|
|
3974
3924
|
let { gen, parentSchema, data, keyword, it } = cxt;
|
|
3975
3925
|
checkStrictTuple(parentSchema), it.opts.unevaluated && schArr.length && it.items !== !0 && (it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items));
|
|
3976
3926
|
let valid = gen.name("valid"), len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
3977
|
-
schArr.forEach((sch,
|
|
3978
|
-
(0, util_1.alwaysValidSchema)(it, sch) || (gen.if((0, codegen_1._)`${len} > ${
|
|
3927
|
+
schArr.forEach((sch, i) => {
|
|
3928
|
+
(0, util_1.alwaysValidSchema)(it, sch) || (gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
|
|
3979
3929
|
keyword,
|
|
3980
|
-
schemaProp:
|
|
3981
|
-
dataProp:
|
|
3930
|
+
schemaProp: i,
|
|
3931
|
+
dataProp: i
|
|
3982
3932
|
}, valid)), cxt.ok(valid));
|
|
3983
3933
|
});
|
|
3984
3934
|
function checkStrictTuple(sch) {
|
|
@@ -4073,10 +4023,10 @@ var require_contains = __commonJS({
|
|
|
4073
4023
|
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
|
|
4074
4024
|
}
|
|
4075
4025
|
function validateItems(_valid, block) {
|
|
4076
|
-
gen.forRange("i", 0, len, (
|
|
4026
|
+
gen.forRange("i", 0, len, (i) => {
|
|
4077
4027
|
cxt.subschema({
|
|
4078
4028
|
keyword: "contains",
|
|
4079
|
-
dataProp:
|
|
4029
|
+
dataProp: i,
|
|
4080
4030
|
dataPropType: util_1.Type.Num,
|
|
4081
4031
|
compositeRule: !0
|
|
4082
4032
|
}, _valid), block();
|
|
@@ -4426,14 +4376,14 @@ var require_oneOf = __commonJS({
|
|
|
4426
4376
|
let schArr = schema, valid = gen.let("valid", !1), passing = gen.let("passing", null), schValid = gen.name("_valid");
|
|
4427
4377
|
cxt.setParams({ passing }), gen.block(validateOneOf), cxt.result(valid, () => cxt.reset(), () => cxt.error(!0));
|
|
4428
4378
|
function validateOneOf() {
|
|
4429
|
-
schArr.forEach((sch,
|
|
4379
|
+
schArr.forEach((sch, i) => {
|
|
4430
4380
|
let schCxt;
|
|
4431
4381
|
(0, util_1.alwaysValidSchema)(it, sch) ? gen.var(schValid, !0) : schCxt = cxt.subschema({
|
|
4432
4382
|
keyword: "oneOf",
|
|
4433
|
-
schemaProp:
|
|
4383
|
+
schemaProp: i,
|
|
4434
4384
|
compositeRule: !0
|
|
4435
|
-
}, schValid),
|
|
4436
|
-
gen.assign(valid, !0), gen.assign(passing,
|
|
4385
|
+
}, schValid), i > 0 && gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, !1).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(), gen.if(schValid, () => {
|
|
4386
|
+
gen.assign(valid, !0), gen.assign(passing, i), schCxt && cxt.mergeEvaluated(schCxt, codegen_1.Name);
|
|
4437
4387
|
});
|
|
4438
4388
|
});
|
|
4439
4389
|
}
|
|
@@ -4456,10 +4406,10 @@ var require_allOf = __commonJS({
|
|
|
4456
4406
|
if (!Array.isArray(schema))
|
|
4457
4407
|
throw new Error("ajv implementation error");
|
|
4458
4408
|
let valid = gen.name("valid");
|
|
4459
|
-
schema.forEach((sch,
|
|
4409
|
+
schema.forEach((sch, i) => {
|
|
4460
4410
|
if ((0, util_1.alwaysValidSchema)(it, sch))
|
|
4461
4411
|
return;
|
|
4462
|
-
let schCxt = cxt.subschema({ keyword: "allOf", schemaProp:
|
|
4412
|
+
let schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
|
|
4463
4413
|
cxt.ok(valid), cxt.mergeEvaluated(schCxt);
|
|
4464
4414
|
});
|
|
4465
4415
|
}
|
|
@@ -4737,8 +4687,8 @@ var require_discriminator = __commonJS({
|
|
|
4737
4687
|
function getMapping() {
|
|
4738
4688
|
var _a;
|
|
4739
4689
|
let oneOfMapping = {}, topRequired = hasRequired(parentSchema), tagRequired = !0;
|
|
4740
|
-
for (let
|
|
4741
|
-
let sch = oneOf[
|
|
4690
|
+
for (let i = 0; i < oneOf.length; i++) {
|
|
4691
|
+
let sch = oneOf[i];
|
|
4742
4692
|
if (sch?.$ref && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
|
|
4743
4693
|
let ref = sch.$ref;
|
|
4744
4694
|
if (sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref), sch instanceof compile_1.SchemaEnv && (sch = sch.schema), sch === void 0)
|
|
@@ -4747,7 +4697,7 @@ var require_discriminator = __commonJS({
|
|
|
4747
4697
|
let propSch = (_a = sch?.properties) === null || _a === void 0 ? void 0 : _a[tagName];
|
|
4748
4698
|
if (typeof propSch != "object")
|
|
4749
4699
|
throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
|
|
4750
|
-
tagRequired = tagRequired && (topRequired || hasRequired(sch)), addMappings(propSch,
|
|
4700
|
+
tagRequired = tagRequired && (topRequired || hasRequired(sch)), addMappings(propSch, i);
|
|
4751
4701
|
}
|
|
4752
4702
|
if (!tagRequired)
|
|
4753
4703
|
throw new Error(`discriminator: "${tagName}" must be required`);
|
|
@@ -4755,19 +4705,19 @@ var require_discriminator = __commonJS({
|
|
|
4755
4705
|
function hasRequired({ required }) {
|
|
4756
4706
|
return Array.isArray(required) && required.includes(tagName);
|
|
4757
4707
|
}
|
|
4758
|
-
function addMappings(sch,
|
|
4708
|
+
function addMappings(sch, i) {
|
|
4759
4709
|
if (sch.const)
|
|
4760
|
-
addMapping(sch.const,
|
|
4710
|
+
addMapping(sch.const, i);
|
|
4761
4711
|
else if (sch.enum)
|
|
4762
4712
|
for (let tagValue of sch.enum)
|
|
4763
|
-
addMapping(tagValue,
|
|
4713
|
+
addMapping(tagValue, i);
|
|
4764
4714
|
else
|
|
4765
4715
|
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
|
|
4766
4716
|
}
|
|
4767
|
-
function addMapping(tagValue,
|
|
4717
|
+
function addMapping(tagValue, i) {
|
|
4768
4718
|
if (typeof tagValue != "string" || tagValue in oneOfMapping)
|
|
4769
4719
|
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
|
|
4770
|
-
oneOfMapping[tagValue] =
|
|
4720
|
+
oneOfMapping[tagValue] = i;
|
|
4771
4721
|
}
|
|
4772
4722
|
}
|
|
4773
4723
|
}
|
|
@@ -4941,7 +4891,7 @@ var require_ajv = __commonJS({
|
|
|
4941
4891
|
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
|
|
4942
4892
|
var core_1 = require_core(), draft7_1 = require_draft7(), discriminator_1 = require_discriminator(), draft7MetaSchema = require_json_schema_draft_07(), META_SUPPORT_DATA = ["/properties"], META_SCHEMA_ID = "http://json-schema.org/draft-07/schema", Ajv2 = class extends core_1.default {
|
|
4943
4893
|
_addVocabularies() {
|
|
4944
|
-
super._addVocabularies(), draft7_1.default.forEach((
|
|
4894
|
+
super._addVocabularies(), draft7_1.default.forEach((v) => this.addVocabulary(v)), this.opts.discriminator && this.addKeyword(discriminator_1.default);
|
|
4945
4895
|
}
|
|
4946
4896
|
_addDefaultMetaSchema() {
|
|
4947
4897
|
if (super._addDefaultMetaSchema(), !this.opts.meta)
|
|
@@ -5231,16 +5181,16 @@ var require_dist = __commonJS({
|
|
|
5231
5181
|
return addFormats(ajv, list, formats, exportName), opts.keywords && (0, limit_1.default)(ajv), ajv;
|
|
5232
5182
|
};
|
|
5233
5183
|
formatsPlugin.get = (name, mode = "full") => {
|
|
5234
|
-
let
|
|
5235
|
-
if (!
|
|
5184
|
+
let f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name];
|
|
5185
|
+
if (!f)
|
|
5236
5186
|
throw new Error(`Unknown format "${name}"`);
|
|
5237
|
-
return
|
|
5187
|
+
return f;
|
|
5238
5188
|
};
|
|
5239
5189
|
function addFormats(ajv, list, fs, exportName) {
|
|
5240
5190
|
var _a, _b;
|
|
5241
5191
|
(_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);
|
|
5242
|
-
for (let
|
|
5243
|
-
ajv.addFormat(
|
|
5192
|
+
for (let f of list)
|
|
5193
|
+
ajv.addFormat(f, fs[f]);
|
|
5244
5194
|
}
|
|
5245
5195
|
module.exports = exports = formatsPlugin;
|
|
5246
5196
|
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
@@ -5248,287 +5198,9 @@ var require_dist = __commonJS({
|
|
|
5248
5198
|
}
|
|
5249
5199
|
});
|
|
5250
5200
|
|
|
5251
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/init.js
|
|
5252
|
-
import { existsSync as existsSync2 } from "node:fs";
|
|
5253
|
-
|
|
5254
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/errors.js
|
|
5255
|
-
var McpUiError = class extends Error {
|
|
5256
|
-
code;
|
|
5257
|
-
context;
|
|
5258
|
-
recoveryHint;
|
|
5259
|
-
cause;
|
|
5260
|
-
constructor(message, options) {
|
|
5261
|
-
super(message), this.name = "McpUiError", this.code = options.code, this.context = options.context ?? {}, this.recoveryHint = options.recoveryHint, this.cause = options.cause, Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
|
|
5262
|
-
}
|
|
5263
|
-
toJSON() {
|
|
5264
|
-
return {
|
|
5265
|
-
name: this.name,
|
|
5266
|
-
code: this.code,
|
|
5267
|
-
message: this.message,
|
|
5268
|
-
context: this.context,
|
|
5269
|
-
recoveryHint: this.recoveryHint,
|
|
5270
|
-
stack: this.stack
|
|
5271
|
-
};
|
|
5272
|
-
}
|
|
5273
|
-
}, ResourceFetchError = class extends McpUiError {
|
|
5274
|
-
constructor(uri, reason, options) {
|
|
5275
|
-
super(`Failed to fetch UI resource "${uri}": ${reason}`, {
|
|
5276
|
-
code: "RESOURCE_FETCH_ERROR",
|
|
5277
|
-
context: { uri, server: options?.server },
|
|
5278
|
-
recoveryHint: "Check that the MCP server is connected and the resource URI is valid.",
|
|
5279
|
-
cause: options?.cause
|
|
5280
|
-
}), this.name = "ResourceFetchError";
|
|
5281
|
-
}
|
|
5282
|
-
}, ResourceParseError = class extends McpUiError {
|
|
5283
|
-
constructor(uri, reason, options) {
|
|
5284
|
-
super(`Invalid UI resource "${uri}": ${reason}`, {
|
|
5285
|
-
code: "RESOURCE_PARSE_ERROR",
|
|
5286
|
-
context: { uri, server: options?.server, mimeType: options?.mimeType },
|
|
5287
|
-
recoveryHint: "Ensure the resource returns valid HTML with the correct MIME type."
|
|
5288
|
-
}), this.name = "ResourceParseError";
|
|
5289
|
-
}
|
|
5290
|
-
};
|
|
5291
|
-
var ConsentError = class extends McpUiError {
|
|
5292
|
-
denied;
|
|
5293
|
-
constructor(server, options) {
|
|
5294
|
-
let message = options.denied ? `Tool calls for "${server}" were denied for this session` : `Tool call approval required for "${server}"`;
|
|
5295
|
-
super(message, {
|
|
5296
|
-
code: options.denied ? "CONSENT_DENIED" : "CONSENT_REQUIRED",
|
|
5297
|
-
context: { server },
|
|
5298
|
-
recoveryHint: options.denied ? "The user denied tool access. Start a new session to try again." : "Prompt the user for consent before calling tools."
|
|
5299
|
-
}), this.name = "ConsentError", this.denied = options.denied ?? !1;
|
|
5300
|
-
}
|
|
5301
|
-
};
|
|
5302
|
-
var ServerError = class extends McpUiError {
|
|
5303
|
-
constructor(reason, options) {
|
|
5304
|
-
super(`UI server error: ${reason}`, {
|
|
5305
|
-
code: "SERVER_ERROR",
|
|
5306
|
-
context: { port: options?.port },
|
|
5307
|
-
recoveryHint: "Check if the port is available. Another process may be using it.",
|
|
5308
|
-
cause: options?.cause
|
|
5309
|
-
}), this.name = "ServerError";
|
|
5310
|
-
}
|
|
5311
|
-
};
|
|
5312
|
-
function wrapError(error, context) {
|
|
5313
|
-
if (error instanceof McpUiError)
|
|
5314
|
-
return new McpUiError(error.message, {
|
|
5315
|
-
code: error.code,
|
|
5316
|
-
context: { ...error.context, ...context },
|
|
5317
|
-
recoveryHint: error.recoveryHint,
|
|
5318
|
-
cause: error.cause
|
|
5319
|
-
});
|
|
5320
|
-
let cause = error instanceof Error ? error : void 0, message = error instanceof Error ? error.message : String(error);
|
|
5321
|
-
return new McpUiError(message, {
|
|
5322
|
-
code: "UNKNOWN_ERROR",
|
|
5323
|
-
context,
|
|
5324
|
-
cause
|
|
5325
|
-
});
|
|
5326
|
-
}
|
|
5327
|
-
|
|
5328
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/logger.js
|
|
5329
|
-
var LEVEL_PRIORITY = {
|
|
5330
|
-
debug: 0,
|
|
5331
|
-
info: 1,
|
|
5332
|
-
warn: 2,
|
|
5333
|
-
error: 3
|
|
5334
|
-
}, LEVEL_PREFIX = {
|
|
5335
|
-
debug: "[MCP-UI:DEBUG]",
|
|
5336
|
-
info: "[MCP-UI]",
|
|
5337
|
-
warn: "[MCP-UI:WARN]",
|
|
5338
|
-
error: "[MCP-UI:ERROR]"
|
|
5339
|
-
}, Logger = class {
|
|
5340
|
-
minLevel = "info";
|
|
5341
|
-
handlers = [];
|
|
5342
|
-
defaultContext = {};
|
|
5343
|
-
setLevel(level) {
|
|
5344
|
-
this.minLevel = level;
|
|
5345
|
-
}
|
|
5346
|
-
setDefaultContext(context) {
|
|
5347
|
-
this.defaultContext = context;
|
|
5348
|
-
}
|
|
5349
|
-
addHandler(handler) {
|
|
5350
|
-
this.handlers.push(handler);
|
|
5351
|
-
}
|
|
5352
|
-
clearHandlers() {
|
|
5353
|
-
this.handlers = [];
|
|
5354
|
-
}
|
|
5355
|
-
shouldLog(level) {
|
|
5356
|
-
return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[this.minLevel];
|
|
5357
|
-
}
|
|
5358
|
-
emit(level, message, context, error) {
|
|
5359
|
-
if (!this.shouldLog(level))
|
|
5360
|
-
return;
|
|
5361
|
-
let entry = {
|
|
5362
|
-
level,
|
|
5363
|
-
message,
|
|
5364
|
-
context: { ...this.defaultContext, ...context },
|
|
5365
|
-
error,
|
|
5366
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
5367
|
-
}, prefix = LEVEL_PREFIX[level], contextStr = formatContext(entry.context), fullMessage = contextStr ? `${prefix} ${message} ${contextStr}` : `${prefix} ${message}`;
|
|
5368
|
-
level === "error" ? console.error(fullMessage, error ?? "") : level === "warn" ? console.warn(fullMessage) : level === "debug" ? console.debug(fullMessage) : console.log(fullMessage);
|
|
5369
|
-
for (let handler of this.handlers)
|
|
5370
|
-
try {
|
|
5371
|
-
handler(entry);
|
|
5372
|
-
} catch {
|
|
5373
|
-
}
|
|
5374
|
-
}
|
|
5375
|
-
debug(message, context) {
|
|
5376
|
-
this.emit("debug", message, context);
|
|
5377
|
-
}
|
|
5378
|
-
info(message, context) {
|
|
5379
|
-
this.emit("info", message, context);
|
|
5380
|
-
}
|
|
5381
|
-
warn(message, context) {
|
|
5382
|
-
this.emit("warn", message, context);
|
|
5383
|
-
}
|
|
5384
|
-
error(message, error, context) {
|
|
5385
|
-
this.emit("error", message, context, error);
|
|
5386
|
-
}
|
|
5387
|
-
/**
|
|
5388
|
-
* Create a child logger with additional default context.
|
|
5389
|
-
*/
|
|
5390
|
-
child(context) {
|
|
5391
|
-
return new ChildLogger(this, context);
|
|
5392
|
-
}
|
|
5393
|
-
}, ChildLogger = class _ChildLogger {
|
|
5394
|
-
parent;
|
|
5395
|
-
context;
|
|
5396
|
-
constructor(parent, context) {
|
|
5397
|
-
this.parent = parent, this.context = context;
|
|
5398
|
-
}
|
|
5399
|
-
debug(message, context) {
|
|
5400
|
-
this.parent.debug(message, { ...this.context, ...context });
|
|
5401
|
-
}
|
|
5402
|
-
info(message, context) {
|
|
5403
|
-
this.parent.info(message, { ...this.context, ...context });
|
|
5404
|
-
}
|
|
5405
|
-
warn(message, context) {
|
|
5406
|
-
this.parent.warn(message, { ...this.context, ...context });
|
|
5407
|
-
}
|
|
5408
|
-
error(message, error, context) {
|
|
5409
|
-
this.parent.error(message, error, { ...this.context, ...context });
|
|
5410
|
-
}
|
|
5411
|
-
child(context) {
|
|
5412
|
-
return new _ChildLogger(this.parent, { ...this.context, ...context });
|
|
5413
|
-
}
|
|
5414
|
-
};
|
|
5415
|
-
function formatContext(context) {
|
|
5416
|
-
if (!context || Object.keys(context).length === 0)
|
|
5417
|
-
return "";
|
|
5418
|
-
let parts = [];
|
|
5419
|
-
for (let [key, value] of Object.entries(context))
|
|
5420
|
-
value != null && parts.push(`${key}=${typeof value == "string" ? value : JSON.stringify(value)}`);
|
|
5421
|
-
return parts.length > 0 ? `(${parts.join(", ")})` : "";
|
|
5422
|
-
}
|
|
5423
|
-
var logger = new Logger();
|
|
5424
|
-
(process.env.MCP_UI_DEBUG === "1" || process.env.MCP_UI_DEBUG === "true") && logger.setLevel("debug");
|
|
5425
|
-
|
|
5426
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/consent-manager.js
|
|
5427
|
-
var ConsentManager = class {
|
|
5428
|
-
mode;
|
|
5429
|
-
approvedServers = /* @__PURE__ */ new Set();
|
|
5430
|
-
deniedServers = /* @__PURE__ */ new Set();
|
|
5431
|
-
log = logger.child({ component: "ConsentManager" });
|
|
5432
|
-
constructor(mode = "once-per-server") {
|
|
5433
|
-
this.mode = mode, this.log.debug("Initialized", { mode });
|
|
5434
|
-
}
|
|
5435
|
-
requiresPrompt(serverName) {
|
|
5436
|
-
return this.mode === "never" ? !1 : this.deniedServers.has(serverName) || this.mode === "always" ? !0 : !this.approvedServers.has(serverName);
|
|
5437
|
-
}
|
|
5438
|
-
shouldCacheConsent() {
|
|
5439
|
-
return this.mode !== "always";
|
|
5440
|
-
}
|
|
5441
|
-
registerDecision(serverName, approved) {
|
|
5442
|
-
if (this.deniedServers.delete(serverName), this.approvedServers.delete(serverName), approved) {
|
|
5443
|
-
this.approvedServers.add(serverName), this.log.debug("Consent granted", { server: serverName });
|
|
5444
|
-
return;
|
|
5445
|
-
}
|
|
5446
|
-
this.deniedServers.add(serverName), this.log.debug("Consent denied", { server: serverName });
|
|
5447
|
-
}
|
|
5448
|
-
ensureApproved(serverName) {
|
|
5449
|
-
if (this.mode !== "never") {
|
|
5450
|
-
if (this.deniedServers.has(serverName))
|
|
5451
|
-
throw new ConsentError(serverName, { denied: !0 });
|
|
5452
|
-
if (!this.approvedServers.has(serverName))
|
|
5453
|
-
throw new ConsentError(serverName, { requiresApproval: !0 });
|
|
5454
|
-
this.mode === "always" && this.approvedServers.delete(serverName);
|
|
5455
|
-
}
|
|
5456
|
-
}
|
|
5457
|
-
clear(serverName) {
|
|
5458
|
-
if (serverName) {
|
|
5459
|
-
this.approvedServers.delete(serverName), this.deniedServers.delete(serverName), this.log.debug("Cleared consent for server", { server: serverName });
|
|
5460
|
-
return;
|
|
5461
|
-
}
|
|
5462
|
-
this.approvedServers.clear(), this.deniedServers.clear(), this.log.debug("Cleared all consent records");
|
|
5463
|
-
}
|
|
5464
|
-
};
|
|
5465
|
-
|
|
5466
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/lifecycle.js
|
|
5467
|
-
var McpLifecycleManager = class {
|
|
5468
|
-
manager;
|
|
5469
|
-
keepAliveServers = /* @__PURE__ */ new Map();
|
|
5470
|
-
allServers = /* @__PURE__ */ new Map();
|
|
5471
|
-
serverSettings = /* @__PURE__ */ new Map();
|
|
5472
|
-
globalIdleTimeout = 600 * 1e3;
|
|
5473
|
-
healthCheckInterval;
|
|
5474
|
-
onReconnect;
|
|
5475
|
-
onIdleShutdown;
|
|
5476
|
-
constructor(manager) {
|
|
5477
|
-
this.manager = manager;
|
|
5478
|
-
}
|
|
5479
|
-
/**
|
|
5480
|
-
* Set callback to be invoked after a successful auto-reconnect.
|
|
5481
|
-
* Use this to update tool metadata when a server reconnects.
|
|
5482
|
-
*/
|
|
5483
|
-
setReconnectCallback(callback) {
|
|
5484
|
-
this.onReconnect = callback;
|
|
5485
|
-
}
|
|
5486
|
-
markKeepAlive(name, definition) {
|
|
5487
|
-
this.keepAliveServers.set(name, definition);
|
|
5488
|
-
}
|
|
5489
|
-
registerServer(name, definition, settings) {
|
|
5490
|
-
this.allServers.set(name, definition), settings?.idleTimeout !== void 0 && this.serverSettings.set(name, settings);
|
|
5491
|
-
}
|
|
5492
|
-
setGlobalIdleTimeout(minutes) {
|
|
5493
|
-
this.globalIdleTimeout = minutes * 60 * 1e3;
|
|
5494
|
-
}
|
|
5495
|
-
setIdleShutdownCallback(callback) {
|
|
5496
|
-
this.onIdleShutdown = callback;
|
|
5497
|
-
}
|
|
5498
|
-
startHealthChecks(intervalMs = 3e4) {
|
|
5499
|
-
this.healthCheckInterval = setInterval(() => {
|
|
5500
|
-
this.checkConnections();
|
|
5501
|
-
}, intervalMs), this.healthCheckInterval.unref();
|
|
5502
|
-
}
|
|
5503
|
-
async checkConnections() {
|
|
5504
|
-
for (let [name, definition] of this.keepAliveServers) {
|
|
5505
|
-
let connection = this.manager.getConnection(name);
|
|
5506
|
-
if (!connection || connection.status !== "connected")
|
|
5507
|
-
try {
|
|
5508
|
-
await this.manager.connect(name, definition), logger.debug(`Reconnected to ${name}`), this.onReconnect?.(name);
|
|
5509
|
-
} catch (error) {
|
|
5510
|
-
console.error(`MCP: Failed to reconnect to ${name}:`, error);
|
|
5511
|
-
}
|
|
5512
|
-
}
|
|
5513
|
-
for (let [name] of this.allServers) {
|
|
5514
|
-
if (this.keepAliveServers.has(name))
|
|
5515
|
-
continue;
|
|
5516
|
-
let timeout = this.getIdleTimeout(name);
|
|
5517
|
-
timeout > 0 && this.manager.isIdle(name, timeout) && (await this.manager.close(name), this.onIdleShutdown?.(name));
|
|
5518
|
-
}
|
|
5519
|
-
}
|
|
5520
|
-
getIdleTimeout(name) {
|
|
5521
|
-
let perServer = this.serverSettings.get(name)?.idleTimeout;
|
|
5522
|
-
return perServer !== void 0 ? perServer * 60 * 1e3 : this.globalIdleTimeout;
|
|
5523
|
-
}
|
|
5524
|
-
async gracefulShutdown() {
|
|
5525
|
-
this.healthCheckInterval && clearInterval(this.healthCheckInterval), await this.manager.closeAll();
|
|
5526
|
-
}
|
|
5527
|
-
};
|
|
5528
|
-
|
|
5529
5201
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
|
|
5530
|
-
function isZ4Schema(
|
|
5531
|
-
return !!
|
|
5202
|
+
function isZ4Schema(s) {
|
|
5203
|
+
return !!s._zod;
|
|
5532
5204
|
}
|
|
5533
5205
|
function safeParse2(schema, data) {
|
|
5534
5206
|
return isZ4Schema(schema) ? safeParse(schema, data) : schema.safeParse(data);
|
|
@@ -5791,13 +5463,13 @@ var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4, Protocol = class {
|
|
|
5791
5463
|
let notificationOptions = { relatedRequestId: request.id };
|
|
5792
5464
|
relatedTaskId && (notificationOptions.relatedTask = { taskId: relatedTaskId }), await this.notification(notification, notificationOptions);
|
|
5793
5465
|
},
|
|
5794
|
-
sendRequest: async (
|
|
5466
|
+
sendRequest: async (r, resultSchema, options) => {
|
|
5795
5467
|
if (abortController.signal.aborted)
|
|
5796
5468
|
throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
|
|
5797
5469
|
let requestOptions = { ...options, relatedRequestId: request.id };
|
|
5798
5470
|
relatedTaskId && !requestOptions.relatedTask && (requestOptions.relatedTask = { taskId: relatedTaskId });
|
|
5799
5471
|
let effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
|
|
5800
|
-
return effectiveTaskId && taskStore && await taskStore.updateTaskStatus(effectiveTaskId, "input_required"), await this.request(
|
|
5472
|
+
return effectiveTaskId && taskStore && await taskStore.updateTaskStatus(effectiveTaskId, "input_required"), await this.request(r, resultSchema, requestOptions);
|
|
5801
5473
|
},
|
|
5802
5474
|
authInfo: extra?.authInfo,
|
|
5803
5475
|
requestId: request.id,
|
|
@@ -5965,7 +5637,7 @@ var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4, Protocol = class {
|
|
|
5965
5637
|
return;
|
|
5966
5638
|
}
|
|
5967
5639
|
let pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
|
|
5968
|
-
await new Promise((
|
|
5640
|
+
await new Promise((resolve) => setTimeout(resolve, pollInterval)), options?.signal?.throwIfAborted();
|
|
5969
5641
|
}
|
|
5970
5642
|
} catch (error) {
|
|
5971
5643
|
yield {
|
|
@@ -5981,7 +5653,7 @@ var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4, Protocol = class {
|
|
|
5981
5653
|
*/
|
|
5982
5654
|
request(request, resultSchema, options) {
|
|
5983
5655
|
let { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
|
|
5984
|
-
return new Promise((
|
|
5656
|
+
return new Promise((resolve, reject) => {
|
|
5985
5657
|
let earlyReject = (error) => {
|
|
5986
5658
|
reject(error);
|
|
5987
5659
|
};
|
|
@@ -5992,8 +5664,8 @@ var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4, Protocol = class {
|
|
|
5992
5664
|
if (this._options?.enforceStrictCapabilities === !0)
|
|
5993
5665
|
try {
|
|
5994
5666
|
this.assertCapabilityForMethod(request.method), task && this.assertTaskCapability(request.method);
|
|
5995
|
-
} catch (
|
|
5996
|
-
earlyReject(
|
|
5667
|
+
} catch (e) {
|
|
5668
|
+
earlyReject(e);
|
|
5997
5669
|
return;
|
|
5998
5670
|
}
|
|
5999
5671
|
options?.signal?.throwIfAborted();
|
|
@@ -6036,7 +5708,7 @@ var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4, Protocol = class {
|
|
|
6036
5708
|
return reject(response);
|
|
6037
5709
|
try {
|
|
6038
5710
|
let parseResult = safeParse2(resultSchema, response.result);
|
|
6039
|
-
parseResult.success ?
|
|
5711
|
+
parseResult.success ? resolve(parseResult.data) : reject(parseResult.error);
|
|
6040
5712
|
} catch (error) {
|
|
6041
5713
|
reject(error);
|
|
6042
5714
|
}
|
|
@@ -6259,12 +5931,12 @@ var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4, Protocol = class {
|
|
|
6259
5931
|
task?.pollInterval && (interval = task.pollInterval);
|
|
6260
5932
|
} catch {
|
|
6261
5933
|
}
|
|
6262
|
-
return new Promise((
|
|
5934
|
+
return new Promise((resolve, reject) => {
|
|
6263
5935
|
if (signal.aborted) {
|
|
6264
5936
|
reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
|
|
6265
5937
|
return;
|
|
6266
5938
|
}
|
|
6267
|
-
let timeoutId = setTimeout(
|
|
5939
|
+
let timeoutId = setTimeout(resolve, interval);
|
|
6268
5940
|
signal.addEventListener("abort", () => {
|
|
6269
5941
|
clearTimeout(timeoutId), reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
|
|
6270
5942
|
}, { once: !0 });
|
|
@@ -6327,11 +5999,11 @@ function isPlainObject(value) {
|
|
|
6327
5999
|
function mergeCapabilities(base, additional) {
|
|
6328
6000
|
let result = { ...base };
|
|
6329
6001
|
for (let key in additional) {
|
|
6330
|
-
let
|
|
6002
|
+
let k = key, addValue = additional[k];
|
|
6331
6003
|
if (addValue === void 0)
|
|
6332
6004
|
continue;
|
|
6333
|
-
let baseValue = result[
|
|
6334
|
-
isPlainObject(baseValue) && isPlainObject(addValue) ? result[
|
|
6005
|
+
let baseValue = result[k];
|
|
6006
|
+
isPlainObject(baseValue) && isPlainObject(addValue) ? result[k] = { ...baseValue, ...addValue } : result[k] = addValue;
|
|
6335
6007
|
}
|
|
6336
6008
|
return result;
|
|
6337
6009
|
}
|
|
@@ -6944,8 +6616,8 @@ var Client = class extends Protocol {
|
|
|
6944
6616
|
try {
|
|
6945
6617
|
let items = await fetcher();
|
|
6946
6618
|
onChanged(null, items);
|
|
6947
|
-
} catch (
|
|
6948
|
-
let error =
|
|
6619
|
+
} catch (e) {
|
|
6620
|
+
let error = e instanceof Error ? e : new Error(String(e));
|
|
6949
6621
|
onChanged(error, null);
|
|
6950
6622
|
}
|
|
6951
6623
|
}, handler = () => {
|
|
@@ -6966,7 +6638,7 @@ var Client = class extends Protocol {
|
|
|
6966
6638
|
|
|
6967
6639
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
|
|
6968
6640
|
var import_cross_spawn = __toESM(require_cross_spawn(), 1);
|
|
6969
|
-
import
|
|
6641
|
+
import process from "node:process";
|
|
6970
6642
|
import { PassThrough } from "node:stream";
|
|
6971
6643
|
|
|
6972
6644
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
|
|
@@ -7002,7 +6674,7 @@ function serializeMessage(message) {
|
|
|
7002
6674
|
}
|
|
7003
6675
|
|
|
7004
6676
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
|
|
7005
|
-
var DEFAULT_INHERITED_ENV_VARS =
|
|
6677
|
+
var DEFAULT_INHERITED_ENV_VARS = process.platform === "win32" ? [
|
|
7006
6678
|
"APPDATA",
|
|
7007
6679
|
"HOMEDRIVE",
|
|
7008
6680
|
"HOMEPATH",
|
|
@@ -7022,7 +6694,7 @@ var DEFAULT_INHERITED_ENV_VARS = process2.platform === "win32" ? [
|
|
|
7022
6694
|
function getDefaultEnvironment() {
|
|
7023
6695
|
let env = {};
|
|
7024
6696
|
for (let key of DEFAULT_INHERITED_ENV_VARS) {
|
|
7025
|
-
let value =
|
|
6697
|
+
let value = process.env[key];
|
|
7026
6698
|
value !== void 0 && (value.startsWith("()") || (env[key] = value));
|
|
7027
6699
|
}
|
|
7028
6700
|
return env;
|
|
@@ -7037,7 +6709,7 @@ var StdioClientTransport = class {
|
|
|
7037
6709
|
async start() {
|
|
7038
6710
|
if (this._process)
|
|
7039
6711
|
throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
7040
|
-
return new Promise((
|
|
6712
|
+
return new Promise((resolve, reject) => {
|
|
7041
6713
|
this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], {
|
|
7042
6714
|
// merge default env with server env because mcp server needs some env vars
|
|
7043
6715
|
env: {
|
|
@@ -7046,12 +6718,12 @@ var StdioClientTransport = class {
|
|
|
7046
6718
|
},
|
|
7047
6719
|
stdio: ["pipe", "pipe", this._serverParams.stderr ?? "inherit"],
|
|
7048
6720
|
shell: !1,
|
|
7049
|
-
windowsHide:
|
|
6721
|
+
windowsHide: process.platform === "win32",
|
|
7050
6722
|
cwd: this._serverParams.cwd
|
|
7051
6723
|
}), this._process.on("error", (error) => {
|
|
7052
6724
|
reject(error), this.onerror?.(error);
|
|
7053
6725
|
}), this._process.on("spawn", () => {
|
|
7054
|
-
|
|
6726
|
+
resolve();
|
|
7055
6727
|
}), this._process.on("close", (_code) => {
|
|
7056
6728
|
this._process = void 0, this.onclose?.();
|
|
7057
6729
|
}), this._process.stdin?.on("error", (error) => {
|
|
@@ -7101,21 +6773,21 @@ var StdioClientTransport = class {
|
|
|
7101
6773
|
if (this._process) {
|
|
7102
6774
|
let processToClose = this._process;
|
|
7103
6775
|
this._process = void 0;
|
|
7104
|
-
let closePromise = new Promise((
|
|
6776
|
+
let closePromise = new Promise((resolve) => {
|
|
7105
6777
|
processToClose.once("close", () => {
|
|
7106
|
-
|
|
6778
|
+
resolve();
|
|
7107
6779
|
});
|
|
7108
6780
|
});
|
|
7109
6781
|
try {
|
|
7110
6782
|
processToClose.stdin?.end();
|
|
7111
6783
|
} catch {
|
|
7112
6784
|
}
|
|
7113
|
-
if (await Promise.race([closePromise, new Promise((
|
|
6785
|
+
if (await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]), processToClose.exitCode === null) {
|
|
7114
6786
|
try {
|
|
7115
6787
|
processToClose.kill("SIGTERM");
|
|
7116
6788
|
} catch {
|
|
7117
6789
|
}
|
|
7118
|
-
await Promise.race([closePromise, new Promise((
|
|
6790
|
+
await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]);
|
|
7119
6791
|
}
|
|
7120
6792
|
if (processToClose.exitCode === null)
|
|
7121
6793
|
try {
|
|
@@ -7126,1831 +6798,17 @@ var StdioClientTransport = class {
|
|
|
7126
6798
|
this._readBuffer.clear();
|
|
7127
6799
|
}
|
|
7128
6800
|
send(message) {
|
|
7129
|
-
return new Promise((
|
|
6801
|
+
return new Promise((resolve) => {
|
|
7130
6802
|
if (!this._process?.stdin)
|
|
7131
6803
|
throw new Error("Not connected");
|
|
7132
6804
|
let json = serializeMessage(message);
|
|
7133
|
-
this._process.stdin.write(json) ?
|
|
7134
|
-
});
|
|
7135
|
-
}
|
|
7136
|
-
};
|
|
7137
|
-
|
|
7138
|
-
// node_modules/eventsource/dist/index.js
|
|
7139
|
-
var ErrorEvent = class extends Event {
|
|
7140
|
-
/**
|
|
7141
|
-
* Constructs a new `ErrorEvent` instance. This is typically not called directly,
|
|
7142
|
-
* but rather emitted by the `EventSource` object when an error occurs.
|
|
7143
|
-
*
|
|
7144
|
-
* @param type - The type of the event (should be "error")
|
|
7145
|
-
* @param errorEventInitDict - Optional properties to include in the error event
|
|
7146
|
-
*/
|
|
7147
|
-
constructor(type, errorEventInitDict) {
|
|
7148
|
-
var _a, _b;
|
|
7149
|
-
super(type), this.code = (_a = errorEventInitDict?.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict?.message) != null ? _b : void 0;
|
|
7150
|
-
}
|
|
7151
|
-
/**
|
|
7152
|
-
* Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
|
|
7153
|
-
* when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
|
|
7154
|
-
* we explicitly include the properties in the `inspect` method.
|
|
7155
|
-
*
|
|
7156
|
-
* This is automatically called by Node.js when you `console.log` an instance of this class.
|
|
7157
|
-
*
|
|
7158
|
-
* @param _depth - The current depth
|
|
7159
|
-
* @param options - The options passed to `util.inspect`
|
|
7160
|
-
* @param inspect - The inspect function to use (prevents having to import it from `util`)
|
|
7161
|
-
* @returns A string representation of the error
|
|
7162
|
-
*/
|
|
7163
|
-
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
|
|
7164
|
-
return inspect(inspectableError(this), options);
|
|
7165
|
-
}
|
|
7166
|
-
/**
|
|
7167
|
-
* Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
|
|
7168
|
-
* when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
|
|
7169
|
-
* we explicitly include the properties in the `inspect` method.
|
|
7170
|
-
*
|
|
7171
|
-
* This is automatically called by Deno when you `console.log` an instance of this class.
|
|
7172
|
-
*
|
|
7173
|
-
* @param inspect - The inspect function to use (prevents having to import it from `util`)
|
|
7174
|
-
* @param options - The options passed to `Deno.inspect`
|
|
7175
|
-
* @returns A string representation of the error
|
|
7176
|
-
*/
|
|
7177
|
-
[/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) {
|
|
7178
|
-
return inspect(inspectableError(this), options);
|
|
7179
|
-
}
|
|
7180
|
-
};
|
|
7181
|
-
function syntaxError(message) {
|
|
7182
|
-
let DomException = globalThis.DOMException;
|
|
7183
|
-
return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
|
|
7184
|
-
}
|
|
7185
|
-
function flattenError(err) {
|
|
7186
|
-
return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
|
|
7187
|
-
}
|
|
7188
|
-
function inspectableError(err) {
|
|
7189
|
-
return {
|
|
7190
|
-
type: err.type,
|
|
7191
|
-
message: err.message,
|
|
7192
|
-
code: err.code,
|
|
7193
|
-
defaultPrevented: err.defaultPrevented,
|
|
7194
|
-
cancelable: err.cancelable,
|
|
7195
|
-
timeStamp: err.timeStamp
|
|
7196
|
-
};
|
|
7197
|
-
}
|
|
7198
|
-
var __typeError = (msg) => {
|
|
7199
|
-
throw TypeError(msg);
|
|
7200
|
-
}, __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg), __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method), _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect, EventSource = class extends EventTarget {
|
|
7201
|
-
constructor(url, eventSourceInitDict) {
|
|
7202
|
-
var _a, _b;
|
|
7203
|
-
super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
|
|
7204
|
-
var _a2;
|
|
7205
|
-
__privateGet(this, _parser).reset();
|
|
7206
|
-
let { body, redirected, status, headers } = response;
|
|
7207
|
-
if (status === 204) {
|
|
7208
|
-
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
|
|
7209
|
-
return;
|
|
7210
|
-
}
|
|
7211
|
-
if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
|
|
7212
|
-
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
|
|
7213
|
-
return;
|
|
7214
|
-
}
|
|
7215
|
-
if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
|
|
7216
|
-
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
|
|
7217
|
-
return;
|
|
7218
|
-
}
|
|
7219
|
-
if (__privateGet(this, _readyState) === this.CLOSED)
|
|
7220
|
-
return;
|
|
7221
|
-
__privateSet(this, _readyState, this.OPEN);
|
|
7222
|
-
let openEvent = new Event("open");
|
|
7223
|
-
if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
|
|
7224
|
-
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
|
|
7225
|
-
return;
|
|
7226
|
-
}
|
|
7227
|
-
let decoder = new TextDecoder(), reader = body.getReader(), open2 = !0;
|
|
7228
|
-
do {
|
|
7229
|
-
let { done, value } = await reader.read();
|
|
7230
|
-
value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open2 = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
|
|
7231
|
-
} while (open2);
|
|
7232
|
-
}), __privateAdd(this, _onFetchError, (err) => {
|
|
7233
|
-
__privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
|
|
7234
|
-
}), __privateAdd(this, _onEvent, (event) => {
|
|
7235
|
-
typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
|
|
7236
|
-
let messageEvent = new MessageEvent(event.event || "message", {
|
|
7237
|
-
data: event.data,
|
|
7238
|
-
origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
|
|
7239
|
-
lastEventId: event.id || ""
|
|
7240
|
-
});
|
|
7241
|
-
__privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
|
|
7242
|
-
}), __privateAdd(this, _onRetryChange, (value) => {
|
|
7243
|
-
__privateSet(this, _reconnectInterval, value);
|
|
7244
|
-
}), __privateAdd(this, _reconnect, () => {
|
|
7245
|
-
__privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
|
|
7246
|
-
});
|
|
7247
|
-
try {
|
|
7248
|
-
if (url instanceof URL)
|
|
7249
|
-
__privateSet(this, _url, url);
|
|
7250
|
-
else if (typeof url == "string")
|
|
7251
|
-
__privateSet(this, _url, new URL(url, getBaseURL()));
|
|
7252
|
-
else
|
|
7253
|
-
throw new Error("Invalid URL");
|
|
7254
|
-
} catch {
|
|
7255
|
-
throw syntaxError("An invalid or illegal string was specified");
|
|
7256
|
-
}
|
|
7257
|
-
__privateSet(this, _parser, createParser({
|
|
7258
|
-
onEvent: __privateGet(this, _onEvent),
|
|
7259
|
-
onRetry: __privateGet(this, _onRetryChange)
|
|
7260
|
-
})), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict?.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict?.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
|
|
7261
|
-
}
|
|
7262
|
-
/**
|
|
7263
|
-
* Returns the state of this EventSource object's connection. It can have the values described below.
|
|
7264
|
-
*
|
|
7265
|
-
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
|
|
7266
|
-
*
|
|
7267
|
-
* Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
|
|
7268
|
-
* defined in the TypeScript `dom` library.
|
|
7269
|
-
*
|
|
7270
|
-
* @public
|
|
7271
|
-
*/
|
|
7272
|
-
get readyState() {
|
|
7273
|
-
return __privateGet(this, _readyState);
|
|
7274
|
-
}
|
|
7275
|
-
/**
|
|
7276
|
-
* Returns the URL providing the event stream.
|
|
7277
|
-
*
|
|
7278
|
-
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
|
|
7279
|
-
*
|
|
7280
|
-
* @public
|
|
7281
|
-
*/
|
|
7282
|
-
get url() {
|
|
7283
|
-
return __privateGet(this, _url).href;
|
|
7284
|
-
}
|
|
7285
|
-
/**
|
|
7286
|
-
* Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
|
|
7287
|
-
*
|
|
7288
|
-
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
|
|
7289
|
-
*/
|
|
7290
|
-
get withCredentials() {
|
|
7291
|
-
return __privateGet(this, _withCredentials);
|
|
7292
|
-
}
|
|
7293
|
-
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
|
|
7294
|
-
get onerror() {
|
|
7295
|
-
return __privateGet(this, _onError);
|
|
7296
|
-
}
|
|
7297
|
-
set onerror(value) {
|
|
7298
|
-
__privateSet(this, _onError, value);
|
|
7299
|
-
}
|
|
7300
|
-
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
|
|
7301
|
-
get onmessage() {
|
|
7302
|
-
return __privateGet(this, _onMessage);
|
|
7303
|
-
}
|
|
7304
|
-
set onmessage(value) {
|
|
7305
|
-
__privateSet(this, _onMessage, value);
|
|
7306
|
-
}
|
|
7307
|
-
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
|
|
7308
|
-
get onopen() {
|
|
7309
|
-
return __privateGet(this, _onOpen);
|
|
7310
|
-
}
|
|
7311
|
-
set onopen(value) {
|
|
7312
|
-
__privateSet(this, _onOpen, value);
|
|
7313
|
-
}
|
|
7314
|
-
addEventListener(type, listener, options) {
|
|
7315
|
-
let listen = listener;
|
|
7316
|
-
super.addEventListener(type, listen, options);
|
|
7317
|
-
}
|
|
7318
|
-
removeEventListener(type, listener, options) {
|
|
7319
|
-
let listen = listener;
|
|
7320
|
-
super.removeEventListener(type, listen, options);
|
|
7321
|
-
}
|
|
7322
|
-
/**
|
|
7323
|
-
* Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
|
|
7324
|
-
*
|
|
7325
|
-
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
|
|
7326
|
-
*
|
|
7327
|
-
* @public
|
|
7328
|
-
*/
|
|
7329
|
-
close() {
|
|
7330
|
-
__privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
|
|
7331
|
-
}
|
|
7332
|
-
};
|
|
7333
|
-
_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
|
|
7334
|
-
* Connect to the given URL and start receiving events
|
|
7335
|
-
*
|
|
7336
|
-
* @internal
|
|
7337
|
-
*/
|
|
7338
|
-
connect_fn = function() {
|
|
7339
|
-
__privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
|
|
7340
|
-
}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
|
|
7341
|
-
* Get request options for the `fetch()` request
|
|
7342
|
-
*
|
|
7343
|
-
* @returns The request options
|
|
7344
|
-
* @internal
|
|
7345
|
-
*/
|
|
7346
|
-
getRequestOptions_fn = function() {
|
|
7347
|
-
var _a;
|
|
7348
|
-
let init = {
|
|
7349
|
-
// [spec] Let `corsAttributeState` be `Anonymous`…
|
|
7350
|
-
// [spec] …will have their mode set to "cors"…
|
|
7351
|
-
mode: "cors",
|
|
7352
|
-
redirect: "follow",
|
|
7353
|
-
headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
|
|
7354
|
-
cache: "no-store",
|
|
7355
|
-
signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
|
|
7356
|
-
};
|
|
7357
|
-
return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
|
|
7358
|
-
}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
|
|
7359
|
-
* Handles the process referred to in the EventSource specification as "failing a connection".
|
|
7360
|
-
*
|
|
7361
|
-
* @param error - The error causing the connection to fail
|
|
7362
|
-
* @param code - The HTTP status code, if available
|
|
7363
|
-
* @internal
|
|
7364
|
-
*/
|
|
7365
|
-
failConnection_fn = function(message, code) {
|
|
7366
|
-
var _a;
|
|
7367
|
-
__privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
|
|
7368
|
-
let errorEvent = new ErrorEvent("error", { code, message });
|
|
7369
|
-
(_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
|
|
7370
|
-
}, /**
|
|
7371
|
-
* Schedules a reconnection attempt against the EventSource endpoint.
|
|
7372
|
-
*
|
|
7373
|
-
* @param message - The error causing the connection to fail
|
|
7374
|
-
* @param code - The HTTP status code, if available
|
|
7375
|
-
* @internal
|
|
7376
|
-
*/
|
|
7377
|
-
scheduleReconnect_fn = function(message, code) {
|
|
7378
|
-
var _a;
|
|
7379
|
-
if (__privateGet(this, _readyState) === this.CLOSED)
|
|
7380
|
-
return;
|
|
7381
|
-
__privateSet(this, _readyState, this.CONNECTING);
|
|
7382
|
-
let errorEvent = new ErrorEvent("error", { code, message });
|
|
7383
|
-
(_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
|
|
7384
|
-
}, _reconnect = /* @__PURE__ */ new WeakMap(), /**
|
|
7385
|
-
* ReadyState representing an EventSource currently trying to connect
|
|
7386
|
-
*
|
|
7387
|
-
* @public
|
|
7388
|
-
*/
|
|
7389
|
-
EventSource.CONNECTING = 0, /**
|
|
7390
|
-
* ReadyState representing an EventSource connection that is open (eg connected)
|
|
7391
|
-
*
|
|
7392
|
-
* @public
|
|
7393
|
-
*/
|
|
7394
|
-
EventSource.OPEN = 1, /**
|
|
7395
|
-
* ReadyState representing an EventSource connection that is closed (eg disconnected)
|
|
7396
|
-
*
|
|
7397
|
-
* @public
|
|
7398
|
-
*/
|
|
7399
|
-
EventSource.CLOSED = 2;
|
|
7400
|
-
function getBaseURL() {
|
|
7401
|
-
let doc = "document" in globalThis ? globalThis.document : void 0;
|
|
7402
|
-
return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
|
|
7403
|
-
}
|
|
7404
|
-
|
|
7405
|
-
// node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
|
|
7406
|
-
var SseError = class extends Error {
|
|
7407
|
-
constructor(code, message, event) {
|
|
7408
|
-
super(`SSE error: ${message}`), this.code = code, this.event = event;
|
|
7409
|
-
}
|
|
7410
|
-
}, SSEClientTransport = class {
|
|
7411
|
-
constructor(url, opts) {
|
|
7412
|
-
this._url = url, this._resourceMetadataUrl = void 0, this._scope = void 0, this._eventSourceInit = opts?.eventSourceInit, this._requestInit = opts?.requestInit, this._authProvider = opts?.authProvider, this._fetch = opts?.fetch, this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
|
|
7413
|
-
}
|
|
7414
|
-
async _authThenStart() {
|
|
7415
|
-
if (!this._authProvider)
|
|
7416
|
-
throw new UnauthorizedError("No auth provider");
|
|
7417
|
-
let result;
|
|
7418
|
-
try {
|
|
7419
|
-
result = await auth(this._authProvider, {
|
|
7420
|
-
serverUrl: this._url,
|
|
7421
|
-
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
7422
|
-
scope: this._scope,
|
|
7423
|
-
fetchFn: this._fetchWithInit
|
|
7424
|
-
});
|
|
7425
|
-
} catch (error) {
|
|
7426
|
-
throw this.onerror?.(error), error;
|
|
7427
|
-
}
|
|
7428
|
-
if (result !== "AUTHORIZED")
|
|
7429
|
-
throw new UnauthorizedError();
|
|
7430
|
-
return await this._startOrAuth();
|
|
7431
|
-
}
|
|
7432
|
-
async _commonHeaders() {
|
|
7433
|
-
let headers = {};
|
|
7434
|
-
if (this._authProvider) {
|
|
7435
|
-
let tokens = await this._authProvider.tokens();
|
|
7436
|
-
tokens && (headers.Authorization = `Bearer ${tokens.access_token}`);
|
|
7437
|
-
}
|
|
7438
|
-
this._protocolVersion && (headers["mcp-protocol-version"] = this._protocolVersion);
|
|
7439
|
-
let extraHeaders = normalizeHeaders(this._requestInit?.headers);
|
|
7440
|
-
return new Headers({
|
|
7441
|
-
...headers,
|
|
7442
|
-
...extraHeaders
|
|
7443
|
-
});
|
|
7444
|
-
}
|
|
7445
|
-
_startOrAuth() {
|
|
7446
|
-
let fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
|
|
7447
|
-
return new Promise((resolve2, reject) => {
|
|
7448
|
-
this._eventSource = new EventSource(this._url.href, {
|
|
7449
|
-
...this._eventSourceInit,
|
|
7450
|
-
fetch: async (url, init) => {
|
|
7451
|
-
let headers = await this._commonHeaders();
|
|
7452
|
-
headers.set("Accept", "text/event-stream");
|
|
7453
|
-
let response = await fetchImpl(url, {
|
|
7454
|
-
...init,
|
|
7455
|
-
headers
|
|
7456
|
-
});
|
|
7457
|
-
if (response.status === 401 && response.headers.has("www-authenticate")) {
|
|
7458
|
-
let { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
7459
|
-
this._resourceMetadataUrl = resourceMetadataUrl, this._scope = scope;
|
|
7460
|
-
}
|
|
7461
|
-
return response;
|
|
7462
|
-
}
|
|
7463
|
-
}), this._abortController = new AbortController(), this._eventSource.onerror = (event) => {
|
|
7464
|
-
if (event.code === 401 && this._authProvider) {
|
|
7465
|
-
this._authThenStart().then(resolve2, reject);
|
|
7466
|
-
return;
|
|
7467
|
-
}
|
|
7468
|
-
let error = new SseError(event.code, event.message, event);
|
|
7469
|
-
reject(error), this.onerror?.(error);
|
|
7470
|
-
}, this._eventSource.onopen = () => {
|
|
7471
|
-
}, this._eventSource.addEventListener("endpoint", (event) => {
|
|
7472
|
-
let messageEvent = event;
|
|
7473
|
-
try {
|
|
7474
|
-
if (this._endpoint = new URL(messageEvent.data, this._url), this._endpoint.origin !== this._url.origin)
|
|
7475
|
-
throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
|
|
7476
|
-
} catch (error) {
|
|
7477
|
-
reject(error), this.onerror?.(error), this.close();
|
|
7478
|
-
return;
|
|
7479
|
-
}
|
|
7480
|
-
resolve2();
|
|
7481
|
-
}), this._eventSource.onmessage = (event) => {
|
|
7482
|
-
let messageEvent = event, message;
|
|
7483
|
-
try {
|
|
7484
|
-
message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
|
|
7485
|
-
} catch (error) {
|
|
7486
|
-
this.onerror?.(error);
|
|
7487
|
-
return;
|
|
7488
|
-
}
|
|
7489
|
-
this.onmessage?.(message);
|
|
7490
|
-
};
|
|
6805
|
+
this._process.stdin.write(json) ? resolve() : this._process.stdin.once("drain", resolve);
|
|
7491
6806
|
});
|
|
7492
6807
|
}
|
|
7493
|
-
async start() {
|
|
7494
|
-
if (this._eventSource)
|
|
7495
|
-
throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
7496
|
-
return await this._startOrAuth();
|
|
7497
|
-
}
|
|
7498
|
-
/**
|
|
7499
|
-
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
|
|
7500
|
-
*/
|
|
7501
|
-
async finishAuth(authorizationCode) {
|
|
7502
|
-
if (!this._authProvider)
|
|
7503
|
-
throw new UnauthorizedError("No auth provider");
|
|
7504
|
-
if (await auth(this._authProvider, {
|
|
7505
|
-
serverUrl: this._url,
|
|
7506
|
-
authorizationCode,
|
|
7507
|
-
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
7508
|
-
scope: this._scope,
|
|
7509
|
-
fetchFn: this._fetchWithInit
|
|
7510
|
-
}) !== "AUTHORIZED")
|
|
7511
|
-
throw new UnauthorizedError("Failed to authorize");
|
|
7512
|
-
}
|
|
7513
|
-
async close() {
|
|
7514
|
-
this._abortController?.abort(), this._eventSource?.close(), this.onclose?.();
|
|
7515
|
-
}
|
|
7516
|
-
async send(message) {
|
|
7517
|
-
if (!this._endpoint)
|
|
7518
|
-
throw new Error("Not connected");
|
|
7519
|
-
try {
|
|
7520
|
-
let headers = await this._commonHeaders();
|
|
7521
|
-
headers.set("content-type", "application/json");
|
|
7522
|
-
let init = {
|
|
7523
|
-
...this._requestInit,
|
|
7524
|
-
method: "POST",
|
|
7525
|
-
headers,
|
|
7526
|
-
body: JSON.stringify(message),
|
|
7527
|
-
signal: this._abortController?.signal
|
|
7528
|
-
}, response = await (this._fetch ?? fetch)(this._endpoint, init);
|
|
7529
|
-
if (!response.ok) {
|
|
7530
|
-
let text = await response.text().catch(() => null);
|
|
7531
|
-
if (response.status === 401 && this._authProvider) {
|
|
7532
|
-
let { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
7533
|
-
if (this._resourceMetadataUrl = resourceMetadataUrl, this._scope = scope, await auth(this._authProvider, {
|
|
7534
|
-
serverUrl: this._url,
|
|
7535
|
-
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
7536
|
-
scope: this._scope,
|
|
7537
|
-
fetchFn: this._fetchWithInit
|
|
7538
|
-
}) !== "AUTHORIZED")
|
|
7539
|
-
throw new UnauthorizedError();
|
|
7540
|
-
return this.send(message);
|
|
7541
|
-
}
|
|
7542
|
-
throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
|
|
7543
|
-
}
|
|
7544
|
-
await response.body?.cancel();
|
|
7545
|
-
} catch (error) {
|
|
7546
|
-
throw this.onerror?.(error), error;
|
|
7547
|
-
}
|
|
7548
|
-
}
|
|
7549
|
-
setProtocolVersion(version) {
|
|
7550
|
-
this._protocolVersion = version;
|
|
7551
|
-
}
|
|
7552
6808
|
};
|
|
7553
6809
|
|
|
7554
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/npx-resolver.js
|
|
7555
|
-
import { existsSync, readFileSync, realpathSync, readdirSync, statSync, writeFileSync, renameSync, mkdirSync, openSync, readSync, closeSync } from "node:fs";
|
|
7556
|
-
import { join, dirname, extname, resolve, sep } from "node:path";
|
|
7557
|
-
import { spawn as spawn2, spawnSync } from "node:child_process";
|
|
7558
|
-
var CACHE_VERSION = 1, CACHE_TTL_MS = 1440 * 60 * 1e3;
|
|
7559
|
-
async function resolveNpxBinary(command, args) {
|
|
7560
|
-
let parsed = command === "npx" ? parseNpxArgs(args) : command === "npm" ? parseNpmExecArgs(args) : null;
|
|
7561
|
-
if (!parsed)
|
|
7562
|
-
return null;
|
|
7563
|
-
let cacheKey = JSON.stringify([command, ...args]), cached = loadCache()?.entries?.[cacheKey];
|
|
7564
|
-
if (cached && Date.now() - cached.resolvedAt < CACHE_TTL_MS && existsSync(cached.resolvedBin))
|
|
7565
|
-
return { binPath: cached.resolvedBin, extraArgs: parsed.extraArgs, isJs: cached.isJs };
|
|
7566
|
-
let resolved = resolveFromNpmCache(parsed.packageSpec, parsed.binName);
|
|
7567
|
-
if (resolved)
|
|
7568
|
-
return saveCacheEntry(cacheKey, resolved), { binPath: resolved.resolvedBin, extraArgs: parsed.extraArgs, isJs: resolved.isJs };
|
|
7569
|
-
await forceNpxCache(parsed.packageSpec);
|
|
7570
|
-
let resolvedAfterInstall = resolveFromNpmCache(parsed.packageSpec, parsed.binName);
|
|
7571
|
-
return resolvedAfterInstall ? (saveCacheEntry(cacheKey, resolvedAfterInstall), { binPath: resolvedAfterInstall.resolvedBin, extraArgs: parsed.extraArgs, isJs: resolvedAfterInstall.isJs }) : null;
|
|
7572
|
-
}
|
|
7573
|
-
function parseNpxArgs(args) {
|
|
7574
|
-
let separatorIndex = args.indexOf("--"), before = separatorIndex >= 0 ? args.slice(0, separatorIndex) : args, after = separatorIndex >= 0 ? args.slice(separatorIndex + 1) : [], positionals = [], packageSpec, sawPackageFlag = !1, foundFirstPositional = !1;
|
|
7575
|
-
for (let i2 = 0; i2 < before.length; i2++) {
|
|
7576
|
-
let arg = before[i2];
|
|
7577
|
-
if (foundFirstPositional) {
|
|
7578
|
-
positionals.push(arg);
|
|
7579
|
-
continue;
|
|
7580
|
-
}
|
|
7581
|
-
if (!(arg === "-y" || arg === "--yes")) {
|
|
7582
|
-
if (arg === "-p" || arg === "--package") {
|
|
7583
|
-
let value = before[i2 + 1];
|
|
7584
|
-
if (!value || value.startsWith("-"))
|
|
7585
|
-
return null;
|
|
7586
|
-
packageSpec || (packageSpec = value), sawPackageFlag = !0, i2++;
|
|
7587
|
-
continue;
|
|
7588
|
-
}
|
|
7589
|
-
if (arg.startsWith("--package=")) {
|
|
7590
|
-
let value = arg.slice(10);
|
|
7591
|
-
if (!value)
|
|
7592
|
-
return null;
|
|
7593
|
-
packageSpec || (packageSpec = value), sawPackageFlag = !0;
|
|
7594
|
-
continue;
|
|
7595
|
-
}
|
|
7596
|
-
if (arg.startsWith("-"))
|
|
7597
|
-
return null;
|
|
7598
|
-
positionals.push(arg), foundFirstPositional = !0;
|
|
7599
|
-
}
|
|
7600
|
-
}
|
|
7601
|
-
let separatedAfter = separatorIndex >= 0 && after.length > 0 ? ["--", ...after] : after;
|
|
7602
|
-
if (sawPackageFlag) {
|
|
7603
|
-
let binName = positionals[0];
|
|
7604
|
-
if (!packageSpec || !binName)
|
|
7605
|
-
return null;
|
|
7606
|
-
let extraArgs2 = positionals.slice(1).concat(separatedAfter);
|
|
7607
|
-
return { packageSpec, binName, extraArgs: extraArgs2 };
|
|
7608
|
-
}
|
|
7609
|
-
let packagePositional = positionals[0];
|
|
7610
|
-
if (!packagePositional)
|
|
7611
|
-
return null;
|
|
7612
|
-
let extraArgs = positionals.slice(1).concat(separatedAfter);
|
|
7613
|
-
return { packageSpec: packagePositional, extraArgs };
|
|
7614
|
-
}
|
|
7615
|
-
function parseNpmExecArgs(args) {
|
|
7616
|
-
if (args[0] !== "exec")
|
|
7617
|
-
return null;
|
|
7618
|
-
let execArgs = args.slice(1), separatorIndex = execArgs.indexOf("--");
|
|
7619
|
-
if (separatorIndex < 0)
|
|
7620
|
-
return null;
|
|
7621
|
-
let before = execArgs.slice(0, separatorIndex), after = execArgs.slice(separatorIndex + 1), packageSpec;
|
|
7622
|
-
for (let i2 = 0; i2 < before.length; i2++) {
|
|
7623
|
-
let arg = before[i2];
|
|
7624
|
-
if (!(arg === "-y" || arg === "--yes")) {
|
|
7625
|
-
if (arg === "--package") {
|
|
7626
|
-
let value = before[i2 + 1];
|
|
7627
|
-
if (!value || value.startsWith("-"))
|
|
7628
|
-
return null;
|
|
7629
|
-
packageSpec || (packageSpec = value), i2++;
|
|
7630
|
-
continue;
|
|
7631
|
-
}
|
|
7632
|
-
if (arg.startsWith("--package=")) {
|
|
7633
|
-
let value = arg.slice(10);
|
|
7634
|
-
if (!value)
|
|
7635
|
-
return null;
|
|
7636
|
-
packageSpec || (packageSpec = value);
|
|
7637
|
-
continue;
|
|
7638
|
-
}
|
|
7639
|
-
if (arg.startsWith("-"))
|
|
7640
|
-
return null;
|
|
7641
|
-
}
|
|
7642
|
-
}
|
|
7643
|
-
let binName = after[0];
|
|
7644
|
-
if (!packageSpec || !binName)
|
|
7645
|
-
return null;
|
|
7646
|
-
let extraArgs = after.slice(1);
|
|
7647
|
-
return { packageSpec, binName, extraArgs };
|
|
7648
|
-
}
|
|
7649
|
-
function resolveFromNpmCache(packageSpec, binName) {
|
|
7650
|
-
let cacheDir = getNpmCacheDir();
|
|
7651
|
-
if (!cacheDir)
|
|
7652
|
-
return null;
|
|
7653
|
-
let packageName = extractPackageName(packageSpec);
|
|
7654
|
-
if (!packageName)
|
|
7655
|
-
return null;
|
|
7656
|
-
let packageDir = findCachedPackageDir(cacheDir, packageName);
|
|
7657
|
-
if (!packageDir)
|
|
7658
|
-
return null;
|
|
7659
|
-
let packageJsonPath = join(packageDir, "package.json");
|
|
7660
|
-
if (!existsSync(packageJsonPath))
|
|
7661
|
-
return null;
|
|
7662
|
-
let pkg = null;
|
|
7663
|
-
try {
|
|
7664
|
-
pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
|
|
7665
|
-
} catch {
|
|
7666
|
-
return null;
|
|
7667
|
-
}
|
|
7668
|
-
let binField = pkg?.bin;
|
|
7669
|
-
if (!binField)
|
|
7670
|
-
return null;
|
|
7671
|
-
let candidates = buildBinCandidates(packageName, binName), chosenBinName, binRel;
|
|
7672
|
-
if (typeof binField == "string")
|
|
7673
|
-
chosenBinName = defaultBinName(packageName), binRel = binField;
|
|
7674
|
-
else {
|
|
7675
|
-
for (let candidate of candidates)
|
|
7676
|
-
if (binField[candidate]) {
|
|
7677
|
-
chosenBinName = candidate, binRel = binField[candidate];
|
|
7678
|
-
break;
|
|
7679
|
-
}
|
|
7680
|
-
if (!binRel) {
|
|
7681
|
-
let firstEntry = Object.entries(binField)[0];
|
|
7682
|
-
firstEntry && (chosenBinName = firstEntry[0], binRel = firstEntry[1]);
|
|
7683
|
-
}
|
|
7684
|
-
}
|
|
7685
|
-
if (!binRel)
|
|
7686
|
-
return null;
|
|
7687
|
-
let nodeModulesDir = findNodeModulesDir(packageDir), binLink = chosenBinName ? join(nodeModulesDir, ".bin", chosenBinName) : null, resolvedBin = binLink && existsSync(binLink) ? safeRealpath(binLink) : "";
|
|
7688
|
-
if (!resolvedBin && (resolvedBin = resolve(packageDir, binRel), !existsSync(resolvedBin)))
|
|
7689
|
-
return null;
|
|
7690
|
-
let isJs = detectJsBinary(resolvedBin);
|
|
7691
|
-
return {
|
|
7692
|
-
resolvedBin,
|
|
7693
|
-
resolvedAt: Date.now(),
|
|
7694
|
-
packageVersion: pkg?.version,
|
|
7695
|
-
isJs
|
|
7696
|
-
};
|
|
7697
|
-
}
|
|
7698
|
-
var FORCE_CACHE_TIMEOUT_MS = 3e4;
|
|
7699
|
-
async function forceNpxCache(packageSpec) {
|
|
7700
|
-
try {
|
|
7701
|
-
await new Promise((resolve2, reject) => {
|
|
7702
|
-
let proc = spawn2("npm", ["exec", "--yes", "--package", packageSpec, "--", "node", "-e", "1"], { stdio: "ignore" }), timer = setTimeout(() => {
|
|
7703
|
-
proc.kill(), reject(new Error("timeout"));
|
|
7704
|
-
}, FORCE_CACHE_TIMEOUT_MS);
|
|
7705
|
-
timer.unref(), proc.on("close", () => {
|
|
7706
|
-
clearTimeout(timer), resolve2();
|
|
7707
|
-
}), proc.on("error", (err) => {
|
|
7708
|
-
clearTimeout(timer), reject(err);
|
|
7709
|
-
});
|
|
7710
|
-
});
|
|
7711
|
-
} catch {
|
|
7712
|
-
}
|
|
7713
|
-
}
|
|
7714
|
-
function buildBinCandidates(packageName, explicitBin) {
|
|
7715
|
-
let candidates = [];
|
|
7716
|
-
if (explicitBin && candidates.push(explicitBin), packageName.startsWith("@")) {
|
|
7717
|
-
let namePart = packageName.split("/")[1] ?? "", scopePart = packageName.split("/")[0]?.replace("@", "") ?? "";
|
|
7718
|
-
namePart && candidates.push(namePart), scopePart && namePart && candidates.push(`${scopePart}-${namePart}`);
|
|
7719
|
-
} else
|
|
7720
|
-
candidates.push(packageName);
|
|
7721
|
-
return [...new Set(candidates.filter(Boolean))];
|
|
7722
|
-
}
|
|
7723
|
-
function extractPackageName(spec) {
|
|
7724
|
-
let trimmed = spec.trim();
|
|
7725
|
-
if (!trimmed)
|
|
7726
|
-
return null;
|
|
7727
|
-
if (trimmed.startsWith("@")) {
|
|
7728
|
-
let slashIndex = trimmed.indexOf("/");
|
|
7729
|
-
if (slashIndex < 0)
|
|
7730
|
-
return null;
|
|
7731
|
-
let atIndex2 = trimmed.lastIndexOf("@");
|
|
7732
|
-
return atIndex2 > slashIndex ? trimmed.slice(0, atIndex2) : trimmed;
|
|
7733
|
-
}
|
|
7734
|
-
let atIndex = trimmed.indexOf("@");
|
|
7735
|
-
return atIndex >= 0 ? trimmed.slice(0, atIndex) : trimmed;
|
|
7736
|
-
}
|
|
7737
|
-
function defaultBinName(packageName) {
|
|
7738
|
-
return packageName.startsWith("@") ? packageName.split("/")[1] ?? packageName.replace("@", "").replace("/", "-") : packageName;
|
|
7739
|
-
}
|
|
7740
|
-
function findCachedPackageDir(cacheDir, packageName) {
|
|
7741
|
-
let npxDir = join(cacheDir, "_npx");
|
|
7742
|
-
if (!existsSync(npxDir))
|
|
7743
|
-
return null;
|
|
7744
|
-
let packagePathParts = packageName.startsWith("@") ? packageName.split("/") : [packageName], candidates = readdirSync(npxDir, { withFileTypes: !0 }).filter((entry) => entry.isDirectory()).map((entry) => {
|
|
7745
|
-
let full = join(npxDir, entry.name), mtime = safeStatMtime(full);
|
|
7746
|
-
return { name: entry.name, mtime };
|
|
7747
|
-
}).sort((a2, b2) => b2.mtime - a2.mtime);
|
|
7748
|
-
for (let entry of candidates) {
|
|
7749
|
-
let pkgDir = join(npxDir, entry.name, "node_modules", ...packagePathParts);
|
|
7750
|
-
if (existsSync(join(pkgDir, "package.json")))
|
|
7751
|
-
return pkgDir;
|
|
7752
|
-
}
|
|
7753
|
-
return null;
|
|
7754
|
-
}
|
|
7755
|
-
function findNodeModulesDir(packageDir) {
|
|
7756
|
-
let parts = packageDir.split(sep), idx = parts.lastIndexOf("node_modules");
|
|
7757
|
-
return idx >= 0 ? parts.slice(0, idx + 1).join(sep) : join(packageDir, "..");
|
|
7758
|
-
}
|
|
7759
|
-
function detectJsBinary(binPath) {
|
|
7760
|
-
let ext = extname(binPath).toLowerCase();
|
|
7761
|
-
if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
|
|
7762
|
-
return !0;
|
|
7763
|
-
try {
|
|
7764
|
-
let fd = openSync(binPath, "r");
|
|
7765
|
-
try {
|
|
7766
|
-
let buf = Buffer.alloc(256);
|
|
7767
|
-
readSync(fd, buf, 0, 256, 0);
|
|
7768
|
-
let firstLine = buf.toString("utf-8").split(`
|
|
7769
|
-
`)[0] ?? "";
|
|
7770
|
-
return firstLine.startsWith("#!") && firstLine.includes("node");
|
|
7771
|
-
} finally {
|
|
7772
|
-
closeSync(fd);
|
|
7773
|
-
}
|
|
7774
|
-
} catch {
|
|
7775
|
-
return !1;
|
|
7776
|
-
}
|
|
7777
|
-
}
|
|
7778
|
-
var npmCacheDirCached;
|
|
7779
|
-
function getNpmCacheDir() {
|
|
7780
|
-
if (npmCacheDirCached !== void 0)
|
|
7781
|
-
return npmCacheDirCached;
|
|
7782
|
-
if (process.env.NPM_CONFIG_CACHE)
|
|
7783
|
-
return npmCacheDirCached = process.env.NPM_CONFIG_CACHE, npmCacheDirCached;
|
|
7784
|
-
try {
|
|
7785
|
-
let result = spawnSync("npm", ["config", "get", "cache"], { encoding: "utf-8" });
|
|
7786
|
-
if (result.status === 0)
|
|
7787
|
-
return npmCacheDirCached = String(result.stdout).trim() || null, npmCacheDirCached;
|
|
7788
|
-
} catch {
|
|
7789
|
-
return npmCacheDirCached = null, null;
|
|
7790
|
-
}
|
|
7791
|
-
return npmCacheDirCached = null, null;
|
|
7792
|
-
}
|
|
7793
|
-
function getNpxCachePath() {
|
|
7794
|
-
return getAgentPath("mcp-npx-cache.json");
|
|
7795
|
-
}
|
|
7796
|
-
function loadCache() {
|
|
7797
|
-
let cachePath = getNpxCachePath();
|
|
7798
|
-
if (!existsSync(cachePath))
|
|
7799
|
-
return null;
|
|
7800
|
-
try {
|
|
7801
|
-
let raw = JSON.parse(readFileSync(cachePath, "utf-8"));
|
|
7802
|
-
return !raw || typeof raw != "object" || raw.version !== CACHE_VERSION || !raw.entries || typeof raw.entries != "object" ? null : raw;
|
|
7803
|
-
} catch {
|
|
7804
|
-
return null;
|
|
7805
|
-
}
|
|
7806
|
-
}
|
|
7807
|
-
function saveCacheEntry(key, entry) {
|
|
7808
|
-
let cachePath = getNpxCachePath(), dir = dirname(cachePath);
|
|
7809
|
-
mkdirSync(dir, { recursive: !0 });
|
|
7810
|
-
let merged = { version: CACHE_VERSION, entries: {} };
|
|
7811
|
-
try {
|
|
7812
|
-
if (existsSync(cachePath)) {
|
|
7813
|
-
let existing = JSON.parse(readFileSync(cachePath, "utf-8"));
|
|
7814
|
-
existing && existing.version === CACHE_VERSION && existing.entries && (merged.entries = { ...existing.entries });
|
|
7815
|
-
}
|
|
7816
|
-
} catch {
|
|
7817
|
-
}
|
|
7818
|
-
merged.entries[key] = entry;
|
|
7819
|
-
let tmpPath = `${cachePath}.${process.pid}.tmp`;
|
|
7820
|
-
writeFileSync(tmpPath, JSON.stringify(merged, null, 2), "utf-8"), renameSync(tmpPath, cachePath);
|
|
7821
|
-
}
|
|
7822
|
-
function safeRealpath(path) {
|
|
7823
|
-
try {
|
|
7824
|
-
return realpathSync(path);
|
|
7825
|
-
} catch {
|
|
7826
|
-
return "";
|
|
7827
|
-
}
|
|
7828
|
-
}
|
|
7829
|
-
function safeStatMtime(path) {
|
|
7830
|
-
try {
|
|
7831
|
-
return statSync(path).mtimeMs;
|
|
7832
|
-
} catch {
|
|
7833
|
-
return 0;
|
|
7834
|
-
}
|
|
7835
|
-
}
|
|
7836
|
-
|
|
7837
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/sampling-handler.js
|
|
7838
|
-
import { complete } from "@ashx-j/lunr-ai/compat";
|
|
7839
|
-
function registerSamplingHandler(client, options) {
|
|
7840
|
-
client.setRequestHandler(CreateMessageRequestSchema, (request) => handleSamplingRequest(options, request));
|
|
7841
|
-
}
|
|
7842
|
-
async function handleSamplingRequest(options, request) {
|
|
7843
|
-
let params = request.params;
|
|
7844
|
-
if ("task" in params && params.task)
|
|
7845
|
-
throw new Error("MCP sampling tasks are not supported");
|
|
7846
|
-
if (params.includeContext && params.includeContext !== "none")
|
|
7847
|
-
throw new Error("MCP sampling context inclusion is not supported");
|
|
7848
|
-
if (params.tools?.length)
|
|
7849
|
-
throw new Error("MCP sampling tool use is not supported");
|
|
7850
|
-
if (params.toolChoice)
|
|
7851
|
-
throw new Error("MCP sampling tool choice is not supported");
|
|
7852
|
-
if (params.stopSequences?.length)
|
|
7853
|
-
throw new Error("MCP sampling stop sequences are not supported");
|
|
7854
|
-
let messages = params.messages.map(convertSamplingMessage), { model, apiKey, headers } = await resolveSamplingModel(options, params.modelPreferences);
|
|
7855
|
-
await confirmSampling(options, "Approve MCP sampling request", formatRequestApproval(options.serverName, `${model.provider}/${model.id}`, params.systemPrompt, messages));
|
|
7856
|
-
let result = await complete(model, {
|
|
7857
|
-
systemPrompt: params.systemPrompt,
|
|
7858
|
-
messages
|
|
7859
|
-
}, {
|
|
7860
|
-
apiKey,
|
|
7861
|
-
headers,
|
|
7862
|
-
maxTokens: params.maxTokens,
|
|
7863
|
-
temperature: params.temperature,
|
|
7864
|
-
metadata: params.metadata,
|
|
7865
|
-
signal: options.getSignal()
|
|
7866
|
-
}), converted = convertAssistantResult(result);
|
|
7867
|
-
return await confirmSampling(options, "Return MCP sampling response", formatResponseApproval(options.serverName, converted)), converted;
|
|
7868
|
-
}
|
|
7869
|
-
function formatRequestApproval(serverName, modelName, systemPrompt, messages) {
|
|
7870
|
-
let lines = [`${serverName} wants to sample ${messages.length} message${messages.length === 1 ? "" : "s"} with ${modelName}.`];
|
|
7871
|
-
systemPrompt && lines.push(`System: ${truncateAtWord(systemPrompt, 400)}`);
|
|
7872
|
-
for (let [index, message] of messages.entries())
|
|
7873
|
-
lines.push(`${index + 1}. ${message.role}: ${truncateAtWord(messageText(message), 400)}`);
|
|
7874
|
-
return lines.join(`
|
|
7875
|
-
|
|
7876
|
-
`);
|
|
7877
|
-
}
|
|
7878
|
-
function formatResponseApproval(serverName, response) {
|
|
7879
|
-
let text = response.content.type === "text" ? response.content.text : `[${response.content.type} content]`;
|
|
7880
|
-
return `${serverName} will receive this response from ${response.model}:
|
|
7881
|
-
|
|
7882
|
-
${truncateAtWord(text, 1e3)}`;
|
|
7883
|
-
}
|
|
7884
|
-
function messageText(message) {
|
|
7885
|
-
return typeof message.content == "string" ? message.content : message.content.map((block) => block.type === "text" ? block.text : block.type === "image" ? `[image: ${block.mimeType}]` : block.type === "thinking" ? "[thinking]" : block.type === "toolCall" ? `[tool call: ${block.name}]` : "[content]").join(`
|
|
7886
|
-
`);
|
|
7887
|
-
}
|
|
7888
|
-
async function resolveSamplingModel(options, modelPreferences) {
|
|
7889
|
-
let candidates = [], availableModels = options.modelRegistry.getAvailable();
|
|
7890
|
-
for (let hint of modelPreferences?.hints ?? []) {
|
|
7891
|
-
let normalizedHint = hint.name?.trim().toLowerCase();
|
|
7892
|
-
if (normalizedHint)
|
|
7893
|
-
for (let model of availableModels)
|
|
7894
|
-
[`${model.provider}/${model.id}`, model.id, model.name].some((name) => name.toLowerCase().includes(normalizedHint)) && addSamplingCandidate(candidates, model);
|
|
7895
|
-
}
|
|
7896
|
-
let currentModel = options.getCurrentModel();
|
|
7897
|
-
currentModel && addSamplingCandidate(candidates, currentModel);
|
|
7898
|
-
for (let model of availableModels)
|
|
7899
|
-
addSamplingCandidate(candidates, model);
|
|
7900
|
-
let errors = [];
|
|
7901
|
-
for (let model of candidates) {
|
|
7902
|
-
let auth2 = await options.modelRegistry.getApiKeyAndHeaders(model);
|
|
7903
|
-
if (auth2.ok === !1) {
|
|
7904
|
-
errors.push(`${model.provider}/${model.id}: ${auth2.error}`);
|
|
7905
|
-
continue;
|
|
7906
|
-
}
|
|
7907
|
-
return { model, apiKey: auth2.apiKey, headers: auth2.headers };
|
|
7908
|
-
}
|
|
7909
|
-
throw errors.length > 0 ? new Error(`No configured auth for MCP sampling model. ${errors.join("; ")}`) : new Error("No Pi model is available for MCP sampling");
|
|
7910
|
-
}
|
|
7911
|
-
function addSamplingCandidate(candidates, model) {
|
|
7912
|
-
candidates.some((candidate) => candidate.provider === model.provider && candidate.id === model.id) || candidates.push(model);
|
|
7913
|
-
}
|
|
7914
|
-
async function confirmSampling(options, title, message) {
|
|
7915
|
-
if (options.autoApprove)
|
|
7916
|
-
return;
|
|
7917
|
-
if (!options.ui)
|
|
7918
|
-
throw new Error("MCP sampling requires interactive approval. Set settings.samplingAutoApprove to true to allow it without UI.");
|
|
7919
|
-
if (!await options.ui.confirm(title, message))
|
|
7920
|
-
throw new Error("MCP sampling request was declined");
|
|
7921
|
-
}
|
|
7922
|
-
function convertSamplingMessage(message) {
|
|
7923
|
-
let blocks = Array.isArray(message.content) ? message.content : [message.content];
|
|
7924
|
-
return message.role === "user" ? {
|
|
7925
|
-
role: "user",
|
|
7926
|
-
content: blocks.map(convertUserContent),
|
|
7927
|
-
timestamp: Date.now()
|
|
7928
|
-
} : {
|
|
7929
|
-
role: "assistant",
|
|
7930
|
-
content: blocks.map(convertAssistantContent),
|
|
7931
|
-
api: "mcp-sampling",
|
|
7932
|
-
provider: "mcp",
|
|
7933
|
-
model: "sampling-request",
|
|
7934
|
-
usage: zeroUsage(),
|
|
7935
|
-
stopReason: "stop",
|
|
7936
|
-
timestamp: Date.now()
|
|
7937
|
-
};
|
|
7938
|
-
}
|
|
7939
|
-
function convertUserContent(block) {
|
|
7940
|
-
if (block.type === "text")
|
|
7941
|
-
return { type: "text", text: block.text };
|
|
7942
|
-
throw new Error(`MCP sampling ${block.type} content is not supported`);
|
|
7943
|
-
}
|
|
7944
|
-
function convertAssistantContent(block) {
|
|
7945
|
-
if (block.type === "text")
|
|
7946
|
-
return { type: "text", text: block.text };
|
|
7947
|
-
throw new Error(`MCP sampling assistant ${block.type} content is not supported`);
|
|
7948
|
-
}
|
|
7949
|
-
function convertAssistantResult(message) {
|
|
7950
|
-
if (message.stopReason === "error")
|
|
7951
|
-
throw new Error(message.errorMessage ?? "MCP sampling model call failed");
|
|
7952
|
-
if (message.stopReason === "aborted")
|
|
7953
|
-
throw new Error(message.errorMessage ?? "MCP sampling model call was aborted");
|
|
7954
|
-
let text = message.content.map((block) => {
|
|
7955
|
-
if (block.type === "text")
|
|
7956
|
-
return block.text;
|
|
7957
|
-
if (block.type !== "thinking")
|
|
7958
|
-
throw new Error(`MCP sampling result ${block.type} content is not supported`);
|
|
7959
|
-
}).filter((value) => value !== void 0).join(`
|
|
7960
|
-
|
|
7961
|
-
`).trim();
|
|
7962
|
-
if (!text)
|
|
7963
|
-
throw new Error("MCP sampling result did not contain text content");
|
|
7964
|
-
return {
|
|
7965
|
-
role: "assistant",
|
|
7966
|
-
content: { type: "text", text },
|
|
7967
|
-
model: `${message.provider}/${message.model}`,
|
|
7968
|
-
stopReason: mapStopReason(message.stopReason)
|
|
7969
|
-
};
|
|
7970
|
-
}
|
|
7971
|
-
function mapStopReason(reason) {
|
|
7972
|
-
return reason === "stop" ? "endTurn" : reason === "length" ? "maxTokens" : reason === "toolUse" ? "toolUse" : reason;
|
|
7973
|
-
}
|
|
7974
|
-
function zeroUsage() {
|
|
7975
|
-
return {
|
|
7976
|
-
input: 0,
|
|
7977
|
-
output: 0,
|
|
7978
|
-
cacheRead: 0,
|
|
7979
|
-
cacheWrite: 0,
|
|
7980
|
-
totalTokens: 0,
|
|
7981
|
-
cost: {
|
|
7982
|
-
input: 0,
|
|
7983
|
-
output: 0,
|
|
7984
|
-
cacheRead: 0,
|
|
7985
|
-
cacheWrite: 0,
|
|
7986
|
-
total: 0
|
|
7987
|
-
}
|
|
7988
|
-
};
|
|
7989
|
-
}
|
|
7990
|
-
|
|
7991
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/elicitation-handler.js
|
|
7992
|
-
import open from "open";
|
|
7993
|
-
function registerElicitationHandler(client, options) {
|
|
7994
|
-
client.setRequestHandler(ElicitRequestSchema, (request) => handleElicitationRequest(options, request));
|
|
7995
|
-
}
|
|
7996
|
-
async function handleElicitationRequest(options, request) {
|
|
7997
|
-
return request.params.mode === "url" ? handleUrlElicitation(options, request.params) : handleFormElicitation(options, request.params);
|
|
7998
|
-
}
|
|
7999
|
-
async function handleFormElicitation(options, params) {
|
|
8000
|
-
let decision = await options.ui.select(`MCP Input Request
|
|
8001
|
-
Server: ${options.serverName}
|
|
8002
|
-
|
|
8003
|
-
${params.message}`, ["Continue", "Decline"]);
|
|
8004
|
-
if (decision === void 0)
|
|
8005
|
-
return { action: "cancel" };
|
|
8006
|
-
if (decision === "Decline")
|
|
8007
|
-
return { action: "decline" };
|
|
8008
|
-
let values = {}, properties = Object.entries(params.requestedSchema.properties);
|
|
8009
|
-
for (let [name, schema] of properties) {
|
|
8010
|
-
let value = await collectValidField(options.ui, params, name, schema);
|
|
8011
|
-
if (!("value" in value))
|
|
8012
|
-
return { action: "cancel" };
|
|
8013
|
-
values[name] = value.value;
|
|
8014
|
-
}
|
|
8015
|
-
for (; ; ) {
|
|
8016
|
-
let content = coerceAndValidateFormValues(params, values), action = await options.ui.select(formatReview(options.serverName, properties, content), properties.length > 0 ? ["Submit", "Edit", "Decline"] : ["Submit", "Decline"]);
|
|
8017
|
-
if (action === void 0)
|
|
8018
|
-
return { action: "cancel" };
|
|
8019
|
-
if (action === "Decline")
|
|
8020
|
-
return { action: "decline" };
|
|
8021
|
-
if (action === "Submit")
|
|
8022
|
-
return { action: "accept", content };
|
|
8023
|
-
let labels = properties.map(([name2, schema2]) => `${schema2.title ?? humanizeName(name2)} (${name2})`), selected = await options.ui.select("Choose a field to edit", labels);
|
|
8024
|
-
if (selected === void 0)
|
|
8025
|
-
return { action: "cancel" };
|
|
8026
|
-
let property = properties[labels.indexOf(selected)];
|
|
8027
|
-
if (!property)
|
|
8028
|
-
continue;
|
|
8029
|
-
let [name, schema] = property, value = await collectValidField(options.ui, params, name, schema, values[name]);
|
|
8030
|
-
if (!("value" in value))
|
|
8031
|
-
return { action: "cancel" };
|
|
8032
|
-
values[name] = value.value;
|
|
8033
|
-
}
|
|
8034
|
-
}
|
|
8035
|
-
async function collectValidField(ui, params, name, schema, current) {
|
|
8036
|
-
let required = params.requestedSchema.required?.includes(name) === !0;
|
|
8037
|
-
for (; ; ) {
|
|
8038
|
-
let result = await collectField(ui, params, name, schema, current);
|
|
8039
|
-
if (!("value" in result))
|
|
8040
|
-
return result;
|
|
8041
|
-
try {
|
|
8042
|
-
return coerceAndValidateFormValues({
|
|
8043
|
-
...params,
|
|
8044
|
-
requestedSchema: {
|
|
8045
|
-
type: "object",
|
|
8046
|
-
properties: { [name]: schema },
|
|
8047
|
-
...required ? { required: [name] } : {}
|
|
8048
|
-
}
|
|
8049
|
-
}, { [name]: result.value }), result;
|
|
8050
|
-
} catch (error) {
|
|
8051
|
-
ui.notify(error instanceof Error ? error.message : String(error), "error"), current = result.value;
|
|
8052
|
-
}
|
|
8053
|
-
}
|
|
8054
|
-
}
|
|
8055
|
-
async function collectField(ui, params, name, schema, current) {
|
|
8056
|
-
let required = params.requestedSchema.required?.includes(name) === !0, title = [schema.title ?? humanizeName(name), required ? "(required)" : "", schema.description].filter(Boolean).join(" ");
|
|
8057
|
-
if (schema.type === "string" && ("enum" in schema || "oneOf" in schema)) {
|
|
8058
|
-
let choices = "oneOf" in schema ? schema.oneOf.map((option) => ({ value: option.const, display: formatChoice(option.const, option.title) })) : schema.enum.map((value, index) => ({
|
|
8059
|
-
value,
|
|
8060
|
-
display: formatChoice(value, "enumNames" in schema ? schema.enumNames?.[index] : void 0)
|
|
8061
|
-
})), displays = uniqueLabels(choices.map((choice) => choice.display)), actions2 = [...displays], useDefault = schema.default === void 0 ? void 0 : uniqueAction("Use default", actions2);
|
|
8062
|
-
useDefault && actions2.push(useDefault);
|
|
8063
|
-
let omit = required ? void 0 : uniqueAction("Omit", actions2);
|
|
8064
|
-
omit && actions2.push(omit);
|
|
8065
|
-
let action2 = await ui.select(title, actions2);
|
|
8066
|
-
return action2 === void 0 ? { cancelled: !0 } : action2 === useDefault ? { cancelled: !1, value: schema.default } : action2 === omit ? { cancelled: !1, value: void 0 } : { cancelled: !1, value: choices[displays.indexOf(action2)]?.value };
|
|
8067
|
-
}
|
|
8068
|
-
if (schema.type === "boolean") {
|
|
8069
|
-
let actions2 = ["Yes", "No"];
|
|
8070
|
-
schema.default !== void 0 && actions2.push("Use default"), required || actions2.push("Omit");
|
|
8071
|
-
let action2 = await ui.select(title, actions2);
|
|
8072
|
-
return action2 === void 0 ? { cancelled: !0 } : action2 === "Use default" ? { cancelled: !1, value: schema.default } : action2 === "Omit" ? { cancelled: !1, value: void 0 } : { cancelled: !1, value: action2 === "Yes" };
|
|
8073
|
-
}
|
|
8074
|
-
if (schema.type === "array") {
|
|
8075
|
-
let actions2 = ["Choose values"];
|
|
8076
|
-
schema.default !== void 0 && actions2.push("Use default"), required || actions2.push("Omit");
|
|
8077
|
-
let action2 = await ui.select(title, actions2);
|
|
8078
|
-
if (action2 === void 0)
|
|
8079
|
-
return { cancelled: !0 };
|
|
8080
|
-
if (action2 === "Use default")
|
|
8081
|
-
return { cancelled: !1, value: schema.default };
|
|
8082
|
-
if (action2 === "Omit")
|
|
8083
|
-
return { cancelled: !1, value: void 0 };
|
|
8084
|
-
let choices = extractMultiSelectOptions(schema), selected = new Set(Array.isArray(current) ? current : []);
|
|
8085
|
-
for (; ; ) {
|
|
8086
|
-
let displays = uniqueLabels(choices.map((choice2) => selected.has(choice2.value) ? `\u2713 ${choice2.display}` : choice2.display)), done = uniqueAction("Done", displays), picked = await ui.select(title, [...displays, done]);
|
|
8087
|
-
if (picked === void 0)
|
|
8088
|
-
return { cancelled: !0 };
|
|
8089
|
-
if (picked === done)
|
|
8090
|
-
return { cancelled: !1, value: [...selected] };
|
|
8091
|
-
let choice = choices[displays.indexOf(picked)];
|
|
8092
|
-
choice && (selected.has(choice.value) ? selected.delete(choice.value) : selected.add(choice.value));
|
|
8093
|
-
}
|
|
8094
|
-
}
|
|
8095
|
-
let actions = ["Enter value"];
|
|
8096
|
-
schema.default !== void 0 && actions.push("Use default"), required || actions.push("Omit");
|
|
8097
|
-
let action = await ui.select(title, actions);
|
|
8098
|
-
if (action === void 0)
|
|
8099
|
-
return { cancelled: !0 };
|
|
8100
|
-
if (action === "Use default")
|
|
8101
|
-
return { cancelled: !1, value: schema.default };
|
|
8102
|
-
if (action === "Omit")
|
|
8103
|
-
return { cancelled: !1, value: void 0 };
|
|
8104
|
-
let entered = await ui.input(title, current === void 0 ? void 0 : String(current));
|
|
8105
|
-
return entered === void 0 ? { cancelled: !0 } : { cancelled: !1, value: entered };
|
|
8106
|
-
}
|
|
8107
|
-
function coerceAndValidateFormValues(params, values) {
|
|
8108
|
-
let output = {}, required = new Set(params.requestedSchema.required ?? []);
|
|
8109
|
-
for (let [name, schema] of Object.entries(params.requestedSchema.properties)) {
|
|
8110
|
-
let value = values[name];
|
|
8111
|
-
if (value === void 0) {
|
|
8112
|
-
if (required.has(name))
|
|
8113
|
-
throw new Error(`Missing required elicitation field: ${name}`);
|
|
8114
|
-
continue;
|
|
8115
|
-
}
|
|
8116
|
-
if (schema.type === "string") {
|
|
8117
|
-
let stringValue = String(value), limits = schema;
|
|
8118
|
-
if (limits.minLength !== void 0 && stringValue.length < limits.minLength)
|
|
8119
|
-
throw new Error(`Elicitation field ${name} is shorter than minimum length ${limits.minLength}`);
|
|
8120
|
-
if (limits.maxLength !== void 0 && stringValue.length > limits.maxLength)
|
|
8121
|
-
throw new Error(`Elicitation field ${name} is longer than maximum length ${limits.maxLength}`);
|
|
8122
|
-
if ("enum" in schema && !schema.enum.includes(stringValue))
|
|
8123
|
-
throw new Error(`Elicitation field ${name} is not an allowed value`);
|
|
8124
|
-
if ("oneOf" in schema && !schema.oneOf.some((option) => option.const === stringValue))
|
|
8125
|
-
throw new Error(`Elicitation field ${name} is not an allowed value`);
|
|
8126
|
-
output[name] = stringValue;
|
|
8127
|
-
continue;
|
|
8128
|
-
}
|
|
8129
|
-
if (schema.type === "number" || schema.type === "integer") {
|
|
8130
|
-
if (typeof value == "string" && value.trim() === "")
|
|
8131
|
-
throw new Error(`Elicitation field ${name} must be a number`);
|
|
8132
|
-
let numberValue = typeof value == "number" ? value : Number(value);
|
|
8133
|
-
if (!Number.isFinite(numberValue))
|
|
8134
|
-
throw new Error(`Elicitation field ${name} must be a number`);
|
|
8135
|
-
if (schema.type === "integer" && !Number.isInteger(numberValue))
|
|
8136
|
-
throw new Error(`Elicitation field ${name} must be an integer`);
|
|
8137
|
-
if (schema.minimum !== void 0 && numberValue < schema.minimum)
|
|
8138
|
-
throw new Error(`Elicitation field ${name} is below minimum ${schema.minimum}`);
|
|
8139
|
-
if (schema.maximum !== void 0 && numberValue > schema.maximum)
|
|
8140
|
-
throw new Error(`Elicitation field ${name} is above maximum ${schema.maximum}`);
|
|
8141
|
-
output[name] = numberValue;
|
|
8142
|
-
continue;
|
|
8143
|
-
}
|
|
8144
|
-
if (schema.type === "boolean") {
|
|
8145
|
-
output[name] = typeof value == "boolean" ? value : value === "true";
|
|
8146
|
-
continue;
|
|
8147
|
-
}
|
|
8148
|
-
if (schema.type === "array") {
|
|
8149
|
-
if (!Array.isArray(value))
|
|
8150
|
-
throw new Error(`Elicitation field ${name} must be a list`);
|
|
8151
|
-
let allowed = new Set(extractMultiSelectOptions(schema).map((option) => option.value)), arrayValue = value.map(String);
|
|
8152
|
-
if (schema.minItems !== void 0 && arrayValue.length < schema.minItems)
|
|
8153
|
-
throw new Error(`Elicitation field ${name} has fewer than ${schema.minItems} selections`);
|
|
8154
|
-
if (schema.maxItems !== void 0 && arrayValue.length > schema.maxItems)
|
|
8155
|
-
throw new Error(`Elicitation field ${name} has more than ${schema.maxItems} selections`);
|
|
8156
|
-
if (arrayValue.some((item) => !allowed.has(item)))
|
|
8157
|
-
throw new Error(`Elicitation field ${name} contains an invalid selection`);
|
|
8158
|
-
output[name] = arrayValue;
|
|
8159
|
-
}
|
|
8160
|
-
}
|
|
8161
|
-
let validation = new AjvJsonSchemaValidator().getValidator(params.requestedSchema)(output);
|
|
8162
|
-
if (!validation.valid)
|
|
8163
|
-
throw new Error(`Invalid elicitation response: ${validation.errorMessage}`);
|
|
8164
|
-
return output;
|
|
8165
|
-
}
|
|
8166
|
-
function formatChoice(value, title) {
|
|
8167
|
-
return title && title !== value ? `${title} (${value})` : value;
|
|
8168
|
-
}
|
|
8169
|
-
function uniqueLabels(labels) {
|
|
8170
|
-
let used = /* @__PURE__ */ new Set();
|
|
8171
|
-
return labels.map((label) => {
|
|
8172
|
-
let unique = label;
|
|
8173
|
-
for (; used.has(unique); )
|
|
8174
|
-
unique += "\u2026";
|
|
8175
|
-
return used.add(unique), unique;
|
|
8176
|
-
});
|
|
8177
|
-
}
|
|
8178
|
-
function uniqueAction(label, choices) {
|
|
8179
|
-
let unique = label;
|
|
8180
|
-
for (; choices.includes(unique); )
|
|
8181
|
-
unique += "\u2026";
|
|
8182
|
-
return unique;
|
|
8183
|
-
}
|
|
8184
|
-
function extractMultiSelectOptions(schema) {
|
|
8185
|
-
let items = schema.items;
|
|
8186
|
-
return items.anyOf ? items.anyOf.map((option) => ({ value: option.const, display: formatChoice(option.const, option.title) })) : (items.enum ?? []).map((value) => ({ value, display: value }));
|
|
8187
|
-
}
|
|
8188
|
-
function formatReview(serverName, properties, content) {
|
|
8189
|
-
let rows = properties.map(([name, schema]) => `${schema.title ?? humanizeName(name)}: ${content[name] === void 0 ? "(omitted)" : String(content[name])}`);
|
|
8190
|
-
return [`Review input for ${serverName}`, "", ...rows].join(`
|
|
8191
|
-
`);
|
|
8192
|
-
}
|
|
8193
|
-
async function handleUrlElicitation(options, params) {
|
|
8194
|
-
if (!options.allowUrl)
|
|
8195
|
-
throw new McpError(ErrorCode.InvalidParams, "URL elicitation is not supported");
|
|
8196
|
-
let parsed;
|
|
8197
|
-
try {
|
|
8198
|
-
parsed = new URL(params.url);
|
|
8199
|
-
} catch {
|
|
8200
|
-
throw new McpError(ErrorCode.InvalidParams, "URL elicitation supplied an invalid URL");
|
|
8201
|
-
}
|
|
8202
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
8203
|
-
throw new McpError(ErrorCode.InvalidParams, "URL elicitation only supports HTTP and HTTPS URLs");
|
|
8204
|
-
let decision = await options.ui.select([
|
|
8205
|
-
"MCP Browser Request",
|
|
8206
|
-
`Server: ${options.serverName}`,
|
|
8207
|
-
"",
|
|
8208
|
-
params.message,
|
|
8209
|
-
"",
|
|
8210
|
-
`Host: ${parsed.host}`,
|
|
8211
|
-
`Full URL: ${params.url}`,
|
|
8212
|
-
"",
|
|
8213
|
-
"Open this URL in your browser?"
|
|
8214
|
-
].join(`
|
|
8215
|
-
`), ["Open", "Decline"]);
|
|
8216
|
-
if (decision === void 0)
|
|
8217
|
-
return { action: "cancel" };
|
|
8218
|
-
if (decision === "Decline")
|
|
8219
|
-
return { action: "decline" };
|
|
8220
|
-
try {
|
|
8221
|
-
await open(params.url);
|
|
8222
|
-
} catch (error) {
|
|
8223
|
-
return options.ui.notify(`Could not open MCP elicitation URL: ${error instanceof Error ? error.message : String(error)}`, "error"), { action: "cancel" };
|
|
8224
|
-
}
|
|
8225
|
-
return options.onUrlAccepted?.(params.elicitationId), options.ui.notify("Opened browser for MCP elicitation.", "info"), { action: "accept" };
|
|
8226
|
-
}
|
|
8227
|
-
function humanizeName(name) {
|
|
8228
|
-
return name.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, (char) => char.toUpperCase());
|
|
8229
|
-
}
|
|
8230
|
-
|
|
8231
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/server-manager.js
|
|
8232
|
-
var McpServerManager = class {
|
|
8233
|
-
defaultCwd;
|
|
8234
|
-
connections = /* @__PURE__ */ new Map();
|
|
8235
|
-
connectPromises = /* @__PURE__ */ new Map();
|
|
8236
|
-
uiStreamListeners = /* @__PURE__ */ new Map();
|
|
8237
|
-
samplingConfig;
|
|
8238
|
-
elicitationConfig;
|
|
8239
|
-
acceptedUrlElicitations = /* @__PURE__ */ new Map();
|
|
8240
|
-
defaultRequestTimeoutMs;
|
|
8241
|
-
/** Default cwd for stdio servers without an explicit config `cwd`. */
|
|
8242
|
-
constructor(defaultCwd) {
|
|
8243
|
-
this.defaultCwd = defaultCwd;
|
|
8244
|
-
}
|
|
8245
|
-
setSamplingConfig(config) {
|
|
8246
|
-
this.samplingConfig = config;
|
|
8247
|
-
}
|
|
8248
|
-
setElicitationConfig(config) {
|
|
8249
|
-
this.elicitationConfig = config;
|
|
8250
|
-
}
|
|
8251
|
-
setDefaultRequestTimeoutMs(timeoutMs) {
|
|
8252
|
-
this.defaultRequestTimeoutMs = normalizeRequestTimeoutMs(timeoutMs);
|
|
8253
|
-
}
|
|
8254
|
-
getRequestOptions(name, signal) {
|
|
8255
|
-
let connection = this.connections.get(name);
|
|
8256
|
-
return this.buildRequestOptions(connection?.definition, signal);
|
|
8257
|
-
}
|
|
8258
|
-
getResolvedRequestTimeoutMs(definition) {
|
|
8259
|
-
return definition?.requestTimeoutMs !== void 0 ? normalizeRequestTimeoutMs(definition.requestTimeoutMs) : this.defaultRequestTimeoutMs;
|
|
8260
|
-
}
|
|
8261
|
-
buildRequestOptions(definition, signal) {
|
|
8262
|
-
let timeout = this.getResolvedRequestTimeoutMs(definition);
|
|
8263
|
-
if (!(!signal && timeout === void 0))
|
|
8264
|
-
return {
|
|
8265
|
-
...signal ? { signal } : {},
|
|
8266
|
-
...timeout !== void 0 ? { timeout } : {}
|
|
8267
|
-
};
|
|
8268
|
-
}
|
|
8269
|
-
async connect(name, definition, signal) {
|
|
8270
|
-
if (throwIfAborted(signal), this.connectPromises.has(name))
|
|
8271
|
-
return abortable(this.connectPromises.get(name), signal);
|
|
8272
|
-
let existing = this.connections.get(name);
|
|
8273
|
-
if (existing?.status === "connected")
|
|
8274
|
-
return existing.lastUsedAt = Date.now(), existing;
|
|
8275
|
-
let promise = this.createConnection(name, definition, signal);
|
|
8276
|
-
this.connectPromises.set(name, promise);
|
|
8277
|
-
try {
|
|
8278
|
-
let connection = await promise;
|
|
8279
|
-
return this.connections.set(name, connection), connection;
|
|
8280
|
-
} finally {
|
|
8281
|
-
this.connectPromises.delete(name);
|
|
8282
|
-
}
|
|
8283
|
-
}
|
|
8284
|
-
async createConnection(name, definition, signal) {
|
|
8285
|
-
throwIfAborted(signal);
|
|
8286
|
-
let client = this.createClient(name), transport;
|
|
8287
|
-
if (definition.command) {
|
|
8288
|
-
let command = definition.command, args = definition.args ?? [];
|
|
8289
|
-
if (command === "npx" || command === "npm") {
|
|
8290
|
-
let resolved = await resolveNpxBinary(command, args);
|
|
8291
|
-
resolved && (command = resolved.isJs ? "node" : resolved.binPath, args = resolved.isJs ? [resolved.binPath, ...resolved.extraArgs] : resolved.extraArgs, logger.debug(`${name} resolved to ${resolved.binPath} (skipping npm parent)`));
|
|
8292
|
-
}
|
|
8293
|
-
transport = new StdioClientTransport({
|
|
8294
|
-
command,
|
|
8295
|
-
args,
|
|
8296
|
-
env: resolveEnv(definition.env),
|
|
8297
|
-
cwd: resolveConfigPath(definition.cwd) ?? this.defaultCwd,
|
|
8298
|
-
stderr: definition.debug ? "inherit" : "ignore"
|
|
8299
|
-
});
|
|
8300
|
-
} else if (definition.url)
|
|
8301
|
-
transport = await this.createHttpTransport(definition, name, signal);
|
|
8302
|
-
else
|
|
8303
|
-
throw new Error(`Server ${name} has no command or url`);
|
|
8304
|
-
let requestOptions = this.buildRequestOptions(definition, signal);
|
|
8305
|
-
try {
|
|
8306
|
-
await client.connect(transport, requestOptions), this.attachAdapterNotificationHandlers(name, client);
|
|
8307
|
-
let [tools, resources] = await Promise.all([
|
|
8308
|
-
this.fetchAllTools(client, requestOptions),
|
|
8309
|
-
this.fetchAllResources(client, requestOptions)
|
|
8310
|
-
]);
|
|
8311
|
-
return {
|
|
8312
|
-
client,
|
|
8313
|
-
transport,
|
|
8314
|
-
definition,
|
|
8315
|
-
tools,
|
|
8316
|
-
resources,
|
|
8317
|
-
lastUsedAt: Date.now(),
|
|
8318
|
-
inFlight: 0,
|
|
8319
|
-
status: "connected"
|
|
8320
|
-
};
|
|
8321
|
-
} catch (error) {
|
|
8322
|
-
if (error instanceof UnauthorizedError && supportsOAuth(definition))
|
|
8323
|
-
return await client.close().catch(() => {
|
|
8324
|
-
}), await transport.close().catch(() => {
|
|
8325
|
-
}), {
|
|
8326
|
-
client,
|
|
8327
|
-
transport,
|
|
8328
|
-
definition,
|
|
8329
|
-
tools: [],
|
|
8330
|
-
resources: [],
|
|
8331
|
-
lastUsedAt: Date.now(),
|
|
8332
|
-
inFlight: 0,
|
|
8333
|
-
status: "needs-auth"
|
|
8334
|
-
};
|
|
8335
|
-
throw await client.close().catch(() => {
|
|
8336
|
-
}), await transport.close().catch(() => {
|
|
8337
|
-
}), error;
|
|
8338
|
-
}
|
|
8339
|
-
}
|
|
8340
|
-
buildClientCapabilities() {
|
|
8341
|
-
return {
|
|
8342
|
-
...this.samplingConfig ? { sampling: {} } : {},
|
|
8343
|
-
...this.elicitationConfig ? {
|
|
8344
|
-
elicitation: {
|
|
8345
|
-
form: {},
|
|
8346
|
-
...this.elicitationConfig.allowUrl ? { url: {} } : {}
|
|
8347
|
-
}
|
|
8348
|
-
} : {}
|
|
8349
|
-
};
|
|
8350
|
-
}
|
|
8351
|
-
createClient(serverName) {
|
|
8352
|
-
let capabilities = this.buildClientCapabilities(), client = new Client({ name: `pi-mcp-${serverName}`, version: "1.0.0" }, Object.keys(capabilities).length > 0 ? { capabilities } : void 0);
|
|
8353
|
-
return this.samplingConfig && registerSamplingHandler(client, { ...this.samplingConfig, serverName }), this.elicitationConfig && (registerElicitationHandler(client, {
|
|
8354
|
-
...this.elicitationConfig,
|
|
8355
|
-
serverName,
|
|
8356
|
-
onUrlAccepted: (elicitationId) => this.rememberUrlElicitation(serverName, elicitationId)
|
|
8357
|
-
}), this.elicitationConfig.allowUrl && client.setNotificationHandler(ElicitationCompleteNotificationSchema, (notification) => {
|
|
8358
|
-
this.acceptedUrlElicitations.get(serverName)?.delete(notification.params.elicitationId) && this.elicitationConfig?.ui.notify(`MCP browser interaction for ${serverName} completed. You can retry the tool now.`, "info");
|
|
8359
|
-
})), client;
|
|
8360
|
-
}
|
|
8361
|
-
async handleUrlElicitationRequired(serverName, error) {
|
|
8362
|
-
if (!this.elicitationConfig?.allowUrl)
|
|
8363
|
-
return "cancel";
|
|
8364
|
-
for (let params of error.elicitations) {
|
|
8365
|
-
let result = await handleUrlElicitation({
|
|
8366
|
-
...this.elicitationConfig,
|
|
8367
|
-
serverName,
|
|
8368
|
-
onUrlAccepted: (elicitationId) => this.rememberUrlElicitation(serverName, elicitationId)
|
|
8369
|
-
}, params);
|
|
8370
|
-
if (result.action !== "accept")
|
|
8371
|
-
return result.action;
|
|
8372
|
-
}
|
|
8373
|
-
return "accept";
|
|
8374
|
-
}
|
|
8375
|
-
rememberUrlElicitation(serverName, elicitationId) {
|
|
8376
|
-
let accepted = this.acceptedUrlElicitations.get(serverName);
|
|
8377
|
-
accepted || (accepted = /* @__PURE__ */ new Set(), this.acceptedUrlElicitations.set(serverName, accepted)), accepted.add(elicitationId);
|
|
8378
|
-
}
|
|
8379
|
-
async createHttpTransport(definition, serverName, signal) {
|
|
8380
|
-
throwIfAborted(signal);
|
|
8381
|
-
let url = new URL(definition.url), headers = resolveHeaders(definition.headers) ?? {};
|
|
8382
|
-
if (definition.auth === "bearer") {
|
|
8383
|
-
let token = resolveBearerToken(definition);
|
|
8384
|
-
token && (headers.Authorization = `Bearer ${token}`);
|
|
8385
|
-
}
|
|
8386
|
-
let requestInit = Object.keys(headers).length > 0 ? { headers } : void 0, authProvider;
|
|
8387
|
-
if (supportsOAuth(definition)) {
|
|
8388
|
-
let oauthConfig = extractOAuthConfig(definition);
|
|
8389
|
-
authProvider = new McpOAuthProvider(serverName, definition.url, oauthConfig, {
|
|
8390
|
-
onRedirect: async (_authUrl) => {
|
|
8391
|
-
}
|
|
8392
|
-
});
|
|
8393
|
-
}
|
|
8394
|
-
let streamableTransport = new StreamableHTTPClientTransport(url, {
|
|
8395
|
-
requestInit,
|
|
8396
|
-
authProvider
|
|
8397
|
-
});
|
|
8398
|
-
try {
|
|
8399
|
-
let testClient = new Client({ name: "pi-mcp-probe", version: "2.1.2" });
|
|
8400
|
-
return await testClient.connect(streamableTransport, this.buildRequestOptions(definition, signal)), await testClient.close().catch(() => {
|
|
8401
|
-
}), await streamableTransport.close().catch(() => {
|
|
8402
|
-
}), new StreamableHTTPClientTransport(url, { requestInit, authProvider });
|
|
8403
|
-
} catch (error) {
|
|
8404
|
-
if (await streamableTransport.close().catch(() => {
|
|
8405
|
-
}), signal?.aborted && throwIfAborted(signal), error instanceof UnauthorizedError)
|
|
8406
|
-
throw error;
|
|
8407
|
-
return new SSEClientTransport(url, { requestInit, authProvider });
|
|
8408
|
-
}
|
|
8409
|
-
}
|
|
8410
|
-
async fetchAllTools(client, requestOptions) {
|
|
8411
|
-
let allTools = [], cursor;
|
|
8412
|
-
do {
|
|
8413
|
-
let result = await client.listTools(cursor ? { cursor } : void 0, requestOptions);
|
|
8414
|
-
allTools.push(...result.tools ?? []), cursor = result.nextCursor;
|
|
8415
|
-
} while (cursor);
|
|
8416
|
-
return allTools;
|
|
8417
|
-
}
|
|
8418
|
-
async fetchAllResources(client, requestOptions) {
|
|
8419
|
-
try {
|
|
8420
|
-
let allResources = [], cursor;
|
|
8421
|
-
do {
|
|
8422
|
-
let result = await client.listResources(cursor ? { cursor } : void 0, requestOptions);
|
|
8423
|
-
allResources.push(...result.resources ?? []), cursor = result.nextCursor;
|
|
8424
|
-
} while (cursor);
|
|
8425
|
-
return allResources;
|
|
8426
|
-
} catch {
|
|
8427
|
-
return requestOptions?.signal?.aborted && throwIfAborted(requestOptions.signal), [];
|
|
8428
|
-
}
|
|
8429
|
-
}
|
|
8430
|
-
attachAdapterNotificationHandlers(serverName, client) {
|
|
8431
|
-
client.setNotificationHandler(serverStreamResultPatchNotificationSchema, (notification) => {
|
|
8432
|
-
let listener = this.uiStreamListeners.get(notification.params.streamToken);
|
|
8433
|
-
listener && listener(serverName, notification.params);
|
|
8434
|
-
});
|
|
8435
|
-
}
|
|
8436
|
-
registerUiStreamListener(streamToken, listener) {
|
|
8437
|
-
this.uiStreamListeners.set(streamToken, listener);
|
|
8438
|
-
}
|
|
8439
|
-
removeUiStreamListener(streamToken) {
|
|
8440
|
-
this.uiStreamListeners.delete(streamToken);
|
|
8441
|
-
}
|
|
8442
|
-
async readResource(name, uri, signal) {
|
|
8443
|
-
let connection = this.connections.get(name);
|
|
8444
|
-
if (!connection || connection.status !== "connected")
|
|
8445
|
-
throw new Error(`Server "${name}" is not connected`);
|
|
8446
|
-
try {
|
|
8447
|
-
return this.touch(name), this.incrementInFlight(name), await connection.client.readResource({ uri }, this.getRequestOptions(name, signal));
|
|
8448
|
-
} finally {
|
|
8449
|
-
this.decrementInFlight(name), this.touch(name);
|
|
8450
|
-
}
|
|
8451
|
-
}
|
|
8452
|
-
async close(name) {
|
|
8453
|
-
let connection = this.connections.get(name);
|
|
8454
|
-
connection && (connection.status = "closed", this.connections.delete(name), this.acceptedUrlElicitations.delete(name), await connection.client.close().catch(() => {
|
|
8455
|
-
}), await connection.transport.close().catch(() => {
|
|
8456
|
-
}));
|
|
8457
|
-
}
|
|
8458
|
-
async closeAll() {
|
|
8459
|
-
let names = [...this.connections.keys()];
|
|
8460
|
-
await Promise.all(names.map((name) => this.close(name)));
|
|
8461
|
-
}
|
|
8462
|
-
getConnection(name) {
|
|
8463
|
-
return this.connections.get(name);
|
|
8464
|
-
}
|
|
8465
|
-
getAllConnections() {
|
|
8466
|
-
return new Map(this.connections);
|
|
8467
|
-
}
|
|
8468
|
-
touch(name) {
|
|
8469
|
-
let connection = this.connections.get(name);
|
|
8470
|
-
connection && (connection.lastUsedAt = Date.now());
|
|
8471
|
-
}
|
|
8472
|
-
incrementInFlight(name) {
|
|
8473
|
-
let connection = this.connections.get(name);
|
|
8474
|
-
connection && (connection.inFlight = (connection.inFlight ?? 0) + 1);
|
|
8475
|
-
}
|
|
8476
|
-
decrementInFlight(name) {
|
|
8477
|
-
let connection = this.connections.get(name);
|
|
8478
|
-
connection && connection.inFlight && connection.inFlight--;
|
|
8479
|
-
}
|
|
8480
|
-
isIdle(name, timeoutMs) {
|
|
8481
|
-
let connection = this.connections.get(name);
|
|
8482
|
-
return !connection || connection.status !== "connected" || connection.inFlight > 0 ? !1 : Date.now() - connection.lastUsedAt > timeoutMs;
|
|
8483
|
-
}
|
|
8484
|
-
};
|
|
8485
|
-
function resolveEnv(env) {
|
|
8486
|
-
let resolved = {};
|
|
8487
|
-
for (let [key, value] of Object.entries(process.env))
|
|
8488
|
-
value !== void 0 && (resolved[key] = value);
|
|
8489
|
-
if (!env)
|
|
8490
|
-
return resolved;
|
|
8491
|
-
let overrides = interpolateEnvRecord(env);
|
|
8492
|
-
return overrides ? { ...resolved, ...overrides } : resolved;
|
|
8493
|
-
}
|
|
8494
|
-
function resolveHeaders(headers) {
|
|
8495
|
-
return interpolateEnvRecord(headers);
|
|
8496
|
-
}
|
|
8497
|
-
function normalizeRequestTimeoutMs(timeoutMs) {
|
|
8498
|
-
return typeof timeoutMs == "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : void 0;
|
|
8499
|
-
}
|
|
8500
|
-
|
|
8501
|
-
// node_modules/@modelcontextprotocol/ext-apps/dist/src/app-bridge.js
|
|
8502
|
-
var ZQ = ((X) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(X, { get: (Y, Z) => (typeof __require < "u" ? __require : Y)[Z] }) : X)(function(X) {
|
|
8503
|
-
if (typeof __require < "u") return __require.apply(this, arguments);
|
|
8504
|
-
throw Error('Dynamic require of "' + X + '" is not supported');
|
|
8505
|
-
});
|
|
8506
|
-
var r = external_exports.union([external_exports.literal("light"), external_exports.literal("dark")]).describe("Color theme preference for the host environment."), B = external_exports.union([external_exports.literal("inline"), external_exports.literal("fullscreen"), external_exports.literal("pip")]).describe("Display mode for UI presentation."), HQ = external_exports.union([external_exports.literal("--color-background-primary"), external_exports.literal("--color-background-secondary"), external_exports.literal("--color-background-tertiary"), external_exports.literal("--color-background-inverse"), external_exports.literal("--color-background-ghost"), external_exports.literal("--color-background-info"), external_exports.literal("--color-background-danger"), external_exports.literal("--color-background-success"), external_exports.literal("--color-background-warning"), external_exports.literal("--color-background-disabled"), external_exports.literal("--color-text-primary"), external_exports.literal("--color-text-secondary"), external_exports.literal("--color-text-tertiary"), external_exports.literal("--color-text-inverse"), external_exports.literal("--color-text-ghost"), external_exports.literal("--color-text-info"), external_exports.literal("--color-text-danger"), external_exports.literal("--color-text-success"), external_exports.literal("--color-text-warning"), external_exports.literal("--color-text-disabled"), external_exports.literal("--color-border-primary"), external_exports.literal("--color-border-secondary"), external_exports.literal("--color-border-tertiary"), external_exports.literal("--color-border-inverse"), external_exports.literal("--color-border-ghost"), external_exports.literal("--color-border-info"), external_exports.literal("--color-border-danger"), external_exports.literal("--color-border-success"), external_exports.literal("--color-border-warning"), external_exports.literal("--color-border-disabled"), external_exports.literal("--color-ring-primary"), external_exports.literal("--color-ring-secondary"), external_exports.literal("--color-ring-inverse"), external_exports.literal("--color-ring-info"), external_exports.literal("--color-ring-danger"), external_exports.literal("--color-ring-success"), external_exports.literal("--color-ring-warning"), external_exports.literal("--font-sans"), external_exports.literal("--font-mono"), external_exports.literal("--font-weight-normal"), external_exports.literal("--font-weight-medium"), external_exports.literal("--font-weight-semibold"), external_exports.literal("--font-weight-bold"), external_exports.literal("--font-text-xs-size"), external_exports.literal("--font-text-sm-size"), external_exports.literal("--font-text-md-size"), external_exports.literal("--font-text-lg-size"), external_exports.literal("--font-heading-xs-size"), external_exports.literal("--font-heading-sm-size"), external_exports.literal("--font-heading-md-size"), external_exports.literal("--font-heading-lg-size"), external_exports.literal("--font-heading-xl-size"), external_exports.literal("--font-heading-2xl-size"), external_exports.literal("--font-heading-3xl-size"), external_exports.literal("--font-text-xs-line-height"), external_exports.literal("--font-text-sm-line-height"), external_exports.literal("--font-text-md-line-height"), external_exports.literal("--font-text-lg-line-height"), external_exports.literal("--font-heading-xs-line-height"), external_exports.literal("--font-heading-sm-line-height"), external_exports.literal("--font-heading-md-line-height"), external_exports.literal("--font-heading-lg-line-height"), external_exports.literal("--font-heading-xl-line-height"), external_exports.literal("--font-heading-2xl-line-height"), external_exports.literal("--font-heading-3xl-line-height"), external_exports.literal("--border-radius-xs"), external_exports.literal("--border-radius-sm"), external_exports.literal("--border-radius-md"), external_exports.literal("--border-radius-lg"), external_exports.literal("--border-radius-xl"), external_exports.literal("--border-radius-full"), external_exports.literal("--border-width-regular"), external_exports.literal("--shadow-hairline"), external_exports.literal("--shadow-sm"), external_exports.literal("--shadow-md"), external_exports.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."), RQ = external_exports.record(HQ.describe(`Style variables for theming MCP apps.
|
|
8507
|
-
|
|
8508
|
-
Individual style keys are optional - hosts may provide any subset of these values.
|
|
8509
|
-
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
8510
|
-
|
|
8511
|
-
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
8512
|
-
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), external_exports.union([external_exports.string(), external_exports.undefined()]).describe(`Style variables for theming MCP apps.
|
|
8513
|
-
|
|
8514
|
-
Individual style keys are optional - hosts may provide any subset of these values.
|
|
8515
|
-
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
8516
|
-
|
|
8517
|
-
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
8518
|
-
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps.
|
|
8519
|
-
|
|
8520
|
-
Individual style keys are optional - hosts may provide any subset of these values.
|
|
8521
|
-
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
8522
|
-
|
|
8523
|
-
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
8524
|
-
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), L = external_exports.object({ method: external_exports.literal("ui/open-link"), params: external_exports.object({ url: external_exports.string().describe("URL to open in the host's browser") }) }), P = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).") }).passthrough(), A = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).") }).passthrough(), U = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the host rejected or failed to deliver the message.") }).passthrough(), w = external_exports.object({ method: external_exports.literal("ui/notifications/sandbox-proxy-ready"), params: external_exports.object({}) }), O = external_exports.object({ connectDomains: external_exports.array(external_exports.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
|
|
8525
|
-
|
|
8526
|
-
- Maps to CSP \`connect-src\` directive
|
|
8527
|
-
- Empty or omitted \u2192 no network connections (secure default)`), resourceDomains: external_exports.array(external_exports.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted \u2192 no network resources (secure default)"), frameDomains: external_exports.array(external_exports.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"), baseUriDomains: external_exports.array(external_exports.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)") }), z = external_exports.object({ camera: external_exports.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."), microphone: external_exports.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."), geolocation: external_exports.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."), clipboardWrite: external_exports.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.") }), H = external_exports.object({ method: external_exports.literal("ui/notifications/size-changed"), params: external_exports.object({ width: external_exports.number().optional().describe("New width in pixels."), height: external_exports.number().optional().describe("New height in pixels.") }) }), R = external_exports.object({ method: external_exports.literal("ui/notifications/tool-input"), params: external_exports.object({ arguments: external_exports.record(external_exports.string(), external_exports.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.") }) }), T = external_exports.object({ method: external_exports.literal("ui/notifications/tool-input-partial"), params: external_exports.object({ arguments: external_exports.record(external_exports.string(), external_exports.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).") }) }), M = external_exports.object({ method: external_exports.literal("ui/notifications/tool-cancelled"), params: external_exports.object({ reason: external_exports.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").') }) }), o = external_exports.object({ fonts: external_exports.string().optional() }), s = external_exports.object({ variables: RQ.optional().describe("CSS variables for theming the app."), css: o.optional().describe("CSS blocks that apps can inject.") }), C = external_exports.object({ method: external_exports.literal("ui/resource-teardown"), params: external_exports.object({}) }), S = external_exports.record(external_exports.string(), external_exports.unknown()), F = external_exports.object({ text: external_exports.object({}).optional().describe("Host supports text content blocks."), image: external_exports.object({}).optional().describe("Host supports image content blocks."), audio: external_exports.object({}).optional().describe("Host supports audio content blocks."), resource: external_exports.object({}).optional().describe("Host supports resource content blocks."), resourceLink: external_exports.object({}).optional().describe("Host supports resource link content blocks."), structuredContent: external_exports.object({}).optional().describe("Host supports structured content.") }), q = external_exports.object({ method: external_exports.literal("ui/notifications/request-teardown"), params: external_exports.object({}).optional() }), t = external_exports.object({ experimental: external_exports.object({}).optional().describe("Experimental features (structure TBD)."), openLinks: external_exports.object({}).optional().describe("Host supports opening external URLs."), downloadFile: external_exports.object({}).optional().describe("Host supports file downloads via ui/download-file."), serverTools: external_exports.object({ listChanged: external_exports.boolean().optional().describe("Host supports tools/list_changed notifications.") }).optional().describe("Host can proxy tool calls to the MCP server."), serverResources: external_exports.object({ listChanged: external_exports.boolean().optional().describe("Host supports resources/list_changed notifications.") }).optional().describe("Host can proxy resource reads to the MCP server."), logging: external_exports.object({}).optional().describe("Host accepts log messages."), sandbox: external_exports.object({ permissions: z.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."), csp: O.optional().describe("CSP domains approved by the host.") }).optional().describe("Sandbox configuration applied by the host."), updateModelContext: F.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."), message: F.optional().describe("Host supports receiving content messages (ui/message) from the view."), sampling: external_exports.object({ tools: external_exports.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.") }).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.") }), a = external_exports.object({ experimental: external_exports.object({}).optional().describe("Experimental features (structure TBD)."), tools: external_exports.object({ listChanged: external_exports.boolean().optional().describe("App supports tools/list_changed notifications.") }).optional().describe("App exposes MCP-style tools that the host can call."), availableDisplayModes: external_exports.array(B).optional().describe("Display modes the app supports.") }), y = external_exports.object({ method: external_exports.literal("ui/notifications/initialized"), params: external_exports.object({}).optional() }), TQ = external_exports.object({ csp: O.optional().describe("Content Security Policy configuration for UI resources."), permissions: z.optional().describe("Sandbox permissions requested by the UI resource."), domain: external_exports.string().optional().describe(`Dedicated origin for view sandbox.
|
|
8528
|
-
|
|
8529
|
-
Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
|
|
8530
|
-
|
|
8531
|
-
**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include:
|
|
8532
|
-
- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`)
|
|
8533
|
-
- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`)
|
|
8534
|
-
|
|
8535
|
-
If omitted, host uses default sandbox origin (typically per-conversation).`), prefersBorder: external_exports.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border.
|
|
8536
|
-
|
|
8537
|
-
Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary.
|
|
8538
|
-
|
|
8539
|
-
- \`true\`: request visible border + background
|
|
8540
|
-
- \`false\`: request no visible border + background
|
|
8541
|
-
- omitted: host decides border`) }), I = external_exports.object({ method: external_exports.literal("ui/request-display-mode"), params: external_exports.object({ mode: B.describe("The display mode being requested.") }) }), g = external_exports.object({ mode: B.describe("The display mode that was actually set. May differ from requested if not supported.") }).passthrough(), e = external_exports.union([external_exports.literal("model"), external_exports.literal("app")]).describe("Tool visibility scope - who can access the tool."), MQ = external_exports.object({ resourceUri: external_exports.string().optional(), visibility: external_exports.array(e).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
8542
|
-
- "model": Tool visible to and callable by the agent
|
|
8543
|
-
- "app": Tool callable by the app from this server only`), csp: external_exports.never().optional(), permissions: external_exports.never().optional() }), OX = external_exports.object({ mimeTypes: external_exports.array(external_exports.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.') }), f = external_exports.object({ method: external_exports.literal("ui/download-file"), params: external_exports.object({ contents: external_exports.array(external_exports.union([EmbeddedResourceSchema, ResourceLinkSchema])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.") }) }), k = external_exports.object({ method: external_exports.literal("ui/message"), params: external_exports.object({ role: external_exports.literal("user").describe('Message role, currently only "user" is supported.'), content: external_exports.array(ContentBlockSchema).describe("Message content blocks (text, image, etc.).") }) }), CQ = external_exports.object({ method: external_exports.literal("ui/notifications/sandbox-resource-ready"), params: external_exports.object({ html: external_exports.string().describe("HTML content to load into the inner iframe."), sandbox: external_exports.string().optional().describe("Optional override for the inner iframe's sandbox attribute."), csp: O.optional().describe("CSP configuration from resource metadata."), permissions: z.optional().describe("Sandbox permissions from resource metadata.") }) }), v = external_exports.object({ method: external_exports.literal("ui/notifications/tool-result"), params: CallToolResultSchema.describe("Standard MCP tool execution result.") }), x = external_exports.object({ toolInfo: external_exports.object({ id: RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."), tool: ToolSchema.describe("Tool definition including name, inputSchema, etc.") }).optional().describe("Metadata of the tool call that instantiated this App."), theme: r.optional().describe("Current color theme preference."), styles: s.optional().describe("Style configuration for theming the app."), displayMode: B.optional().describe("How the UI is currently displayed."), availableDisplayModes: external_exports.array(B).optional().describe("Display modes the host supports."), containerDimensions: external_exports.union([external_exports.object({ height: external_exports.number().describe("Fixed container height in pixels.") }), external_exports.object({ maxHeight: external_exports.union([external_exports.number(), external_exports.undefined()]).optional().describe("Maximum container height in pixels.") })]).and(external_exports.union([external_exports.object({ width: external_exports.number().describe("Fixed container width in pixels.") }), external_exports.object({ maxWidth: external_exports.union([external_exports.number(), external_exports.undefined()]).optional().describe("Maximum container width in pixels.") })])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
8544
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`), locale: external_exports.string().optional().describe("User's language and region preference in BCP 47 format."), timeZone: external_exports.string().optional().describe("User's timezone in IANA format."), userAgent: external_exports.string().optional().describe("Host application identifier."), platform: external_exports.union([external_exports.literal("web"), external_exports.literal("desktop"), external_exports.literal("mobile")]).optional().describe("Platform type for responsive design decisions."), deviceCapabilities: external_exports.object({ touch: external_exports.boolean().optional().describe("Whether the device supports touch input."), hover: external_exports.boolean().optional().describe("Whether the device supports hover interactions.") }).optional().describe("Device input capabilities."), safeAreaInsets: external_exports.object({ top: external_exports.number().describe("Top safe area inset in pixels."), right: external_exports.number().describe("Right safe area inset in pixels."), bottom: external_exports.number().describe("Bottom safe area inset in pixels."), left: external_exports.number().describe("Left safe area inset in pixels.") }).optional().describe("Mobile safe area boundaries in pixels.") }).passthrough(), b = external_exports.object({ method: external_exports.literal("ui/notifications/host-context-changed"), params: x.describe("Partial context update containing only changed fields.") }), d = external_exports.object({ method: external_exports.literal("ui/update-model-context"), params: external_exports.object({ content: external_exports.array(ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."), structuredContent: external_exports.record(external_exports.string(), external_exports.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.") }) }), u = external_exports.object({ method: external_exports.literal("ui/initialize"), params: external_exports.object({ appInfo: ImplementationSchema.describe("App identification (name and version)."), appCapabilities: a.describe("Features and capabilities this app provides."), protocolVersion: external_exports.string().describe("Protocol version this app supports.") }) }), h = external_exports.object({ protocolVersion: external_exports.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'), hostInfo: ImplementationSchema.describe("Host application identification and version."), hostCapabilities: t.describe("Features and capabilities provided by the host."), hostContext: x.describe("Rich context about the host environment.") }).passthrough();
|
|
8545
|
-
var i = "ui/resourceUri", pQ = "text/html;profile=mcp-app";
|
|
8546
|
-
function FZ(X) {
|
|
8547
|
-
let Z = X._meta?.ui?.resourceUri;
|
|
8548
|
-
if (Z === void 0 && (Z = X._meta?.[i]), typeof Z == "string" && Z.startsWith("ui://")) return Z;
|
|
8549
|
-
if (Z !== void 0) throw Error(`Invalid UI resource URI: ${JSON.stringify(Z)}`);
|
|
8550
|
-
}
|
|
8551
|
-
function AZ(X) {
|
|
8552
|
-
if (!X) return "";
|
|
8553
|
-
let Y = [];
|
|
8554
|
-
return X.camera && Y.push("camera"), X.microphone && Y.push("microphone"), X.geolocation && Y.push("geolocation"), X.clipboardWrite && Y.push("clipboard-write"), Y.join("; ");
|
|
8555
|
-
}
|
|
8556
|
-
|
|
8557
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/tool-metadata.js
|
|
8558
|
-
function buildToolMetadata(tools, resources, definition, serverName, prefix) {
|
|
8559
|
-
let metadata = [], failedTools = [];
|
|
8560
|
-
for (let tool of tools) {
|
|
8561
|
-
if (!tool?.name) {
|
|
8562
|
-
failedTools.push("(unnamed)");
|
|
8563
|
-
continue;
|
|
8564
|
-
}
|
|
8565
|
-
if (isToolExcluded(tool.name, serverName, prefix, definition.excludeTools))
|
|
8566
|
-
continue;
|
|
8567
|
-
let uiResourceUri;
|
|
8568
|
-
try {
|
|
8569
|
-
uiResourceUri = FZ({ _meta: tool._meta });
|
|
8570
|
-
} catch {
|
|
8571
|
-
failedTools.push(tool.name);
|
|
8572
|
-
}
|
|
8573
|
-
metadata.push({
|
|
8574
|
-
name: formatToolName(tool.name, serverName, prefix),
|
|
8575
|
-
originalName: tool.name,
|
|
8576
|
-
description: tool.description ?? "",
|
|
8577
|
-
inputSchema: tool.inputSchema,
|
|
8578
|
-
uiResourceUri,
|
|
8579
|
-
uiStreamMode: extractToolUiStreamMode(tool._meta)
|
|
8580
|
-
});
|
|
8581
|
-
}
|
|
8582
|
-
if (definition.exposeResources !== !1)
|
|
8583
|
-
for (let resource of resources) {
|
|
8584
|
-
let baseName = `get_${resourceNameToToolName(resource.name)}`;
|
|
8585
|
-
isToolExcluded(baseName, serverName, prefix, definition.excludeTools) || metadata.push({
|
|
8586
|
-
name: formatToolName(baseName, serverName, prefix),
|
|
8587
|
-
originalName: baseName,
|
|
8588
|
-
description: resource.description ?? `Read resource: ${resource.uri}`,
|
|
8589
|
-
resourceUri: resource.uri
|
|
8590
|
-
});
|
|
8591
|
-
}
|
|
8592
|
-
return { metadata, failedTools };
|
|
8593
|
-
}
|
|
8594
|
-
function getToolNames(state, serverName) {
|
|
8595
|
-
return state.toolMetadata.get(serverName)?.map((m) => m.name) ?? [];
|
|
8596
|
-
}
|
|
8597
|
-
function totalToolCount(state) {
|
|
8598
|
-
let count = 0;
|
|
8599
|
-
for (let metadata of state.toolMetadata.values())
|
|
8600
|
-
count += metadata.length;
|
|
8601
|
-
return count;
|
|
8602
|
-
}
|
|
8603
|
-
function findToolByName(metadata, toolName) {
|
|
8604
|
-
if (!metadata)
|
|
8605
|
-
return;
|
|
8606
|
-
let exact = metadata.find((m) => m.name === toolName);
|
|
8607
|
-
if (exact)
|
|
8608
|
-
return exact;
|
|
8609
|
-
let normalized = toolName.replace(/-/g, "_");
|
|
8610
|
-
return metadata.find((m) => m.name.replace(/-/g, "_") === normalized);
|
|
8611
|
-
}
|
|
8612
|
-
function formatSchema(schema, indent = " ") {
|
|
8613
|
-
if (!schema || typeof schema != "object" || Array.isArray(schema))
|
|
8614
|
-
return `${indent}(no schema)`;
|
|
8615
|
-
let s2 = schema;
|
|
8616
|
-
if (s2.type === "object" && s2.properties && typeof s2.properties == "object" && !Array.isArray(s2.properties)) {
|
|
8617
|
-
let props = s2.properties, required = Array.isArray(s2.required) ? s2.required.filter((name) => typeof name == "string") : [];
|
|
8618
|
-
if (Object.keys(props).length === 0)
|
|
8619
|
-
return `${indent}(no parameters)`;
|
|
8620
|
-
let lines2 = [];
|
|
8621
|
-
for (let [name, propSchema] of Object.entries(props))
|
|
8622
|
-
lines2.push(...formatProperty(name, propSchema, required.includes(name), indent));
|
|
8623
|
-
return lines2.join(`
|
|
8624
|
-
`);
|
|
8625
|
-
}
|
|
8626
|
-
let lines = formatNestedSchema(s2, indent);
|
|
8627
|
-
if (lines.length > 0)
|
|
8628
|
-
return lines.join(`
|
|
8629
|
-
`);
|
|
8630
|
-
let typeStr = formatType(s2);
|
|
8631
|
-
return typeStr ? `${indent}(${typeStr})` : `${indent}(complex schema)`;
|
|
8632
|
-
}
|
|
8633
|
-
function formatProperty(name, schema, required, indent) {
|
|
8634
|
-
if (!schema || typeof schema != "object" || Array.isArray(schema))
|
|
8635
|
-
return [`${indent}${name}${required ? " *required*" : ""}`];
|
|
8636
|
-
let s2 = schema, parts = [`${indent}${name}`], typeStr = formatType(s2);
|
|
8637
|
-
return typeStr && parts.push(`(${typeStr})`), required && parts.push("*required*"), appendSchemaAnnotations(parts, s2), [parts.join(" "), ...formatNestedSchema(s2, `${indent} `)];
|
|
8638
|
-
}
|
|
8639
|
-
function formatNestedSchema(schema, indent) {
|
|
8640
|
-
let lines = [];
|
|
8641
|
-
if (Array.isArray(schema.anyOf) && lines.push(...formatVariants("anyOf", schema.anyOf, indent)), Array.isArray(schema.oneOf) && lines.push(...formatVariants("oneOf", schema.oneOf, indent)), schema.items !== void 0 && lines.push(...formatProperty("items", schema.items, !1, indent)), schema.properties && typeof schema.properties == "object" && !Array.isArray(schema.properties)) {
|
|
8642
|
-
let required = Array.isArray(schema.required) ? schema.required.filter((name) => typeof name == "string") : [];
|
|
8643
|
-
for (let [name, propSchema] of Object.entries(schema.properties))
|
|
8644
|
-
lines.push(...formatProperty(name, propSchema, required.includes(name), indent));
|
|
8645
|
-
}
|
|
8646
|
-
return lines;
|
|
8647
|
-
}
|
|
8648
|
-
function formatVariants(keyword, variants, indent) {
|
|
8649
|
-
let lines = [`${indent}${keyword}:`];
|
|
8650
|
-
for (let variant of variants) {
|
|
8651
|
-
if (!variant || typeof variant != "object" || Array.isArray(variant)) {
|
|
8652
|
-
lines.push(`${indent} - ${JSON.stringify(variant)}`);
|
|
8653
|
-
continue;
|
|
8654
|
-
}
|
|
8655
|
-
let s2 = variant, typeStr = formatType(s2) || "schema", parts = [`${indent} - ${typeStr}`];
|
|
8656
|
-
appendSchemaAnnotations(parts, s2), lines.push(parts.join(" ")), lines.push(...formatNestedSchema(s2, `${indent} `));
|
|
8657
|
-
}
|
|
8658
|
-
return lines;
|
|
8659
|
-
}
|
|
8660
|
-
function formatType(schema) {
|
|
8661
|
-
return Object.hasOwn(schema, "const") ? `const ${JSON.stringify(schema.const)}` : Array.isArray(schema.enum) ? `enum: ${schema.enum.map((v2) => JSON.stringify(v2)).join(", ")}` : Array.isArray(schema.type) ? schema.type.map((type) => String(type)).join(" | ") : schema.type ? String(schema.type) : schema.properties && typeof schema.properties == "object" && !Array.isArray(schema.properties) ? "object" : schema.items !== void 0 ? "array" : "";
|
|
8662
|
-
}
|
|
8663
|
-
function appendSchemaAnnotations(parts, schema) {
|
|
8664
|
-
schema.description && typeof schema.description == "string" && parts.push(`- ${schema.description}`);
|
|
8665
|
-
for (let key of ["minLength", "maxLength", "minimum", "maximum", "minItems", "maxItems", "format", "pattern"])
|
|
8666
|
-
schema[key] !== void 0 && parts.push(`[${key}: ${JSON.stringify(schema[key])}]`);
|
|
8667
|
-
schema.default !== void 0 && parts.push(`[default: ${JSON.stringify(schema.default)}]`);
|
|
8668
|
-
}
|
|
8669
|
-
|
|
8670
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/ui-resource-handler.js
|
|
8671
|
-
var UiResourceHandler = class {
|
|
8672
|
-
manager;
|
|
8673
|
-
log = logger.child({ component: "UiResourceHandler" });
|
|
8674
|
-
constructor(manager) {
|
|
8675
|
-
this.manager = manager;
|
|
8676
|
-
}
|
|
8677
|
-
async readUiResource(serverName, uri) {
|
|
8678
|
-
let log = this.log.child({ server: serverName, uri });
|
|
8679
|
-
if (!uri.startsWith("ui://"))
|
|
8680
|
-
throw new ResourceParseError(uri, "URI must start with ui://", { server: serverName });
|
|
8681
|
-
log.debug("Fetching UI resource");
|
|
8682
|
-
let result;
|
|
8683
|
-
try {
|
|
8684
|
-
result = await this.manager.readResource(serverName, uri);
|
|
8685
|
-
} catch (error) {
|
|
8686
|
-
if (error instanceof UrlElicitationRequiredError)
|
|
8687
|
-
throw error;
|
|
8688
|
-
let message = error instanceof Error ? error.message : String(error);
|
|
8689
|
-
throw log.error("Failed to read resource", error instanceof Error ? error : void 0), new ResourceFetchError(uri, message, {
|
|
8690
|
-
server: serverName,
|
|
8691
|
-
cause: error instanceof Error ? error : void 0
|
|
8692
|
-
});
|
|
8693
|
-
}
|
|
8694
|
-
let content = selectContent(result, uri), mimeType = content.mimeType;
|
|
8695
|
-
if (mimeType && !isHtmlMimeType(mimeType))
|
|
8696
|
-
throw log.warn("Unsupported MIME type", { mimeType }), new ResourceParseError(uri, `unsupported MIME type "${mimeType}" (expected text/html or ${pQ})`, { server: serverName, mimeType });
|
|
8697
|
-
let html = toHtml(content);
|
|
8698
|
-
if (!html.trim())
|
|
8699
|
-
throw log.warn("Resource content is empty"), new ResourceParseError(uri, "content is empty", { server: serverName });
|
|
8700
|
-
let contentMeta = extractUiMeta(content._meta), listMeta = extractUiMeta(this.getListResourceMeta(serverName, uri));
|
|
8701
|
-
return log.debug("Resource loaded successfully", {
|
|
8702
|
-
contentLength: html.length,
|
|
8703
|
-
hasCsp: !!contentMeta.csp || !!listMeta.csp
|
|
8704
|
-
}), {
|
|
8705
|
-
uri: content.uri ?? uri,
|
|
8706
|
-
html,
|
|
8707
|
-
mimeType: mimeType ?? pQ,
|
|
8708
|
-
meta: {
|
|
8709
|
-
csp: contentMeta.csp ?? listMeta.csp,
|
|
8710
|
-
permissions: contentMeta.permissions ?? listMeta.permissions,
|
|
8711
|
-
domain: contentMeta.domain ?? listMeta.domain,
|
|
8712
|
-
prefersBorder: contentMeta.prefersBorder ?? listMeta.prefersBorder
|
|
8713
|
-
}
|
|
8714
|
-
};
|
|
8715
|
-
}
|
|
8716
|
-
getListResourceMeta(serverName, uri) {
|
|
8717
|
-
let connection = this.manager.getConnection(serverName);
|
|
8718
|
-
if (!connection?.resources?.length)
|
|
8719
|
-
return;
|
|
8720
|
-
let resource = connection.resources.find((entry) => entry.uri === uri);
|
|
8721
|
-
if (!(!resource || !resource._meta || typeof resource._meta != "object"))
|
|
8722
|
-
return resource._meta;
|
|
8723
|
-
}
|
|
8724
|
-
};
|
|
8725
|
-
function selectContent(result, preferredUri) {
|
|
8726
|
-
let contents = result.contents ?? [];
|
|
8727
|
-
if (contents.length === 0)
|
|
8728
|
-
throw new Error(`No contents returned for UI resource: ${preferredUri}`);
|
|
8729
|
-
let byUri = contents.find((content) => content.uri === preferredUri);
|
|
8730
|
-
if (byUri)
|
|
8731
|
-
return byUri;
|
|
8732
|
-
let byHtmlMime = contents.find((content) => content.mimeType && isHtmlMimeType(content.mimeType));
|
|
8733
|
-
return byHtmlMime || contents[0];
|
|
8734
|
-
}
|
|
8735
|
-
function isHtmlMimeType(mimeType) {
|
|
8736
|
-
let normalized = mimeType.toLowerCase();
|
|
8737
|
-
return normalized.startsWith("text/html") || normalized === pQ.toLowerCase();
|
|
8738
|
-
}
|
|
8739
|
-
function toHtml(content) {
|
|
8740
|
-
if (typeof content.text == "string")
|
|
8741
|
-
return content.text;
|
|
8742
|
-
if (typeof content.blob == "string")
|
|
8743
|
-
return Buffer.from(content.blob, "base64").toString("utf-8");
|
|
8744
|
-
throw new Error(`UI resource ${content.uri ?? "(unknown)"} did not include text or blob content`);
|
|
8745
|
-
}
|
|
8746
|
-
function extractUiMeta(meta) {
|
|
8747
|
-
if (!meta || typeof meta != "object")
|
|
8748
|
-
return {};
|
|
8749
|
-
let ui = meta.ui;
|
|
8750
|
-
if (!ui || typeof ui != "object")
|
|
8751
|
-
return {};
|
|
8752
|
-
let out = {};
|
|
8753
|
-
return ui.csp && typeof ui.csp == "object" && (out.csp = ui.csp), ui.permissions && typeof ui.permissions == "object" && (out.permissions = ui.permissions), typeof ui.domain == "string" && (out.domain = ui.domain), typeof ui.prefersBorder == "boolean" && (out.prefersBorder = ui.prefersBorder), out;
|
|
8754
|
-
}
|
|
8755
|
-
|
|
8756
|
-
// packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/init.js
|
|
8757
|
-
var FAILURE_BACKOFF_MS = 60 * 1e3;
|
|
8758
|
-
function isTuiMode(ctx) {
|
|
8759
|
-
return ctx.hasUI && ctx.mode === "tui";
|
|
8760
|
-
}
|
|
8761
|
-
async function initializeMcp(pi, ctx, options = {}) {
|
|
8762
|
-
let signal = options.signal ?? ctx.signal;
|
|
8763
|
-
throwIfAborted(signal);
|
|
8764
|
-
let configPath = pi.getFlag("mcp-config"), config = loadMcpConfig(configPath, ctx.cwd), manager = new McpServerManager(ctx.cwd);
|
|
8765
|
-
manager.setDefaultRequestTimeoutMs(config.settings?.requestTimeoutMs);
|
|
8766
|
-
let samplingAutoApprove = config.settings?.samplingAutoApprove === !0;
|
|
8767
|
-
config.settings?.sampling !== !1 && (ctx.hasUI || samplingAutoApprove) && manager.setSamplingConfig({
|
|
8768
|
-
autoApprove: samplingAutoApprove,
|
|
8769
|
-
ui: ctx.hasUI ? ctx.ui : void 0,
|
|
8770
|
-
modelRegistry: ctx.modelRegistry,
|
|
8771
|
-
getCurrentModel: () => ctx.model,
|
|
8772
|
-
getSignal: () => ctx.signal
|
|
8773
|
-
}), config.settings?.elicitation !== !1 && ctx.hasUI && manager.setElicitationConfig({
|
|
8774
|
-
ui: ctx.ui,
|
|
8775
|
-
allowUrl: isTuiMode(ctx)
|
|
8776
|
-
});
|
|
8777
|
-
let lifecycle = new McpLifecycleManager(manager), toolMetadata = /* @__PURE__ */ new Map(), failureTracker = /* @__PURE__ */ new Map(), uiResourceHandler = new UiResourceHandler(manager), consentManager = new ConsentManager("once-per-server"), ui = ctx.hasUI ? ctx.ui : void 0, state = {
|
|
8778
|
-
manager,
|
|
8779
|
-
lifecycle,
|
|
8780
|
-
toolMetadata,
|
|
8781
|
-
config,
|
|
8782
|
-
failureTracker,
|
|
8783
|
-
uiResourceHandler,
|
|
8784
|
-
consentManager,
|
|
8785
|
-
uiServer: null,
|
|
8786
|
-
completedUiSessions: [],
|
|
8787
|
-
openBrowser: (url) => openUrl(pi, url, process.env.BROWSER),
|
|
8788
|
-
ui,
|
|
8789
|
-
sendMessage: (message, options2) => pi.sendMessage(message, options2)
|
|
8790
|
-
};
|
|
8791
|
-
options.onState?.(state);
|
|
8792
|
-
let serverEntries = Object.entries(config.mcpServers);
|
|
8793
|
-
if (serverEntries.length === 0)
|
|
8794
|
-
return state;
|
|
8795
|
-
let idleSetting = typeof config.settings?.idleTimeout == "number" ? config.settings.idleTimeout : 10;
|
|
8796
|
-
lifecycle.setGlobalIdleTimeout(idleSetting);
|
|
8797
|
-
let cachePath = getMetadataCachePath(), cacheFileExists = existsSync2(cachePath), cache = loadMetadataCache(), bootstrapAll = !1;
|
|
8798
|
-
cacheFileExists ? cache || (cache = { version: 1, servers: {} }, saveMetadataCache(cache)) : (bootstrapAll = !0, saveMetadataCache({ version: 1, servers: {} }));
|
|
8799
|
-
let prefix = config.settings?.toolPrefix ?? "server";
|
|
8800
|
-
for (let [name, definition] of serverEntries) {
|
|
8801
|
-
let lifecycleMode = definition.lifecycle ?? "lazy", idleOverride = definition.idleTimeout ?? (lifecycleMode === "eager" ? 0 : void 0);
|
|
8802
|
-
if (lifecycle.registerServer(name, definition, idleOverride !== void 0 ? { idleTimeout: idleOverride } : void 0), lifecycleMode === "keep-alive" && lifecycle.markKeepAlive(name, definition), cache?.servers?.[name] && isServerCacheValid(cache.servers[name], definition)) {
|
|
8803
|
-
let metadata = reconstructToolMetadata(name, cache.servers[name], prefix, definition);
|
|
8804
|
-
toolMetadata.set(name, metadata);
|
|
8805
|
-
}
|
|
8806
|
-
}
|
|
8807
|
-
let startupServers = bootstrapAll ? serverEntries : serverEntries.filter(([, definition]) => {
|
|
8808
|
-
let mode = definition.lifecycle ?? "lazy";
|
|
8809
|
-
return mode === "keep-alive" || mode === "eager";
|
|
8810
|
-
});
|
|
8811
|
-
ctx.hasUI && startupServers.length > 0 && ctx.ui.setStatus("mcp", `MCP: connecting to ${startupServers.length} servers...`);
|
|
8812
|
-
let results = await parallelLimit(startupServers, 10, async ([name, definition]) => {
|
|
8813
|
-
try {
|
|
8814
|
-
throwIfAborted(signal);
|
|
8815
|
-
let connection = await manager.connect(name, definition, signal);
|
|
8816
|
-
return connection.status === "needs-auth" ? { name, definition, connection: null, error: `OAuth authentication required. Run /mcp-auth ${name}.` } : { name, definition, connection, error: null };
|
|
8817
|
-
} catch (error) {
|
|
8818
|
-
let message = error instanceof Error ? error.message : String(error);
|
|
8819
|
-
return { name, definition, connection: null, error: message };
|
|
8820
|
-
}
|
|
8821
|
-
});
|
|
8822
|
-
throwIfAborted(signal);
|
|
8823
|
-
for (let { name, definition, connection, error } of results) {
|
|
8824
|
-
if (error || !connection) {
|
|
8825
|
-
ctx.hasUI && ctx.ui.notify(`MCP: Failed to connect to ${name}: ${error}`, "error"), console.error(`MCP: Failed to connect to ${name}: ${error}`);
|
|
8826
|
-
continue;
|
|
8827
|
-
}
|
|
8828
|
-
let { metadata, failedTools } = buildToolMetadata(connection.tools, connection.resources, definition, name, prefix);
|
|
8829
|
-
toolMetadata.set(name, metadata), updateMetadataCache(state, name), failedTools.length > 0 && ctx.hasUI && ctx.ui.notify(`MCP: ${name} - ${failedTools.length} tools skipped`, "warning");
|
|
8830
|
-
}
|
|
8831
|
-
let connectedCount = results.filter((r2) => r2.connection).length, failedCount = results.filter((r2) => r2.error).length;
|
|
8832
|
-
if (ctx.hasUI && connectedCount > 0) {
|
|
8833
|
-
let totalTools = totalToolCount(state), msg = failedCount > 0 ? `MCP: ${connectedCount}/${startupServers.length} servers connected (${totalTools} tools)` : `MCP: ${connectedCount} servers connected (${totalTools} tools)`;
|
|
8834
|
-
ctx.ui.notify(msg, "info");
|
|
8835
|
-
}
|
|
8836
|
-
if (process.env.MCP_DIRECT_TOOLS !== "__none__") {
|
|
8837
|
-
let currentCache = loadMetadataCache(), missingCacheServers = getMissingConfiguredDirectToolServers(config, currentCache);
|
|
8838
|
-
if (missingCacheServers.length > 0) {
|
|
8839
|
-
let bootstrapResults = await parallelLimit(missingCacheServers.filter((name) => !results.some((r2) => r2.name === name && r2.connection)), 10, async (name) => {
|
|
8840
|
-
let definition = config.mcpServers[name];
|
|
8841
|
-
try {
|
|
8842
|
-
throwIfAborted(signal);
|
|
8843
|
-
let connection = await manager.connect(name, definition, signal);
|
|
8844
|
-
if (connection.status === "needs-auth")
|
|
8845
|
-
return { name, ok: !1 };
|
|
8846
|
-
let { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, name, prefix);
|
|
8847
|
-
return toolMetadata.set(name, metadata), updateMetadataCache(state, name), { name, ok: !0 };
|
|
8848
|
-
} catch (error) {
|
|
8849
|
-
let message = error instanceof Error ? error.message : String(error);
|
|
8850
|
-
return logger.debug(`MCP: direct-tools bootstrap failed for ${name}: ${message}`), { name, ok: !1 };
|
|
8851
|
-
}
|
|
8852
|
-
});
|
|
8853
|
-
throwIfAborted(signal);
|
|
8854
|
-
let bootstrapped = bootstrapResults.filter((r2) => r2.ok).map((r2) => r2.name);
|
|
8855
|
-
bootstrapped.length > 0 && ctx.hasUI && ctx.ui.notify(`MCP: direct tools for ${bootstrapped.join(", ")} will be available after restart`, "info");
|
|
8856
|
-
}
|
|
8857
|
-
}
|
|
8858
|
-
return lifecycle.setReconnectCallback((serverName) => {
|
|
8859
|
-
updateServerMetadata(state, serverName), updateMetadataCache(state, serverName), state.failureTracker.delete(serverName), updateStatusBar(state);
|
|
8860
|
-
}), lifecycle.setIdleShutdownCallback((serverName) => {
|
|
8861
|
-
let idleMinutes = getEffectiveIdleTimeoutMinutes(state, serverName);
|
|
8862
|
-
logger.debug(`${serverName} shut down (idle ${idleMinutes}m)`), updateStatusBar(state);
|
|
8863
|
-
}), lifecycle.startHealthChecks(), state;
|
|
8864
|
-
}
|
|
8865
|
-
function updateServerMetadata(state, serverName) {
|
|
8866
|
-
let connection = state.manager.getConnection(serverName);
|
|
8867
|
-
if (!connection || connection.status !== "connected")
|
|
8868
|
-
return;
|
|
8869
|
-
let definition = state.config.mcpServers[serverName];
|
|
8870
|
-
if (!definition)
|
|
8871
|
-
return;
|
|
8872
|
-
let prefix = state.config.settings?.toolPrefix ?? "server", { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, serverName, prefix);
|
|
8873
|
-
state.toolMetadata.set(serverName, metadata);
|
|
8874
|
-
}
|
|
8875
|
-
function updateMetadataCache(state, serverName) {
|
|
8876
|
-
let connection = state.manager.getConnection(serverName);
|
|
8877
|
-
if (!connection || connection.status !== "connected")
|
|
8878
|
-
return;
|
|
8879
|
-
let definition = state.config.mcpServers[serverName];
|
|
8880
|
-
if (!definition)
|
|
8881
|
-
return;
|
|
8882
|
-
let configHash = computeServerHash(definition), existingEntry = loadMetadataCache()?.servers?.[serverName], tools = serializeTools(connection.tools), resources = definition.exposeResources === !1 ? [] : serializeResources(connection.resources);
|
|
8883
|
-
definition.exposeResources !== !1 && resources.length === 0 && existingEntry?.resources?.length && existingEntry.configHash === configHash && (resources = existingEntry.resources);
|
|
8884
|
-
let entry = {
|
|
8885
|
-
configHash,
|
|
8886
|
-
tools,
|
|
8887
|
-
resources,
|
|
8888
|
-
cachedAt: Date.now()
|
|
8889
|
-
};
|
|
8890
|
-
saveMetadataCache({ version: 1, servers: { [serverName]: entry } });
|
|
8891
|
-
}
|
|
8892
|
-
function flushMetadataCache(state) {
|
|
8893
|
-
for (let [name, connection] of state.manager.getAllConnections())
|
|
8894
|
-
connection.status === "connected" && updateMetadataCache(state, name);
|
|
8895
|
-
}
|
|
8896
|
-
function updateStatusBar(state) {
|
|
8897
|
-
let ui = state.ui;
|
|
8898
|
-
if (!ui)
|
|
8899
|
-
return;
|
|
8900
|
-
let total = Object.keys(state.config.mcpServers).length;
|
|
8901
|
-
if (total === 0) {
|
|
8902
|
-
ui.setStatus("mcp", void 0);
|
|
8903
|
-
return;
|
|
8904
|
-
}
|
|
8905
|
-
let connectedCount = state.manager.getAllConnections().size;
|
|
8906
|
-
ui.setStatus("mcp", ui.theme.fg("accent", `MCP: ${connectedCount}/${total} servers`));
|
|
8907
|
-
}
|
|
8908
|
-
function getFailureAgeSeconds(state, serverName) {
|
|
8909
|
-
let failedAt = state.failureTracker.get(serverName);
|
|
8910
|
-
if (!failedAt)
|
|
8911
|
-
return null;
|
|
8912
|
-
let ageMs = Date.now() - failedAt;
|
|
8913
|
-
return ageMs > FAILURE_BACKOFF_MS ? null : Math.round(ageMs / 1e3);
|
|
8914
|
-
}
|
|
8915
|
-
async function lazyConnect(state, serverName, signal) {
|
|
8916
|
-
let connection = state.manager.getConnection(serverName);
|
|
8917
|
-
if (connection?.status === "needs-auth")
|
|
8918
|
-
return !1;
|
|
8919
|
-
if (connection?.status === "connected")
|
|
8920
|
-
return updateServerMetadata(state, serverName), !0;
|
|
8921
|
-
if (getFailureAgeSeconds(state, serverName) !== null)
|
|
8922
|
-
return !1;
|
|
8923
|
-
let definition = state.config.mcpServers[serverName];
|
|
8924
|
-
if (!definition)
|
|
8925
|
-
return !1;
|
|
8926
|
-
try {
|
|
8927
|
-
return state.ui && state.ui.setStatus("mcp", `MCP: connecting to ${serverName}...`), (await state.manager.connect(serverName, definition, signal)).status === "needs-auth" ? !1 : (state.failureTracker.delete(serverName), updateServerMetadata(state, serverName), updateMetadataCache(state, serverName), updateStatusBar(state), !0);
|
|
8928
|
-
} catch (error) {
|
|
8929
|
-
signal?.aborted && throwIfAborted(signal), state.failureTracker.set(serverName, Date.now());
|
|
8930
|
-
let message = error instanceof Error ? error.message : String(error);
|
|
8931
|
-
return logger.debug(`MCP: lazy connect failed for ${serverName}: ${message}`), updateStatusBar(state), !1;
|
|
8932
|
-
}
|
|
8933
|
-
}
|
|
8934
|
-
function getEffectiveIdleTimeoutMinutes(state, serverName) {
|
|
8935
|
-
let definition = state.config.mcpServers[serverName];
|
|
8936
|
-
return definition ? typeof definition.idleTimeout == "number" ? definition.idleTimeout : (definition.lifecycle ?? "lazy") === "eager" ? 0 : typeof state.config.settings?.idleTimeout == "number" ? state.config.settings.idleTimeout : 10 : typeof state.config.settings?.idleTimeout == "number" ? state.config.settings.idleTimeout : 10;
|
|
8937
|
-
}
|
|
8938
|
-
|
|
8939
6810
|
export {
|
|
8940
|
-
|
|
8941
|
-
|
|
8942
|
-
|
|
8943
|
-
AZ,
|
|
8944
|
-
buildToolMetadata,
|
|
8945
|
-
getToolNames,
|
|
8946
|
-
findToolByName,
|
|
8947
|
-
formatSchema,
|
|
8948
|
-
isTuiMode,
|
|
8949
|
-
initializeMcp,
|
|
8950
|
-
updateServerMetadata,
|
|
8951
|
-
updateMetadataCache,
|
|
8952
|
-
flushMetadataCache,
|
|
8953
|
-
updateStatusBar,
|
|
8954
|
-
getFailureAgeSeconds,
|
|
8955
|
-
lazyConnect
|
|
6811
|
+
AjvJsonSchemaValidator,
|
|
6812
|
+
Client,
|
|
6813
|
+
StdioClientTransport
|
|
8956
6814
|
};
|