@humain/humain-code 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +139 -0
- package/README.md +2 -2
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/anthropic-messages-UZB5HJE3.js +77 -0
- package/dist/bundle/chunks/anthropic.js +25 -24
- package/dist/bundle/chunks/azure-openai-responses-J3LCMWPQ.js +15 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +460 -431
- package/dist/bundle/chunks/bowser-DXKSTXFQ.js +89 -0
- package/dist/bundle/chunks/{chunk-HTA325LJ.js → chunk-2NVGOSBN.js} +1 -1
- package/dist/bundle/chunks/{chunk-5B25YXF7.js → chunk-3CGMVKHA.js} +13 -3
- package/dist/bundle/chunks/{chunk-SCINMV4X.js → chunk-46C6D7UC.js} +22 -21
- package/dist/bundle/chunks/{chunk-RS6PZK35.js → chunk-4EV7CK26.js} +249 -216
- package/dist/bundle/chunks/{chunk-T7BXP46S.js → chunk-4SFWYKL5.js} +1848 -1662
- package/dist/bundle/chunks/{chunk-TGDPZCSW.js → chunk-4TDNOR36.js} +1 -1
- package/dist/bundle/chunks/{chunk-C6VERWRZ.js → chunk-4XF5JX7X.js} +1 -1
- package/dist/bundle/chunks/chunk-6HTHDVJC.js +4 -0
- package/dist/bundle/chunks/{chunk-2G7YVAVF.js → chunk-7EONJCBE.js} +1 -1
- package/dist/bundle/chunks/chunk-7H2WNBX7.js +11 -0
- package/dist/bundle/chunks/{chunk-2FYYW6FY.js → chunk-7OZNMWAJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-R6YQR7TZ.js → chunk-7WE77IE3.js} +1 -1
- package/dist/bundle/chunks/{chunk-Z5YLKK3S.js → chunk-7WETECIB.js} +1 -1
- package/dist/bundle/chunks/{chunk-EIC7CQX3.js → chunk-AI7EHDAX.js} +1 -1
- package/dist/bundle/chunks/{chunk-KRCX3ZBA.js → chunk-APNPBT7Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-4HTVBBJD.js → chunk-ATFZAFMS.js} +2 -2
- package/dist/bundle/chunks/{chunk-R5OOX7RW.js → chunk-B47PNNLL.js} +9 -2
- package/dist/bundle/chunks/{chunk-AZXVJN6E.js → chunk-C4DHVDYT.js} +1 -1
- package/dist/bundle/chunks/{chunk-4PRNKB6V.js → chunk-CET2MXXN.js} +7 -7
- package/dist/bundle/chunks/{chunk-66FZJO75.js → chunk-CU6KU7JK.js} +472 -3924
- package/dist/bundle/chunks/{chunk-MD7K7RPN.js → chunk-D3KYOSQY.js} +1 -1
- package/dist/bundle/chunks/{chunk-I3NDOUHE.js → chunk-DCXHRP6C.js} +1 -1
- package/dist/bundle/chunks/{chunk-OB332KMV.js → chunk-DD5UT56Y.js} +46 -32
- package/dist/bundle/chunks/{chunk-G4QPSFBF.js → chunk-EMBIUIQ2.js} +216 -223
- package/dist/bundle/chunks/{chunk-Q7VXYXY3.js → chunk-ENBDASDN.js} +2 -2
- package/dist/bundle/chunks/{chunk-2H3LUS62.js → chunk-FJIISX5W.js} +241 -229
- package/dist/bundle/chunks/{chunk-WQOOJP7U.js → chunk-GV5OVRKK.js} +1 -1
- package/dist/bundle/chunks/{chunk-KTSJYIYC.js → chunk-HHWVVNGG.js} +1 -1
- package/dist/bundle/chunks/{chunk-4JRER4XK.js → chunk-HQMUDHC3.js} +19 -19
- package/dist/bundle/chunks/{chunk-WQ7EJQIT.js → chunk-IOLLZXQN.js} +225 -239
- package/dist/bundle/chunks/chunk-IXQYPQRQ.js +2079 -0
- package/dist/bundle/chunks/{chunk-RU7ADKA7.js → chunk-J4GII2EE.js} +112 -96
- package/dist/bundle/chunks/chunk-J5TSAJGC.js +22 -0
- package/dist/bundle/chunks/{chunk-QT6ZHDMP.js → chunk-JBSWWCT5.js} +1 -1
- package/dist/bundle/chunks/{chunk-P6AXBESH.js → chunk-JV7VHOAY.js} +1119 -1098
- package/dist/bundle/chunks/{chunk-PWUDFU5V.js → chunk-JWOPWHVH.js} +4 -4
- package/dist/bundle/chunks/{chunk-4V5VL2BO.js → chunk-KLSRGGOH.js} +131 -154
- package/dist/bundle/chunks/{chunk-JF7FYXAI.js → chunk-KONLZKPL.js} +7 -6
- package/dist/bundle/chunks/{chunk-32QLLD2P.js → chunk-KQXXBQ57.js} +360 -332
- package/dist/bundle/chunks/{chunk-UZNIPOGS.js → chunk-L4J7SMJB.js} +1 -1
- package/dist/bundle/chunks/chunk-MPRAQ6ZI.js +41 -0
- package/dist/bundle/chunks/{chunk-GUHNFZ2Q.js → chunk-NNWNIBLG.js} +20 -19
- package/dist/bundle/chunks/{chunk-TWAHPPXN.js → chunk-OVDMYBIT.js} +1307 -1194
- package/dist/bundle/chunks/{chunk-WAPZN4KP.js → chunk-P2Y2H7SD.js} +2 -2
- package/dist/bundle/chunks/{chunk-PPBDDQHP.js → chunk-PGVDL4KB.js} +7 -6
- package/dist/bundle/chunks/{chunk-XHDVDJM7.js → chunk-PVNXN2TC.js} +7 -7
- package/dist/bundle/chunks/{chunk-RNBZBCH2.js → chunk-QJB5YI3I.js} +1 -1
- package/dist/bundle/chunks/{chunk-I5E7RQ5V.js → chunk-QRYDGY5I.js} +5 -5
- package/dist/bundle/chunks/{chunk-4QAXV5T6.js → chunk-R3VDXQW2.js} +9 -9
- package/dist/bundle/chunks/chunk-SKCJ25SX.js +24 -0
- package/dist/bundle/chunks/chunk-SQ7NTRLJ.js +77 -0
- package/dist/bundle/chunks/{chunk-SSRCVJZK.js → chunk-TYN46EVI.js} +5 -5
- package/dist/bundle/chunks/{chunk-6E6RHNOU.js → chunk-UXM4WFLH.js} +12 -11
- package/dist/bundle/chunks/{chunk-LB4CIS4F.js → chunk-VCMXBP5S.js} +17 -17
- package/dist/bundle/chunks/{chunk-N2SNMUD3.js → chunk-VKQNYZUA.js} +1 -1
- package/dist/bundle/chunks/{chunk-JYWUOKOI.js → chunk-WBSGWISD.js} +367 -353
- package/dist/bundle/chunks/{chunk-3EDMWQ35.js → chunk-WGXMYMPE.js} +17 -15
- package/dist/bundle/chunks/chunk-WRYGY5XG.js +24 -0
- package/dist/bundle/chunks/{chunk-GRJUKEE3.js → chunk-XVIQYONJ.js} +4 -4
- package/dist/bundle/chunks/chunk-YSWDFV2L.js +11 -0
- package/dist/bundle/chunks/{chunk-AEWYICBL.js → chunk-Z5UFSRO4.js} +2 -2
- package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
- package/dist/bundle/chunks/chunk-ZTG5OKI7.js +3 -0
- package/dist/bundle/chunks/{cli-H4LJNE2V.js → cli-6DJO467D.js} +2 -2
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-T5R2RVFQ.js → cloudflare-workers-ai-system-one-ETKC6B2S.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +68 -68
- package/dist/bundle/chunks/compat-HS4ARZK3.js +15 -0
- package/dist/bundle/chunks/curator-server-TC7RVVN2.js +3600 -0
- package/dist/bundle/chunks/dist-35STTNYA.js +37 -0
- package/dist/bundle/chunks/{dist-FMWWM4H7.js → dist-5AQPJ2TI.js} +2 -2
- package/dist/bundle/chunks/{dist-NHQTBDHT.js → dist-DYB3AR7C.js} +91 -257
- package/dist/bundle/chunks/dist-NMEXYUP3.js +11 -0
- package/dist/bundle/chunks/dist-cjs-EROMDUKS.js +193 -0
- package/dist/bundle/chunks/{easter-egg-3d-BUEOC3NO.js → easter-egg-3d-VVUF3C3X.js} +1 -1
- package/dist/bundle/chunks/entry-2GZ3PTWQ.js +2 -0
- package/dist/bundle/chunks/{entry-A2CSLKHC.js → entry-SRYLSS5P.js} +3 -3
- package/dist/bundle/chunks/{event-streams-7YGFEPBZ.js → event-streams-F67JLS6B.js} +1 -1
- package/dist/bundle/chunks/{execute-MY5JSEPV.js → execute-I3WGGPWL.js} +2 -2
- package/dist/bundle/chunks/{extract-PTGACPGP.js → extract-QHZTEVJP.js} +68 -65
- package/dist/bundle/chunks/{flow-implementer-APJFY4YI.js → flow-implementer-QMN3HKE2.js} +8 -9
- package/dist/bundle/chunks/github-copilot.js +55 -45
- package/dist/bundle/chunks/google-generative-ai-ZND73WDQ.js +22 -0
- package/dist/bundle/chunks/google-vertex-YAH62YRM.js +25 -0
- package/dist/bundle/chunks/host-Q565BCXB.js +3 -0
- package/dist/bundle/chunks/image-resize-worker.js +3 -3
- package/dist/bundle/chunks/{index.bundle-THL4EUSU.js → index.bundle-HONF3PUD.js} +177 -176
- package/dist/bundle/chunks/{inprocess-5NP5VJHZ.js → inprocess-453SLFL5.js} +6 -6
- package/dist/bundle/chunks/interactive-mode-MVZOJ5OU.js +5 -0
- package/dist/bundle/chunks/{llama-cpp-classify-GJAXULWL.js → llama-cpp-classify-Z4GZY4GC.js} +1 -1
- package/dist/bundle/chunks/mistral-conversations-7I5JURDP.js +43 -0
- package/dist/bundle/chunks/{node-ZFIIS5IM.js → node-IMSYVRPL.js} +53 -30
- package/dist/bundle/chunks/{node-UNHECG4X.js → node-MHHE76P4.js} +475 -440
- package/dist/bundle/chunks/{openai-codex-responses-S7CMCAOY.js → openai-codex-responses-LTHOMN37.js} +30 -29
- package/dist/bundle/chunks/openai-codex.js +9 -8
- package/dist/bundle/chunks/{openai-completions-2Z57N7PC.js → openai-completions-W2X635EE.js} +22 -22
- package/dist/bundle/chunks/{openai-decisions-JIOJDB4C.js → openai-decisions-TN2GNOYI.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-5VBZSTHL.js → openai-responses-DVY4QXOG.js} +4 -5
- package/dist/bundle/chunks/{openrouter-images-S6O7DBEJ.js → openrouter-images-SE2JMS44.js} +1 -1
- package/dist/bundle/chunks/openrouter.js +9 -8
- package/dist/bundle/chunks/pdfjs-FE3L72A6.js +3662 -0
- package/dist/bundle/chunks/{pdfjs-decoders-OFXX4HDZ.js → pdfjs-decoders-VCMCTQJ2.js} +1 -1
- package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-I4K6AIV4.js +295 -0
- package/dist/bundle/chunks/pdfjs-openjpeg-PYQCV6CM.js +590 -0
- package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-G363SGDI.js +775 -0
- package/dist/bundle/chunks/{pi-messages-SMLN5J2W.js → pi-messages-WAS6Z5L5.js} +11 -11
- package/dist/bundle/chunks/radius.js +8 -7
- package/dist/bundle/chunks/{runtime-OYTWXIUM.js → runtime-H7LYNKCZ.js} +1 -1
- package/dist/bundle/chunks/session-picker-XNVLSJ22.js +4 -0
- package/dist/bundle/chunks/startup-ui-3TCT465D.js +3 -0
- package/dist/bundle/chunks/{trace-command-YLDYCL55.js → trace-command-7ORDQ3JS.js} +4 -4
- package/dist/bundle/chunks/{typesafe-system-one-7BEL3H5N.js → typesafe-system-one-AAZH6S3I.js} +1 -1
- package/dist/bundle/chunks/{undici-C6S56CGI.js → undici-WVNE45GY.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-CIVXCEAN.js +28 -0
- package/dist/bundle/cli-runtime.js +5 -5
- package/dist/bundle/flow/package.json +5 -5
- package/dist/bundle/index.js +13 -13
- package/dist/bundle/orchestrate/package.json +22 -6
- package/dist/bundle/rpc-entry.js +4 -5
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +4 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/config-selector.d.ts.map +1 -1
- package/dist/cli/config-selector.js +9 -6
- package/dist/cli/config-selector.js.map +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js +9 -6
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +8 -4
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +11 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +19 -0
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +0 -2
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +0 -2
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +31 -39
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +231 -535
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/anthropic-subscription-usage.d.ts +4 -2
- package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
- package/dist/core/anthropic-subscription-usage.js +32 -16
- package/dist/core/anthropic-subscription-usage.js.map +1 -1
- package/dist/core/auto-session-namer.js +1 -1
- package/dist/core/auto-session-namer.js.map +1 -1
- package/dist/core/cache-warmer.d.ts.map +1 -1
- package/dist/core/cache-warmer.js +2 -0
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/exec.d.ts +1 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +4 -1
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/ansi-to-html.d.ts +6 -1
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js +57 -20
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/template.js +1 -1
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +2 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +18 -1
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +5 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +5 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/flow-implementer.d.ts.map +1 -1
- package/dist/core/flow-implementer.js +3 -9
- package/dist/core/flow-implementer.js.map +1 -1
- package/dist/core/keybindings.d.ts +40 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +5 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-config.d.ts +13 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-registry.d.ts +3 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +32 -8
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +0 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +3 -10
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +18 -7
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +41 -8
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/oauth-account-pool.d.ts +5 -0
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +34 -3
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/core/package-manager.d.ts +16 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +46 -3
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +1 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +7 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts +5 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +2 -0
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-outcome.d.ts +6 -3
- package/dist/core/run-outcome.d.ts.map +1 -1
- package/dist/core/run-outcome.js +36 -9
- package/dist/core/run-outcome.js.map +1 -1
- package/dist/core/run-preflight.d.ts +1 -1
- package/dist/core/run-preflight.d.ts.map +1 -1
- package/dist/core/run-preflight.js +19 -11
- package/dist/core/run-preflight.js.map +1 -1
- package/dist/core/sdk.d.ts +0 -6
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +7 -16
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +0 -5
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +0 -9
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +0 -4
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +0 -1
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/tools/bash-jobs.d.ts.map +1 -1
- package/dist/core/tools/bash-jobs.js +2 -9
- package/dist/core/tools/bash-jobs.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +28 -16
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +4 -1
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/read.d.ts +8 -4
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +10 -15
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/renderers/read.d.ts.map +1 -1
- package/dist/core/tools/renderers/read.js +6 -2
- package/dist/core/tools/renderers/read.js.map +1 -1
- package/dist/core/tools/subagent-worktree.d.ts.map +1 -1
- package/dist/core/tools/subagent-worktree.js +2 -10
- package/dist/core/tools/subagent-worktree.js.map +1 -1
- package/dist/core/trace-client/credential-store.d.ts.map +1 -1
- package/dist/core/trace-client/credential-store.js +9 -5
- package/dist/core/trace-client/credential-store.js.map +1 -1
- package/dist/extensions/codemode/execute.js +2 -2
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +6 -4
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/extensions/usage/account-reconnect.d.ts +5 -0
- package/dist/extensions/usage/account-reconnect.d.ts.map +1 -0
- package/dist/extensions/usage/account-reconnect.js +12 -0
- package/dist/extensions/usage/account-reconnect.js.map +1 -0
- package/dist/extensions/usage/hcode-overview.d.ts +6 -19
- package/dist/extensions/usage/hcode-overview.d.ts.map +1 -1
- package/dist/extensions/usage/hcode-overview.js +86 -100
- package/dist/extensions/usage/hcode-overview.js.map +1 -1
- package/dist/extensions/usage/index.d.ts.map +1 -1
- package/dist/extensions/usage/index.js +74 -98
- package/dist/extensions/usage/index.js.map +1 -1
- package/dist/extensions/usage/overview.d.ts +22 -17
- package/dist/extensions/usage/overview.d.ts.map +1 -1
- package/dist/extensions/usage/overview.js +98 -13
- package/dist/extensions/usage/overview.js.map +1 -1
- package/dist/extensions/usage/popup.d.ts +9 -14
- package/dist/extensions/usage/popup.d.ts.map +1 -1
- package/dist/extensions/usage/popup.js +78 -165
- package/dist/extensions/usage/popup.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +4 -1
- package/dist/humain/flow-command.js +1 -1
- package/dist/humain/flow-command.js.map +1 -1
- package/dist/humain/flow-loader.d.ts +9 -4
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +30 -21
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/humain/gateway/client.d.ts +3 -1
- package/dist/humain/gateway/client.d.ts.map +1 -1
- package/dist/humain/gateway/client.js +10 -5
- package/dist/humain/gateway/client.js.map +1 -1
- package/dist/humain/gateway/login.d.ts.map +1 -1
- package/dist/humain/gateway/login.js +160 -53
- package/dist/humain/gateway/login.js.map +1 -1
- package/dist/humain/hcode/account-store.d.ts +29 -5
- package/dist/humain/hcode/account-store.d.ts.map +1 -1
- package/dist/humain/hcode/account-store.js +224 -124
- package/dist/humain/hcode/account-store.js.map +1 -1
- package/dist/humain/hcode/account.d.ts +6 -0
- package/dist/humain/hcode/account.d.ts.map +1 -1
- package/dist/humain/hcode/account.js +348 -129
- package/dist/humain/hcode/account.js.map +1 -1
- package/dist/humain/hcode/catalog-watch.d.ts +21 -0
- package/dist/humain/hcode/catalog-watch.d.ts.map +1 -0
- package/dist/humain/hcode/catalog-watch.js +46 -0
- package/dist/humain/hcode/catalog-watch.js.map +1 -0
- package/dist/humain/hcode/contracts.d.ts +16 -1
- package/dist/humain/hcode/contracts.d.ts.map +1 -1
- package/dist/humain/hcode/contracts.js +122 -128
- package/dist/humain/hcode/contracts.js.map +1 -1
- package/dist/humain/hcode/environment.d.ts +3 -1
- package/dist/humain/hcode/environment.d.ts.map +1 -1
- package/dist/humain/hcode/environment.js +12 -2
- package/dist/humain/hcode/environment.js.map +1 -1
- package/dist/humain/hcode/facade.d.ts +26 -6
- package/dist/humain/hcode/facade.d.ts.map +1 -1
- package/dist/humain/hcode/facade.js +148 -38
- package/dist/humain/hcode/facade.js.map +1 -1
- package/dist/humain/hcode/http.d.ts +3 -1
- package/dist/humain/hcode/http.d.ts.map +1 -1
- package/dist/humain/hcode/http.js +44 -23
- package/dist/humain/hcode/http.js.map +1 -1
- package/dist/humain/hcode/images.d.ts +67 -0
- package/dist/humain/hcode/images.d.ts.map +1 -0
- package/dist/humain/hcode/images.js +463 -0
- package/dist/humain/hcode/images.js.map +1 -0
- package/dist/humain/hcode/login-copy.d.ts +28 -0
- package/dist/humain/hcode/login-copy.d.ts.map +1 -0
- package/dist/humain/hcode/login-copy.js +74 -0
- package/dist/humain/hcode/login-copy.js.map +1 -0
- package/dist/humain/hcode/login-failure.d.ts +26 -0
- package/dist/humain/hcode/login-failure.d.ts.map +1 -0
- package/dist/humain/hcode/login-failure.js +50 -0
- package/dist/humain/hcode/login-failure.js.map +1 -0
- package/dist/humain/hcode/notices.d.ts +24 -1
- package/dist/humain/hcode/notices.d.ts.map +1 -1
- package/dist/humain/hcode/notices.js +93 -7
- package/dist/humain/hcode/notices.js.map +1 -1
- package/dist/humain/hcode/provider.d.ts +7 -3
- package/dist/humain/hcode/provider.d.ts.map +1 -1
- package/dist/humain/hcode/provider.js +123 -19
- package/dist/humain/hcode/provider.js.map +1 -1
- package/dist/humain/hcode/selection.d.ts +2 -0
- package/dist/humain/hcode/selection.d.ts.map +1 -1
- package/dist/humain/hcode/selection.js +8 -1
- package/dist/humain/hcode/selection.js.map +1 -1
- package/dist/humain/hcode/transport.d.ts +13 -10
- package/dist/humain/hcode/transport.d.ts.map +1 -1
- package/dist/humain/hcode/transport.js +103 -148
- package/dist/humain/hcode/transport.js.map +1 -1
- package/dist/humain/hcode/wire.d.ts +3 -0
- package/dist/humain/hcode/wire.d.ts.map +1 -1
- package/dist/humain/hcode/wire.js +11 -0
- package/dist/humain/hcode/wire.js.map +1 -1
- package/dist/humain/metadata/contracts.d.ts +1 -0
- package/dist/humain/metadata/contracts.d.ts.map +1 -1
- package/dist/humain/metadata/contracts.js +2 -1
- package/dist/humain/metadata/contracts.js.map +1 -1
- package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/anysearch.js +7 -3
- package/dist/humain/web-access/vendor/anysearch.js.map +1 -1
- package/dist/humain/web-access/vendor/autom.d.ts +4 -0
- package/dist/humain/web-access/vendor/autom.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/autom.js +191 -0
- package/dist/humain/web-access/vendor/autom.js.map +1 -0
- package/dist/humain/web-access/vendor/cloro.d.ts +4 -0
- package/dist/humain/web-access/vendor/cloro.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/cloro.js +236 -0
- package/dist/humain/web-access/vendor/cloro.js.map +1 -0
- package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-page.js +7 -1
- package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.js +6 -0
- package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
- package/dist/humain/web-access/vendor/domain-filter-normalization.d.ts +8 -0
- package/dist/humain/web-access/vendor/domain-filter-normalization.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/domain-filter-normalization.js +37 -0
- package/dist/humain/web-access/vendor/domain-filter-normalization.js.map +1 -1
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts +28 -8
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js +135 -34
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js.map +1 -1
- package/dist/humain/web-access/vendor/duckduckgo.d.ts +1 -1
- package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/duckduckgo.js +10 -3
- package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -1
- package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/extract.js +61 -5
- package/dist/humain/web-access/vendor/extract.js.map +1 -1
- package/dist/humain/web-access/vendor/gemini-search.d.ts +3 -3
- package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/gemini-search.js +35 -5
- package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
- package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/index.js +8 -1
- package/dist/humain/web-access/vendor/index.js.map +1 -1
- package/dist/humain/web-access/vendor/page-query.d.ts +5 -0
- package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/page-query.js +12 -2
- package/dist/humain/web-access/vendor/page-query.js.map +1 -1
- package/dist/humain/web-access/vendor/specstream.d.ts +6 -0
- package/dist/humain/web-access/vendor/specstream.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/specstream.js +253 -0
- package/dist/humain/web-access/vendor/specstream.js.map +1 -0
- package/dist/humain/web-access/vendor/tool-activation.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/tool-activation.js +21 -5
- package/dist/humain/web-access/vendor/tool-activation.js.map +1 -1
- package/dist/humain/web-access/vendor/upgrade-notice.d.ts +1 -1
- package/dist/humain/web-access/vendor/upgrade-notice.js +1 -1
- package/dist/humain/web-access/vendor/upgrade-notice.js.map +1 -1
- package/dist/humain/web-access/vendor/utils.d.ts +1 -0
- package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/utils.js +3 -0
- package/dist/humain/web-access/vendor/utils.js.map +1 -1
- package/dist/humain/web-access/vendor/video-extract.js +2 -2
- package/dist/humain/web-access/vendor/video-extract.js.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-core.d.ts +13 -0
- package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-core.js +16 -5
- package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
- package/dist/humain/web-access/vendor/youtube-extract.js +2 -2
- package/dist/humain/web-access/vendor/youtube-extract.js.map +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +96 -28
- package/dist/main.js.map +1 -1
- package/dist/modes/diagnostics-stderr.d.ts +4 -0
- package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
- package/dist/modes/diagnostics-stderr.js +11 -0
- package/dist/modes/diagnostics-stderr.js.map +1 -0
- package/dist/modes/interactive/components/assistant-message.d.ts +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +5 -2
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +14 -5
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +2 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +6 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +10 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +101 -23
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +5 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +17 -6
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/radius-login-selector.js +2 -1
- package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +13 -6
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +8 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +41 -9
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +5 -1
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +0 -17
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-indicator.js +1 -78
- package/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/dist/modes/interactive/components/themed-text.d.ts +1 -1
- package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
- package/dist/modes/interactive/components/themed-text.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +5 -1
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +3 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/trust-selector.js +14 -5
- package/dist/modes/interactive/components/trust-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +1 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +20 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +605 -223
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-catalog-refresh.d.ts +4 -0
- package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
- package/dist/modes/interactive/model-catalog-refresh.js +40 -1
- package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
- package/dist/modes/interactive/oauth-account-format.d.ts +6 -2
- package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
- package/dist/modes/interactive/oauth-account-format.js +12 -3
- package/dist/modes/interactive/oauth-account-format.js.map +1 -1
- package/dist/modes/interactive/session-share.js +2 -0
- package/dist/modes/interactive/session-share.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +30 -32
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +26 -39
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +1 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +14 -1
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/abort.d.ts +5 -0
- package/dist/utils/abort.d.ts.map +1 -1
- package/dist/utils/abort.js +9 -0
- package/dist/utils/abort.js.map +1 -1
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/changelog.js +3 -2
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/flush-stdout.d.ts +8 -0
- package/dist/utils/flush-stdout.d.ts.map +1 -0
- package/dist/utils/flush-stdout.js +23 -0
- package/dist/utils/flush-stdout.js.map +1 -0
- package/dist/utils/image-process.d.ts +2 -0
- package/dist/utils/image-process.d.ts.map +1 -1
- package/dist/utils/image-process.js +3 -3
- package/dist/utils/image-process.js.map +1 -1
- package/dist/utils/image-resize-core.js +2 -2
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/shell.d.ts +2 -0
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +19 -0
- package/dist/utils/shell.js.map +1 -1
- package/docs/cli.md +1 -1
- package/docs/development.md +0 -13
- package/docs/extensions.md +6 -4
- package/docs/flow.md +4 -62
- package/docs/humain-code-forge-architecture.md +1 -47
- package/docs/humain-code-forge-flow-walkthrough.md +1 -1
- package/docs/humain-code.md +1 -1
- package/docs/keybindings.md +2 -0
- package/docs/llama-cpp.md +5 -5
- package/docs/models-configuration.md +4 -2
- package/docs/nvidia-rtx-llama-cpp.md +5 -5
- package/docs/providers.md +14 -9
- package/docs/rpc-commands.md +1 -1
- package/docs/run-preflight.md +1 -1
- package/docs/slash-commands.md +1 -1
- package/docs/tui.md +2 -0
- package/examples/README.md +0 -3
- package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/gondolin/index.ts +4 -7
- package/examples/tsconfig.json +96 -76
- package/npm-shrinkwrap.json +285 -764
- package/package.json +24 -37
- package/schemas/keybindings.schema.json +20 -0
- package/schemas/models.schema.json +5 -1
- package/schemas/settings.schema.json +0 -13
- package/src/humain/web-access/UPSTREAM.md +52 -1
- package/src/humain/web-access/upstream.json +5 -5
- package/src/humain/web-access/vendor/CHANGELOG.md +29 -0
- package/dist/bundle/chunks/adaptive-peer-worker-X2ZNZE3S.js +0 -8
- package/dist/bundle/chunks/adaptive-session-host-7KDSQV5I.js +0 -162
- package/dist/bundle/chunks/anthropic-messages-TQK3FUV3.js +0 -68
- package/dist/bundle/chunks/azure-openai-responses-JY7OSLH2.js +0 -15
- package/dist/bundle/chunks/chunk-5L4PBYC7.js +0 -11
- package/dist/bundle/chunks/chunk-6PNQYO6A.js +0 -10
- package/dist/bundle/chunks/chunk-CRN54O4D.js +0 -24
- package/dist/bundle/chunks/chunk-CTU2ECLD.js +0 -7
- package/dist/bundle/chunks/chunk-DBL35X7L.js +0 -3
- package/dist/bundle/chunks/chunk-GME4AWDG.js +0 -23
- package/dist/bundle/chunks/chunk-GTILMMUF.js +0 -12
- package/dist/bundle/chunks/chunk-J57HOSWD.js +0 -21
- package/dist/bundle/chunks/chunk-KQM7ZGL6.js +0 -11
- package/dist/bundle/chunks/chunk-MX4Q4W6H.js +0 -214
- package/dist/bundle/chunks/chunk-NXA6NEHE.js +0 -54
- package/dist/bundle/chunks/chunk-PJACZCIR.js +0 -2
- package/dist/bundle/chunks/chunk-T5A6T24H.js +0 -93
- package/dist/bundle/chunks/chunk-WCFHG6NO.js +0 -16
- package/dist/bundle/chunks/chunk-ZJUU6WOV.js +0 -2052
- package/dist/bundle/chunks/compat-ZK2DIW3P.js +0 -15
- package/dist/bundle/chunks/dist-EY7YKQHB.js +0 -11
- package/dist/bundle/chunks/dist-J5IUPLMH.js +0 -37
- package/dist/bundle/chunks/dist-cjs-2SKN226B.js +0 -184
- package/dist/bundle/chunks/entry-AL54ZGYO.js +0 -2
- package/dist/bundle/chunks/es5-GYTRHFKS.js +0 -77
- package/dist/bundle/chunks/google-generative-ai-UL7YEQ6J.js +0 -21
- package/dist/bundle/chunks/google-vertex-OTMSPUYH.js +0 -26
- package/dist/bundle/chunks/host-75YAHLDR.js +0 -3
- package/dist/bundle/chunks/interactive-mode-IW4PIVAQ.js +0 -5
- package/dist/bundle/chunks/mistral-conversations-E72Y6OC3.js +0 -43
- package/dist/bundle/chunks/pdfjs-AKD6EBKN.js +0 -3614
- package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-FH3KJM4H.js +0 -326
- package/dist/bundle/chunks/pdfjs-openjpeg-SKR7C34X.js +0 -671
- package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-VUBL7UEE.js +0 -974
- package/dist/bundle/chunks/session-picker-DM6S37IF.js +0 -4
- package/dist/bundle/chunks/startup-ui-4GGLWNSU.js +0 -3
- package/dist/bundle/chunks/virtual-modules-TI3W24YL.js +0 -28
- package/dist/core/internal-process.d.ts +0 -23
- package/dist/core/internal-process.d.ts.map +0 -1
- package/dist/core/internal-process.js +0 -88
- package/dist/core/internal-process.js.map +0 -1
- package/dist/humain/adaptive-execution.d.ts +0 -51
- package/dist/humain/adaptive-execution.d.ts.map +0 -1
- package/dist/humain/adaptive-execution.js +0 -100
- package/dist/humain/adaptive-execution.js.map +0 -1
- package/dist/humain/adaptive-peer-process.d.ts +0 -44
- package/dist/humain/adaptive-peer-process.d.ts.map +0 -1
- package/dist/humain/adaptive-peer-process.js +0 -159
- package/dist/humain/adaptive-peer-process.js.map +0 -1
- package/dist/humain/adaptive-peer-worker.d.ts +0 -3
- package/dist/humain/adaptive-peer-worker.d.ts.map +0 -1
- package/dist/humain/adaptive-peer-worker.js +0 -122
- package/dist/humain/adaptive-peer-worker.js.map +0 -1
- package/dist/humain/adaptive-runtime-types.d.ts +0 -621
- package/dist/humain/adaptive-runtime-types.d.ts.map +0 -1
- package/dist/humain/adaptive-runtime-types.js +0 -3
- package/dist/humain/adaptive-runtime-types.js.map +0 -1
- package/dist/humain/adaptive-session-host.d.ts +0 -113
- package/dist/humain/adaptive-session-host.d.ts.map +0 -1
- package/dist/humain/adaptive-session-host.js +0 -1838
- package/dist/humain/adaptive-session-host.js.map +0 -1
- package/dist/utils/deprecation.d.ts +0 -4
- package/dist/utils/deprecation.d.ts.map +0 -1
- package/dist/utils/deprecation.js +0 -13
- package/dist/utils/deprecation.js.map +0 -1
- package/examples/plugins/pi-example-plugin/README.md +0 -38
- package/examples/plugins/pi-example-plugin/package.json +0 -10
- package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
- package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
- package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
|
@@ -1,47 +1,8 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{
|
|
3
|
-
let environmentValue=process.env.HUMAIN_TERMINAL_WEB_ACCESS_ALLOW_HTTP_BASE_URLS??process.env.PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS;if(environmentValue!==void 0){let value2=environmentValue.trim().toLowerCase();if(value2==="true"||value2==="1")return!0;if(value2==="false"||value2==="0")return!1;throw new Error("Invalid configuration: HUMAIN_TERMINAL_WEB_ACCESS_ALLOW_HTTP_BASE_URLS (or PI_WEB_ACCESS_ALLOW_HTTP_BASE_URLS) must be true, false, 1, or 0")}let path=getWebSearchConfigPath();if(!existsSync(
|
|
4
|
-
path))return!1;let raw;try{raw=JSON.parse(readFileSync(path,"utf-8"))}catch(err){throw new Error(`Failed to parse ${path}: ${err instanceof Error?err.message:String(err)}`)}let value=isRecord(raw)?raw.allowHttpBaseUrls:void 0;if(value!==void 0&&typeof value!="boolean")throw new Error(`allowHttpBaseUrls in ${path} must be a boolean`);return value===!0}function resolveApiBaseUrl(options){let fromEnvironment=options.environmentValue!==void 0,value=fromEnvironment?options.environmentValue:options.configuredValue;
|
|
5
|
-
if(value===void 0)return options.defaultValue;let source=fromEnvironment?options.environmentKey:`${options.configKey} in ${getWebSearchConfigPath()}`;if(typeof value!="string"||value.trim().length===0)throw new Error(`${source} must be an absolute HTTP(S) URL`);let url;try{url=new URL(value.trim())}catch{throw new Error(`${source} must be an absolute HTTP(S) URL`)}if(url.protocol!=="https:"&&(url.protocol!=="http:"||!isLoopbackHostname(url.hostname)&&!allowsHttpBaseUrls()))throw new Error(`${source}\
|
|
6
|
-
must be an absolute HTTPS URL`);if(url.username||url.password)throw new Error(`${source} must not include credentials`);if(url.search||url.hash)throw new Error(`${source} must not include query parameters or fragments`);return url.search="",url.hash="",url.pathname=url.pathname.replace(/\/+$/,""),url.toString().replace(/\/+$/,"")}var PI_PREFIXED_ENVIRONMENT_STEMS=new Set(["ollama","deepseek","tabstack"]);function resolveProviderApiUrl(configStem,defaultUrl,configuredValue){let official=new URL(
|
|
7
|
-
defaultUrl),stemKey=configStem.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toUpperCase()+"_BASE_URL",environmentKey=PI_PREFIXED_ENVIRONMENT_STEMS.has(configStem)?process.env[`HUMAIN_TERMINAL_${stemKey}`]!==void 0?`HUMAIN_TERMINAL_${stemKey}`:`PI_${stemKey}`:stemKey;return resolveApiBaseUrl({configKey:configStem+"BaseUrl",configuredValue,defaultValue:official.origin,environmentKey,environmentValue:process.env[environmentKey]})+official.pathname+official.search}var API_REDIRECT_STATUSES=new Set([301,302,
|
|
8
|
-
303,307,308]),API_REQUEST_BODY_HEADERS=["Content-Encoding","Content-Language","Content-Location","Content-Type"],MAX_API_REDIRECTS=5;async function fetchWithCredentialRedirects(url,init,credentialHeaders,credentialQueryParams=[]){let current=new URL(url),source=new URL(url);for(let name of credentialQueryParams)source.searchParams.delete(name);let requestInit=init;for(let redirects=0;;redirects++){let response=await fetch(current,{...requestInit,redirect:"manual"});if(!API_REDIRECT_STATUSES.has(
|
|
9
|
-
response.status))return response;let location=response.headers.get("location");if(!location)return response;if(redirects===MAX_API_REDIRECTS)throw new Error(`Too many API redirects from ${source}`);let next=new URL(location,current);if(next.protocol!=="http:"&&next.protocol!=="https:")throw new Error(`API redirect from ${current.origin} must use HTTP(S)`);let method=requestInit.method?.toUpperCase()??"GET";if((response.status===301||response.status===302)&&method==="POST"||response.status===303&&
|
|
10
|
-
method!=="GET"&&method!=="HEAD"){let headers=new Headers(requestInit.headers);for(let name of API_REQUEST_BODY_HEADERS)headers.delete(name);let{body:_body,...withoutBody}=requestInit;requestInit={...withoutBody,method:"GET",headers}}if(next.origin!==current.origin){for(let name of credentialQueryParams)next.searchParams.delete(name);let headers=new Headers(requestInit.headers);for(let name of credentialHeaders)headers.delete(name);requestInit={...requestInit,headers}}current=next}}var LOCAL_CURATOR_NETWORK_DEFAULTS={
|
|
11
|
-
enabled:!1,host:"localhost",bind:"127.0.0.1"};function trimmedString(value){if(typeof value!="string")return;let trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function resolveCuratorNetworkConfig(){let configPath=getWebSearchConfigPath();if(!existsSync(configPath))return LOCAL_CURATOR_NETWORK_DEFAULTS;let raw;try{raw=JSON.parse(readFileSync(configPath,"utf-8"))}catch{return LOCAL_CURATOR_NETWORK_DEFAULTS}if(!raw||typeof raw!="object"||Array.isArray(raw))return LOCAL_CURATOR_NETWORK_DEFAULTS;
|
|
12
|
-
let curatorRemote=raw.curatorRemote;if(curatorRemote===!0)return{enabled:!0,host:hostname(),bind:"0.0.0.0"};if(curatorRemote&&typeof curatorRemote=="object"&&!Array.isArray(curatorRemote)){let obj=curatorRemote;return{enabled:!0,host:trimmedString(obj.host)??hostname(),bind:trimmedString(obj.bind)??"0.0.0.0"}}return LOCAL_CURATOR_NETWORK_DEFAULTS}function formatSeconds(s){let h=Math.floor(s/3600),m=Math.floor(s%3600/60),sec=s%60;return h>0?`${h}:${String(m).padStart(2,"0")}:${String(sec).padStart(
|
|
13
|
-
2,"0")}`:`${m}:${String(sec).padStart(2,"0")}`}function readExecError(err){if(!err||typeof err!="object")return{stderr:"",message:String(err)};let code=err.code,message=err.message??"",stderrRaw=err.stderr,stderr=Buffer.isBuffer(stderrRaw)?stderrRaw.toString("utf-8"):typeof stderrRaw=="string"?stderrRaw:"";return{code,stderr,message}}function isTimeoutError(err){if(!err||typeof err!="object")return!1;if(err.killed)return!0;let name=err.name,code=err.code,message=err.message??"";return name==="Ab\
|
|
14
|
-
ortError"||code==="ETIMEDOUT"||message.toLowerCase().includes("timed out")}function trimErrorText(text2){return text2.replace(/\s+/g," ").trim().slice(0,200)}function mapFfmpegError(err){let{code,stderr,message}=readExecError(err);if(code==="ENOENT")return"ffmpeg is not installed. Install with: brew install ffmpeg";if(isTimeoutError(err))return"ffmpeg timed out extracting frame";if(stderr.includes("403"))return"Stream URL returned 403 \u2014 may have expired, try again";let snippet=trimErrorText(
|
|
15
|
-
stderr||message);return snippet?`ffmpeg failed: ${snippet}`:"ffmpeg failed"}var sharedProxyState=globalThis,proxyStorage=sharedProxyState[Symbol.for("pi-web-access.proxyStorage")]??=new AsyncLocalStorage;function normalizeProxyUrl(value,source){if(value==null)return null;if(typeof value!="string")throw new Error(`${source} must be an http(s) or socks proxy URL string`);let trimmed=value.trim();if(!trimmed)return null;let parsed;try{parsed=new URL(trimmed)}catch{throw new Error(`${source} must be\
|
|
16
|
-
a valid proxy URL: ${JSON.stringify(trimmed)}`)}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:"&&parsed.protocol!=="socks4:"&&parsed.protocol!=="socks4a:"&&parsed.protocol!=="socks5:"&&parsed.protocol!=="socks5h:")throw new Error(`${source} must use the http://, https://, or socks scheme: ${trimmed}`);if(!parsed.hostname)throw new Error(`${source} must include a proxy host: ${trimmed}`);return parsed.hash="",parsed.search="",parsed.toString()}function redactProxyUrl(value){let parsed=new URL(
|
|
17
|
-
value);return parsed.username&&(parsed.username="redacted"),parsed.password&&(parsed.password="redacted"),parsed.toString()}function loadProxyConfig(){let config={},path=getWebSearchConfigPath();if(existsSync(path)){let raw;try{raw=JSON.parse(readFileSync(path,"utf-8"))}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to load proxy config from ${path}: ${message}`)}raw&&typeof raw=="object"&&!Array.isArray(raw)&&(config=raw)}if(config.lockProxy!==void 0&&
|
|
18
|
-
typeof config.lockProxy!="boolean")throw new Error(`lockProxy in ${path} must be true or false`);let locked=config.lockProxy===!0,proxy=config.proxy===void 0?null:normalizeProxyUrl(config.proxy,`proxy in ${path}`);if(locked&&proxy===null)throw new Error(`lockProxy is set in ${path} but no proxy is configured there; set proxy or remove lockProxy`);return{proxy,locked}}function loadConfiguredProxy(){return loadProxyConfig().proxy}function runWithProxy(proxy,fn){let{proxy:configured,locked}=loadProxyConfig(),
|
|
19
|
-
normalized=proxy===void 0?configured:normalizeProxyUrl(proxy,"proxy");if(locked&&normalized!==configured)throw new Error(`proxy argument rejected: lockProxy is set in ${getWebSearchConfigPath()}; omit proxy to use the configured proxy`);return normalized!==null&&installGlobalProxyFetch(),proxyStorage.run(normalized,fn)}function getActiveProxy(){return proxyStorage.getStore()??null}function hasScopedProxyDecision(){return proxyStorage.getStore()!==void 0}function noProxyEntryMatches(hostname2,entry){
|
|
20
|
-
if(!entry)return!1;if(entry==="*")return!0;let host=entry;if(host.startsWith("[")){let close=host.indexOf("]");close>0&&(host=host.slice(0,close+1))}else{let colon=host.lastIndexOf(":");colon>-1&&/^\d+$/.test(host.slice(colon+1))&&(host=host.slice(0,colon))}return host=host.toLowerCase().replace(/^\[|\]$/g,""),host?hostname2===host||hostname2.endsWith(host.startsWith(".")?host:`.${host}`):!1}function getMetadataServerOrigin(){let host=process.env.GCE_METADATA_HOST?.trim()||"metadata.google.inter\
|
|
21
|
-
nal";try{let url=new URL(/^https?:\/\//i.test(host)?host:`http://${host}`);if(!/^https?:$/.test(url.protocol)||!url.hostname||url.username||url.password||url.pathname!=="/"||url.search||url.hash||/\s/.test(host))throw new Error("Invalid metadata host");return url.origin}catch{throw new Error("GCE_METADATA_HOST must be an HTTP(S) host with an optional port, without credentials, path, query or fragment")}}function isProxyBypassedUrl(url){let hostname2=url.hostname.toLowerCase().replace(/^\[|\]$/g,
|
|
22
|
-
"");if(hostname2==="localhost"||hostname2.endsWith(".localhost")||hostname2==="127.0.0.1"||hostname2==="::1"||hostname2==="metadata.google.internal"||hostname2==="169.254.169.254"||process.env.GCE_METADATA_HOST?.trim()&&url.origin===getMetadataServerOrigin())return!0;let noProxy=process.env.NO_PROXY||process.env.no_proxy;return!!(noProxy&&noProxy.split(",").some(entry=>noProxyEntryMatches(hostname2,entry.trim())))}function installGlobalProxyFetch(){let current=globalThis.fetch;if(typeof current!=
|
|
23
|
-
"function"||current.__piWebAccessSharedProxyFetch===!0)return;let nativeFetch=current,wrapped=(async(input,init)=>{let proxy=init?.__proxy??(hasScopedProxyDecision()?getActiveProxy():null);if(!proxy)return nativeFetch(input,init);let url=null;try{url=new URL(typeof input=="string"||input instanceof URL?input:input.url)}catch{url=null}if(!url||url.protocol!=="http:"&&url.protocol!=="https:"||isProxyBypassedUrl(url))return nativeFetch(input,init);if(input instanceof Request||init?.body instanceof FormData||
|
|
24
|
-
init?.body instanceof Blob){let request=new Request(input,init);request.signal.throwIfAborted();let body=request.body===null?null:new Uint8Array(await new Response(request.body.pipeThrough(new TransformStream,{signal:request.signal})).arrayBuffer());init={...init,method:request.method,headers:request.headers,body,signal:request.signal,redirect:request.redirect}}return fetchViaCurl(url,init??{},{command:["curl"],proxy})});wrapped.__piWebAccessSharedProxyFetch=!0,current.__piWebAccessProxyFetch===
|
|
25
|
-
!0&&(wrapped.__piWebAccessProxyFetch=!0),globalThis.fetch=wrapped}function createCurlFetch(command,{maxBytes,envProxy}){return async(input,init)=>{let url=new URL(input instanceof Request?input.url:input),proxy;if(init?.__proxy!==void 0||hasScopedProxyDecision()){let chosen=init?.__proxy??getActiveProxy();proxy=chosen&&!isProxyBypassedUrl(url)?chosen:null}else proxy=envProxy(url);return fetchViaCurl(url,init??{},{command,proxy,maxBytes,notFound:`fetchContent.curl command not found: ${command[0]}`})}}
|
|
26
|
-
function parseHeaderDump(dump,keepLengthHeaders){let blocks=dump.split(/\r?\n\r?\n/).filter(block2=>/^HTTP\/[\d.]+\s+\d{3}/.test(block2.trim())),lines=(blocks.length>0?blocks[blocks.length-1]:"").trim().split(/\r?\n/),status=0,statusText="",headers=[];for(let line of lines){let match=/^HTTP\/[\d.]+\s+(\d{3})(?:\s+(.*))?$/.exec(line.trim());if(match){status=Number(match[1]),statusText=match[2]??"",headers.length=0;continue}let separator=line.indexOf(":");if(separator>0){let name=line.slice(0,separator).
|
|
27
|
-
trim();if(!keepLengthHeaders&&(name.toLowerCase()==="content-encoding"||name.toLowerCase()==="content-length"))continue;headers.push([name,line.slice(separator+1).trim()])}}return{status,statusText,headers}}var CurlTransportError=class extends Error{};function quoteCurlConfigValue(value,label){if(/[\0-\x08\x0c\x0e-\x1f\x7f]/.test(value))throw new Error(`${label} contains unsupported control characters`);return`"${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\t/g,"\\t").replace(/\n/g,
|
|
28
|
-
"\\n").replace(/\r/g,"\\r").replace(/\v/g,"\\v")}"`}function curlConfigOption(name,value,label=name){return value===void 0?name:`${name} = ${quoteCurlConfigValue(value,label)}`}async function fetchViaCurl(url,init,transport){let current=url,currentInit=init;for(let redirects=0;;redirects++){let response=await fetchViaCurlOnce(current,currentInit,transport),location=response.headers.get("location");if(!location||![301,302,303,307,308].includes(response.status))return redirects>0&&Object.defineProperty(
|
|
29
|
-
response,"redirected",{value:!0,configurable:!0}),response;if(currentInit.redirect==="manual")return response;if(currentInit.redirect==="error")throw new TypeError(`Proxy fetch redirect blocked from ${current.toString()}`);if(redirects===20)throw new Error(`Too many proxy redirects from ${url.toString()}`);let next=new URL(location,current);if(next.protocol!=="http:"&&next.protocol!=="https:")throw new Error(`Proxy redirect from ${current.origin} must use HTTP(S)`);let headers=new Headers(currentInit.
|
|
30
|
-
headers),nextInit,method=currentInit.method?.toUpperCase()??"GET";if((response.status===301||response.status===302)&&method==="POST"||response.status===303&&method!=="GET"&&method!=="HEAD"){for(let name of["Content-Encoding","Content-Language","Content-Location","Content-Type"])headers.delete(name);let{body:_body,...withoutBody}=currentInit;nextInit={...withoutBody,method:"GET",headers}}else nextInit={...currentInit,headers};next.origin!==current.origin&&(headers=new Headers,nextInit={...nextInit,
|
|
31
|
-
headers}),current=next,currentInit=nextInit}}async function fetchViaCurlOnce(url,init,{command,proxy,notFound,maxBytes}){let method=(init.method??"GET").toUpperCase(),headers=new Headers(init.headers),dir=await mkdtemp(join(tmpdir(),"pi-web-access-proxy-")),headerFile=join(dir,"headers"),bodyFile=join(dir,"body"),requestBodyFile=join(dir,"request-body"),config=[curlConfigOption("silent"),curlConfigOption("show-error"),curlConfigOption("compressed"),curlConfigOption("no-location"),curlConfigOption(
|
|
32
|
-
"globoff"),curlConfigOption("connect-timeout","20"),curlConfigOption("proxy",proxy??"","proxy URL"),...proxy?[curlConfigOption("noproxy","")]:[],curlConfigOption("dump-header",headerFile),curlConfigOption("output",bodyFile),curlConfigOption("write-out","%{json}")];method==="HEAD"?config.push(curlConfigOption("head")):method!=="GET"&&config.push(curlConfigOption("request",method)),maxBytes!==void 0&&config.push(curlConfigOption("max-filesize",String(maxBytes)));for(let[name,value]of headers.entries())
|
|
33
|
-
value!==""&&config.push(curlConfigOption("header",`${name}: ${value}`,`header ${name}`));let body=init.body;if(body!=null){let buffer;if(typeof body=="string")buffer=Buffer.from(body,"utf-8");else if(body instanceof URLSearchParams)buffer=Buffer.from(body.toString(),"utf-8");else if(body instanceof ArrayBuffer)buffer=Buffer.from(body);else if(ArrayBuffer.isView(body))buffer=Buffer.from(body.buffer,body.byteOffset,body.byteLength);else throw new Error(`Unsupported request body type for proxy fetc\
|
|
34
|
-
h: ${typeof body}`);await writeFile(requestBodyFile,buffer,{mode:384}),config.push(curlConfigOption("data-binary",`@${requestBodyFile}`)),method==="GET"&&config.push(curlConfigOption("request","GET"))}else(method==="POST"||method==="PUT")&&!headers.has("content-length")&&config.push(curlConfigOption("header","Content-Length: 0"));config.push(curlConfigOption("url",url.toString(),"request URL"));let configInput=`${config.join(`
|
|
35
|
-
`)}
|
|
36
|
-
`,signal=init.signal??null,stdout;try{stdout=await new Promise((resolve,reject)=>{if(signal?.aborted){reject(new DOMException("The operation was aborted.","AbortError"));return}let child=spawn(command[0],[...command.slice(1),"--config","-"],{windowsHide:!0,stdio:["pipe","pipe","pipe"]}),out="",stderr="",onAbort=()=>{try{child.kill()}catch{}};if(signal&&signal.addEventListener("abort",onAbort,{once:!0}),child.stdout?.on("data",chunk=>{out+=chunk.toString("utf-8")}),child.stderr?.on("data",chunk=>{
|
|
37
|
-
stderr.length<4096&&(stderr+=chunk.toString("utf-8"))}),child.once("error",err=>{signal?.removeEventListener("abort",onAbort),reject(new CurlTransportError(err.code==="ENOENT"?notFound??"curl executable not found on PATH; proxy transport requires curl":`${command[0]} failed to start: ${err.message}`))}),child.once("close",code=>{if(signal?.removeEventListener("abort",onAbort),signal?.aborted)return reject(new DOMException("The operation was aborted.","AbortError"));if(code===63&&maxBytes!==void 0)
|
|
38
|
-
return reject(new CurlTransportError(`Response too large (over ${Math.round(maxBytes/1024/1024)}MB)`));if(code!==0)return reject(new CurlTransportError(`${command[0]} exited with code ${code??"unknown"}${proxy?` via ${redactProxyUrl(proxy)}`:""}${stderr.trim()?`: ${stderr.trim()}`:""}`));resolve(out)}),!child.stdin){child.kill(),reject(new CurlTransportError("curl stdin unavailable for protected proxy configuration"));return}child.stdin.on("error",err=>reject(new CurlTransportError(`curl stdin f\
|
|
39
|
-
ailed: ${err.message}`))),child.stdin.end(configInput)})}catch(err){throw await rm(dir,{recursive:!0,force:!0}).catch(()=>{}),err instanceof CurlTransportError?new Error(err.message):err}let bodyBuffer=Buffer.alloc(0),dump="";try{[dump,bodyBuffer]=await Promise.all([readFile(headerFile,"utf-8"),readFile(bodyFile)])}catch{}finally{await rm(dir,{recursive:!0,force:!0}).catch(()=>{})}let{status,statusText,headers:responseHeaders}=parseHeaderDump(dump,method==="HEAD");if(status===0)throw new Error(proxy?
|
|
40
|
-
`Proxy fetch to ${url.toString()} via ${redactProxyUrl(proxy)} returned no HTTP status`:`${command[0]} fetch to ${url.toString()} returned no HTTP status`);let finalUrl=url.toString(),redirected=!1;try{let trimmed=stdout.trim();if(trimmed.startsWith("{")){let writeOut=JSON.parse(trimmed);writeOut.url_effective&&(finalUrl=writeOut.url_effective),redirected=(writeOut.num_redirects??0)>0}}catch{}let nullBody=method==="HEAD"||status===204||status===205||status===304,response=new Response(nullBody?null:
|
|
41
|
-
new Uint8Array(bodyBuffer),{status,statusText:statusText||void 0,headers:new Headers(responseHeaders)});return Object.defineProperty(response,"url",{value:finalUrl,configurable:!0}),Object.defineProperty(response,"redirected",{value:redirected,configurable:!0}),response}var ActivityMonitor=class{entries=[];maxEntries=10;listeners=new Set;rateLimitInfo={used:0,max:10,oldestTimestamp:null,windowMs:6e4};nextId=1;logStart(partial){let id=`act-${this.nextId++}`,entry={...partial,id,startTime:Date.now(),status:null};return this.entries.push(entry),this.entries.length>this.maxEntries&&this.entries.shift(),this.notify(),id}logComplete(id,status){let entry=this.entries.find(e=>e.id===id);entry&&(entry.endTime=Date.now(),entry.status=status,this.notify())}logError(id,error){
|
|
2
|
+
import{fetchWithCredentialRedirects,getActiveProxy,getMetadataServerOrigin,getWebSearchConfigPath,hasScopedProxyDecision,isLoopbackHostname,isProxyBypassedUrl,isRecord,loadConfiguredProxy,normalizeProxyUrl,resolveApiBaseUrl,resolveProviderApiUrl}from"./chunk-MPRAQ6ZI.js";var ActivityMonitor=class{entries=[];maxEntries=10;listeners=new Set;rateLimitInfo={used:0,max:10,oldestTimestamp:null,windowMs:6e4};nextId=1;logStart(partial){let id=`act-${this.nextId++}`,entry={...partial,id,startTime:Date.now(),status:null};return this.entries.push(entry),this.entries.length>this.maxEntries&&this.entries.shift(),this.notify(),id}logComplete(id,status){let entry=this.entries.find(e=>e.id===id);entry&&(entry.endTime=Date.now(),entry.status=status,this.notify())}logError(id,error){
|
|
42
3
|
let entry=this.entries.find(e=>e.id===id);entry&&(entry.endTime=Date.now(),entry.error=error,this.notify())}getEntries(){return this.entries}getRateLimitInfo(){return this.rateLimitInfo}updateRateLimit(info){this.rateLimitInfo=info,this.notify()}onUpdate(callback){return this.listeners.add(callback),()=>this.listeners.delete(callback)}clear(){this.entries=[],this.rateLimitInfo={used:0,max:10,oldestTimestamp:null,windowMs:6e4},this.notify()}notify(){for(let cb of this.listeners)try{cb()}catch{}}},
|
|
43
|
-
activityMonitor=new ActivityMonitor;import{chmodSync,closeSync,constants as fsConstants,existsSync
|
|
44
|
-
|
|
4
|
+
activityMonitor=new ActivityMonitor;import{chmodSync,closeSync,constants as fsConstants,existsSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFileSync,readSync,readdirSync,realpathSync,rmSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{lstat as lstatAsync,open as openAsync,opendir as opendirAsync,readFile as readFileAsync,realpath as realpathAsync,rm as rmAsync}from"node:fs/promises";import{execFile as execFile2,spawn}from"node:child_process";import{createHash}from"node:crypto";import{basename,dirname,extname,join,resolve as resolvePath,
|
|
5
|
+
sep as pathSep}from"node:path";import{tmpdir}from"node:os";import{execFile}from"node:child_process";var MAX_TREE_ENTRIES=200,MAX_INLINE_FILE_CHARS=1e5,ghAvailable=null,ghHintShown=!1;async function checkGhAvailable(signal){return ghAvailable!==null?ghAvailable:new Promise(resolve=>{execFile("gh",["--version"],{timeout:5e3,...signal?{signal}:{}},err=>{let available=!err;signal?.aborted||(ghAvailable=available),resolve(available)})})}function showGhHint(){ghHintShown||(ghHintShown=!0,console.error("[pi-web-access] Install `gh` CLI for better GitHub repo a\
|
|
45
6
|
ccess including private repos."))}async function checkRepoSize(owner,repo){return await checkGhAvailable()?new Promise(resolve=>{execFile("gh",["api",`repos/${owner}/${repo}`,"--jq",".size"],{timeout:1e4},(err,stdout)=>{if(err){resolve(null);return}let kb=parseInt(stdout.trim(),10);resolve(Number.isNaN(kb)?null:kb)})}):null}async function getDefaultBranch(owner,repo){return await checkGhAvailable()?new Promise(resolve=>{execFile("gh",["api",`repos/${owner}/${repo}`,"--jq",".default_branch"],{timeout:1e4},
|
|
46
7
|
(err,stdout)=>{if(err){resolve(null);return}let branch=stdout.trim();resolve(branch||null)})}):null}async function fetchTreeViaApi(owner,repo,ref){return await checkGhAvailable()?new Promise(resolve=>{execFile("gh",["api",`repos/${owner}/${repo}/git/trees/${ref}?recursive=1`,"--jq",".tree[].path"],{timeout:15e3,maxBuffer:5*1024*1024},(err,stdout)=>{if(err){resolve(null);return}let paths=stdout.trim().split(`
|
|
47
8
|
`).filter(Boolean);if(paths.length===0){resolve(null);return}let truncated=paths.length>MAX_TREE_ENTRIES,display=paths.slice(0,MAX_TREE_ENTRIES).join(`
|
|
@@ -56,42 +17,41 @@ let ref=info.ref||await getDefaultBranch(owner,repo);if(!ref)return null;let lin
|
|
|
56
17
|
`),error:null}}var CONFIG_PATH=getWebSearchConfigPath(),BINARY_EXTENSIONS=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".tiff",".tif",".mp3",".mp4",".avi",".mov",".mkv",".flv",".wmv",".wav",".ogg",".webm",".flac",".aac",".zip",".tar",".gz",".bz2",".xz",".7z",".rar",".zst",".exe",".dll",".so",".dylib",".bin",".o",".a",".lib",".woff",".woff2",".ttf",".otf",".eot",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".sqlite",".db",".sqlite3",".pyc",".pyo",".class",".jar",".war",".iso",".img",
|
|
57
18
|
".dmg"]),NOISE_DIRS=new Set(["node_modules","vendor",".next","dist","build","__pycache__",".venv","venv",".tox",".mypy_cache",".pytest_cache","target",".gradle",".idea",".vscode"]),MAX_INLINE_FILE_CHARS2=1e5,MAX_TREE_ENTRIES2=200,CLONE_RUNTIME_OWNER_FILENAME=".owner.json",CLONE_RUNTIME_OWNER_VERSION=1,MAX_CLONE_RUNTIME_OWNER_BYTES=1024,cloneCache=new Map,startedCloneRuntimeCleanups=new Set,cachedConfig=null,cloneRuntime=null;function normalizeEnabled(value,fallback){return typeof value=="boolean"?
|
|
58
19
|
value:fallback}function normalizePositiveNumber(value,fallback){return typeof value!="number"||!Number.isFinite(value)?fallback:value>0?value:fallback}function expandPath(value){let expanded=value;return(expanded.startsWith("~/")||expanded==="~")&&(expanded=expanded.replace(/^~/,process.env.HOME||process.env.USERPROFILE||"")),expanded=expanded.replace(/\$([A-Z_][A-Z0-9_]*)/gi,(match,varName)=>process.env[varName]??match),expanded}function normalizeClonePath(value,fallback){if(typeof value!="stri\
|
|
59
|
-
ng")return fallback;let normalized=value.trim();return normalized.length===0?fallback:expandPath(normalized)}function loadGitHubConfig(){if(cachedConfig)return cachedConfig;let defaults={enabled:!0,maxRepoSizeMB:350,cloneTimeoutSeconds:30,clonePath:
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
let owner={version:CLONE_RUNTIME_OWNER_VERSION,pid:process.pid,platform:process.platform};if(process.platform==="linux"){let bootId=readLinuxBootId(),processInfo=readLinuxProcessInfo(process.pid);bootId&&processInfo?.startTime&&(owner.bootId=bootId,owner.startTime=processInfo.startTime)}return owner}function writeCloneRuntimeOwner(runtimePath){let ownerPath=
|
|
67
|
-
|
|
68
|
-
platform};if(record.bootId!==void 0){if(typeof record.bootId!="string"||record.bootId.length===0||record.bootId.length>256)return null;owner.bootId=record.bootId}if(record.startTime!==void 0){if(typeof record.startTime!="string"||!/^\d+$/.test(record.startTime))return null;owner.startTime=record.startTime}return owner}async function readCloneRuntimeOwner(runtimePath){let ownerPath=
|
|
20
|
+
ng")return fallback;let normalized=value.trim();return normalized.length===0?fallback:expandPath(normalized)}function loadGitHubConfig(){if(cachedConfig)return cachedConfig;let defaults={enabled:!0,maxRepoSizeMB:350,cloneTimeoutSeconds:30,clonePath:join(tmpdir(),"pi-github-repos")};if(!existsSync(CONFIG_PATH))return cachedConfig=defaults,cachedConfig;let rawText=readFileSync(CONFIG_PATH,"utf-8"),raw;try{raw=JSON.parse(rawText)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(
|
|
21
|
+
`Failed to parse ${CONFIG_PATH}: ${message}`)}let gc=raw.githubClone??{};return cachedConfig={enabled:normalizeEnabled(gc.enabled,defaults.enabled),maxRepoSizeMB:normalizePositiveNumber(gc.maxRepoSizeMB,defaults.maxRepoSizeMB),cloneTimeoutSeconds:normalizePositiveNumber(gc.cloneTimeoutSeconds,defaults.cloneTimeoutSeconds),clonePath:normalizeClonePath(gc.clonePath,defaults.clonePath)},cachedConfig}var NON_CODE_SEGMENTS=new Set(["issues","pull","pulls","discussions","releases","wiki","actions","se\
|
|
22
|
+
ttings","security","projects","graphs","compare","commits","tags","branches","stargazers","watchers","network","forks","milestone","labels","packages","codespaces","contribute","community","sponsors","invitations","notifications","insights"]);function parseGitHubUrl(url){let parsed;try{parsed=new URL(url)}catch{return null}let host=parsed.hostname.toLowerCase();if(host!=="github.com"&&host!=="www.github.com")return null;let segments=[];for(let segment of parsed.pathname.split("/").filter(Boolean))
|
|
23
|
+
try{segments.push(decodeURIComponent(segment))}catch{return null}if(segments.length<2)return null;let owner=segments[0],repo=segments[1].replace(/\.git$/,"");if(!/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(owner)||owner.includes("--")||!/^[A-Za-z0-9._-]{1,100}$/.test(repo)||repo==="."||repo===".."||NON_CODE_SEGMENTS.has(segments[2]?.toLowerCase()))return null;if(segments.length===2)return{owner,repo,refIsFullSha:!1,type:"root"};let action=segments[2];if(action!=="blob"&&action!=="tree"||
|
|
24
|
+
segments.length<4)return null;let ref=segments[3];if(ref.length===0||ref.length>1024||/[\0-\x1f\x7f]/.test(ref))return null;let refIsFullSha=/^[0-9a-f]{40}$/.test(ref),pathParts=segments.slice(4),path=pathParts.length>0?pathParts.join("/"):"";return{owner,repo,ref,refIsFullSha,path,type:action}}function cacheKey(owner,repo,ref){return ref?`${owner}/${repo}@${ref}`:`${owner}/${repo}`}function readLinuxBootId(){try{let bootId=readFileSync("/proc/sys/kernel/random/boot_id","utf-8").trim();return bootId.
|
|
25
|
+
length>0?bootId:null}catch{return null}}async function readLinuxBootIdAsync(){try{let bootId=(await readFileAsync("/proc/sys/kernel/random/boot_id","utf-8")).trim();return bootId.length>0?bootId:null}catch{return null}}function parseLinuxProcessInfo(stat){let closingParen=stat.lastIndexOf(") ");if(closingParen<0)return null;let fields=stat.slice(closingParen+2).trim().split(/\s+/),state=fields[0],startTime=fields[19];return!state||!startTime||!/^\d+$/.test(startTime)?null:{state,startTime,dead:!1}}
|
|
26
|
+
function readLinuxProcessInfo(pid){try{return parseLinuxProcessInfo(readFileSync(`/proc/${pid}/stat`,"utf-8"))}catch(err){return err&&typeof err=="object"&&"code"in err&&err.code==="ENOENT"?{state:"",startTime:null,dead:!0}:null}}async function readLinuxProcessInfoAsync(pid){try{return parseLinuxProcessInfo(await readFileAsync(`/proc/${pid}/stat`,"utf-8"))}catch(err){return err&&typeof err=="object"&&"code"in err&&err.code==="ENOENT"?{state:"",startTime:null,dead:!0}:null}}function currentCloneRuntimeOwner(){
|
|
27
|
+
let owner={version:CLONE_RUNTIME_OWNER_VERSION,pid:process.pid,platform:process.platform};if(process.platform==="linux"){let bootId=readLinuxBootId(),processInfo=readLinuxProcessInfo(process.pid);bootId&&processInfo?.startTime&&(owner.bootId=bootId,owner.startTime=processInfo.startTime)}return owner}function writeCloneRuntimeOwner(runtimePath){let ownerPath=join(runtimePath,CLONE_RUNTIME_OWNER_FILENAME);writeFileSync(ownerPath,JSON.stringify(currentCloneRuntimeOwner()),{encoding:"utf-8",flag:"wx",
|
|
28
|
+
mode:384})}function parseCloneRuntimeOwner(text2){let parsed;try{parsed=JSON.parse(text2)}catch{return null}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return null;let record=parsed;if(record.version!==CLONE_RUNTIME_OWNER_VERSION||typeof record.pid!="number"||!Number.isSafeInteger(record.pid)||record.pid<=0||typeof record.platform!="string"||record.platform.length===0||record.platform.length>32)return null;let owner={version:CLONE_RUNTIME_OWNER_VERSION,pid:record.pid,platform:record.
|
|
29
|
+
platform};if(record.bootId!==void 0){if(typeof record.bootId!="string"||record.bootId.length===0||record.bootId.length>256)return null;owner.bootId=record.bootId}if(record.startTime!==void 0){if(typeof record.startTime!="string"||!/^\d+$/.test(record.startTime))return null;owner.startTime=record.startTime}return owner}async function readCloneRuntimeOwner(runtimePath){let ownerPath=join(runtimePath,CLONE_RUNTIME_OWNER_FILENAME),file;try{let entry=await lstatAsync(ownerPath);if(!entry.isFile()||entry.
|
|
69
30
|
size>MAX_CLONE_RUNTIME_OWNER_BYTES)return null;let noFollow=fsConstants.O_NOFOLLOW??0;file=await openAsync(ownerPath,fsConstants.O_RDONLY|noFollow);let opened=await file.stat();return!opened.isFile()||opened.size>MAX_CLONE_RUNTIME_OWNER_BYTES?null:parseCloneRuntimeOwner(await file.readFile("utf-8"))}catch{return null}finally{if(file!==void 0)try{await file.close()}catch{}}}function processNonexistenceProven(pid){try{return process.kill(pid,0),!1}catch(err){return!!(err&&typeof err=="object"&&"co\
|
|
70
31
|
de"in err&&err.code==="ESRCH")}}async function cloneRuntimeOwnerIsDead(owner,bootId){if(owner.platform!==process.platform)return!1;if(process.platform!=="linux")return processNonexistenceProven(owner.pid);if(!owner.bootId||!owner.startTime||!bootId)return!1;let processInfo=await readLinuxProcessInfoAsync(owner.pid);return processInfo?processInfo.dead||processInfo.state==="Z"||processInfo.state==="X"?!0:processInfo.startTime!==owner.startTime||bootId!==owner.bootId:!1}async function removeCloneRuntimeAsync(parentPath,runtimePath){
|
|
71
32
|
let normalizedParentPath=resolvePath(parentPath),normalizedRuntimePath=resolvePath(runtimePath);if(!(dirname(normalizedRuntimePath)!==normalizedParentPath||!basename(normalizedRuntimePath).startsWith("runtime-")))try{let realRuntimePath=await realpathAsync(normalizedRuntimePath);if(dirname(realRuntimePath)!==normalizedParentPath||basename(realRuntimePath)!==basename(normalizedRuntimePath))return;let entry=await lstatAsync(normalizedRuntimePath);if(entry.isSymbolicLink()||!entry.isDirectory())return;
|
|
72
33
|
await rmAsync(normalizedRuntimePath,{recursive:!0,force:!0})}catch{}}async function sweepStaleCloneRuntimes(parentPath){let normalizedParentPath=resolvePath(parentPath),bootId=process.platform==="linux"?await readLinuxBootIdAsync():null;try{let directory=await opendirAsync(normalizedParentPath);for await(let entry of directory)if(entry.name.startsWith("runtime-"))try{if(!entry.isDirectory()||entry.isSymbolicLink())continue;let runtimePath=resolvePath(normalizedParentPath,entry.name);if(dirname(runtimePath)!==
|
|
73
34
|
normalizedParentPath)continue;let runtimeEntry=await lstatAsync(runtimePath);if(!runtimeEntry.isDirectory()||runtimeEntry.isSymbolicLink())continue;let realRuntimePath=await realpathAsync(runtimePath);if(dirname(realRuntimePath)!==normalizedParentPath||basename(realRuntimePath)!==basename(runtimePath))continue;let owner=await readCloneRuntimeOwner(runtimePath);if(!owner||!await cloneRuntimeOwnerIsDead(owner,bootId))continue;await removeCloneRuntimeAsync(normalizedParentPath,runtimePath)}catch{}}catch{}}
|
|
74
35
|
function startStaleCloneRuntimeCleanup(parentPath){let normalizedParentPath=resolvePath(parentPath);startedCloneRuntimeCleanups.has(normalizedParentPath)||(startedCloneRuntimeCleanups.add(normalizedParentPath),sweepStaleCloneRuntimes(normalizedParentPath).catch(()=>{}))}function removeCloneRuntime(parentPath,runtimePath){let normalizedParentPath=resolvePath(parentPath),normalizedRuntimePath=resolvePath(runtimePath);if(!(dirname(normalizedRuntimePath)!==normalizedParentPath||!basename(normalizedRuntimePath).
|
|
75
|
-
startsWith("runtime-")))try{lstatSync(normalizedRuntimePath).isSymbolicLink()?unlinkSync(normalizedRuntimePath):rmSync(normalizedRuntimePath,{recursive:!0,force:!0})}catch{}}function getCloneRuntimeRoot(config){if(cloneRuntime)return cloneRuntime.rootPath;let parentPath=null,runtimePath=null;try{let configuredPath=resolvePath(config.clonePath);mkdirSync(configuredPath,{recursive:!0}),parentPath=realpathSync(configuredPath),startStaleCloneRuntimeCleanup(parentPath),runtimePath=mkdtempSync(
|
|
36
|
+
startsWith("runtime-")))try{lstatSync(normalizedRuntimePath).isSymbolicLink()?unlinkSync(normalizedRuntimePath):rmSync(normalizedRuntimePath,{recursive:!0,force:!0})}catch{}}function getCloneRuntimeRoot(config){if(cloneRuntime)return cloneRuntime.rootPath;let parentPath=null,runtimePath=null;try{let configuredPath=resolvePath(config.clonePath);mkdirSync(configuredPath,{recursive:!0}),parentPath=realpathSync(configuredPath),startStaleCloneRuntimeCleanup(parentPath),runtimePath=mkdtempSync(join(parentPath,
|
|
76
37
|
"runtime-")),chmodSync(runtimePath,448);let rootPath=realpathSync(runtimePath);return dirname(rootPath)!==parentPath?(removeCloneRuntime(parentPath,runtimePath),null):(writeCloneRuntimeOwner(rootPath),cloneRuntime={parentPath,rootPath},rootPath)}catch{return parentPath&&runtimePath&&removeCloneRuntime(parentPath,runtimePath),null}}function cloneDestination(config,owner,repo,ref){try{let rootPath=getCloneRuntimeRoot(config);if(!rootPath)return null;let digest=createHash("sha256").update(JSON.stringify(
|
|
77
38
|
[owner,repo,ref??null])).digest("hex"),localPath=resolvePath(rootPath,digest);return dirname(localPath)!==rootPath?null:{rootPath,localPath}}catch{return null}}function removeCloneDestination(destination){let rootPath=resolvePath(destination.rootPath),localPath=resolvePath(destination.localPath);if(dirname(localPath)!==rootPath||!/^[0-9a-f]{64}$/.test(basename(localPath)))return!1;try{return lstatSync(localPath).isSymbolicLink()?unlinkSync(localPath):rmSync(localPath,{recursive:!0,force:!0}),!0}catch(err){
|
|
78
39
|
return!!(err&&typeof err=="object"&&"code"in err&&err.code==="ENOENT")}}var PROCESS_KILL_GRACE_MS=3e3;function terminateProcessTree(child){let pid=child.pid;if(!pid)return;if(process.platform==="win32"){execFile2("taskkill",["/pid",String(pid),"/T","/F"],{windowsHide:!0},err=>{err&&child.kill()}).unref();return}try{process.kill(-pid,"SIGTERM")}catch{child.kill()}setTimeout(()=>{try{process.kill(-pid,"SIGKILL")}catch{child.kill("SIGKILL")}},PROCESS_KILL_GRACE_MS).unref()}function execClone(args,destination,timeoutMs,signal){
|
|
79
|
-
return new Promise(resolve=>{let{localPath}=destination,settled=!1,timeout,onAbort,finish=success=>{if(!settled){if(settled=!0,timeout&&clearTimeout(timeout),signal&&onAbort&&signal.removeEventListener("abort",onAbort),!success){removeCloneDestination(destination),resolve(null);return}resolve(localPath)}},child=
|
|
40
|
+
return new Promise(resolve=>{let{localPath}=destination,settled=!1,timeout,onAbort,finish=success=>{if(!settled){if(settled=!0,timeout&&clearTimeout(timeout),signal&&onAbort&&signal.removeEventListener("abort",onAbort),!success){removeCloneDestination(destination),resolve(null);return}resolve(localPath)}},child=spawn(args[0],args.slice(1),{detached:process.platform!=="win32",env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"Never",GH_PROMPT_DISABLED:"1"},stdio:"ignore",windowsHide:!0});
|
|
80
41
|
child.once("error",()=>finish(!1)),child.once("close",code=>finish(code===0)),timeout=setTimeout(()=>terminateProcessTree(child),timeoutMs),timeout.unref(),signal&&(onAbort=()=>{timeout&&clearTimeout(timeout),terminateProcessTree(child)},signal.aborted?onAbort():signal.addEventListener("abort",onAbort,{once:!0}))})}async function cloneRepo(owner,repo,ref,config,destination,signal){let{localPath}=destination;if(!removeCloneDestination(destination))return null;let timeoutMs=config.cloneTimeoutSeconds*
|
|
81
42
|
1e3;if(await checkGhAvailable()){let args2=["gh","repo","clone",`${owner}/${repo}`,localPath,"--","--depth","1","--single-branch"];return ref&&args2.push("--branch",ref),execClone(args2,destination,timeoutMs,signal)}showGhHint();let gitUrl=`https://github.com/${owner}/${repo}.git`,args=["git","clone","--depth","1","--single-branch"];return ref&&args.push("--branch",ref),args.push(gitUrl,localPath),execClone(args,destination,timeoutMs,signal)}function isBinaryFile(filePath){let ext=extname(filePath).
|
|
82
43
|
toLowerCase();if(BINARY_EXTENSIONS.has(ext))return!0;let fd;try{fd=openSync(filePath,"r")}catch{return!1}try{let buf=Buffer.alloc(512),bytesRead=readSync(fd,buf,0,512,0);for(let i=0;i<bytesRead;i++)if(buf[i]===0)return!0}catch{return!1}finally{closeSync(fd)}return!1}function formatFileSize(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}function resolveWithinRepo(rootPath,relativePath){let normalizedRoot=resolvePath(rootPath),
|
|
83
|
-
candidate=resolvePath(normalizedRoot,relativePath);if(candidate!==normalizedRoot){let rootPrefix=normalizedRoot.endsWith(pathSep)?normalizedRoot:normalizedRoot+pathSep;if(!candidate.startsWith(rootPrefix))return null}if(!
|
|
84
|
-
candidate:null}catch{return null}}function readTextFile(path){try{return
|
|
44
|
+
candidate=resolvePath(normalizedRoot,relativePath);if(candidate!==normalizedRoot){let rootPrefix=normalizedRoot.endsWith(pathSep)?normalizedRoot:normalizedRoot+pathSep;if(!candidate.startsWith(rootPrefix))return null}if(!existsSync(candidate))return candidate;try{let realRoot=realpathSync(normalizedRoot),realCandidate=realpathSync(candidate);if(realCandidate===realRoot)return candidate;let realRootPrefix=realRoot.endsWith(pathSep)?realRoot:realRoot+pathSep;return realCandidate.startsWith(realRootPrefix)?
|
|
45
|
+
candidate:null}catch{return null}}function readTextFile(path){try{return readFileSync(path,"utf-8")}catch{return null}}function buildTree(rootPath){let entries=[];function walk(dir,relPath){if(entries.length>=MAX_TREE_ENTRIES2)return;let items;try{items=readdirSync(dir).sort()}catch{return}for(let item of items){if(entries.length>=MAX_TREE_ENTRIES2)return;if(item===".git")continue;let rel=relPath?`${relPath}/${item}`:item,safePath=resolveWithinRepo(rootPath,rel);if(!safePath){entries.push(`${rel}\
|
|
85
46
|
[outside repo skipped]`);continue}let stat;try{stat=statSync(safePath)}catch{continue}if(stat.isDirectory()){if(NOISE_DIRS.has(item)){entries.push(`${rel}/ [skipped]`);continue}entries.push(`${rel}/`),walk(safePath,rel)}else entries.push(rel)}}return walk(rootPath,""),entries.length>=MAX_TREE_ENTRIES2&&entries.push(`... (truncated at ${MAX_TREE_ENTRIES2} entries)`),entries.join(`
|
|
86
47
|
`)}function buildDirListing(rootPath,subPath){let targetPath=resolveWithinRepo(rootPath,subPath);if(!targetPath)return"(path escapes repository root)";let lines=[],items;try{items=readdirSync(targetPath).sort()}catch{return"(directory not readable)"}for(let item of items){if(item===".git")continue;let rel=subPath?`${subPath}/${item}`:item,safePath=resolveWithinRepo(rootPath,rel);if(!safePath){lines.push(` ${item} (outside repo)`);continue}try{let stat=statSync(safePath);stat.isDirectory()?lines.
|
|
87
48
|
push(` ${item}/`):lines.push(` ${item} (${formatFileSize(stat.size)})`)}catch{lines.push(` ${item} (unreadable)`)}}return lines.join(`
|
|
88
|
-
`)}function readReadme(localPath){let candidates=["README.md","readme.md","README","README.txt","README.rst"];for(let name of candidates){let readmePath=
|
|
49
|
+
`)}function readReadme(localPath){let candidates=["README.md","readme.md","README","README.txt","README.rst"];for(let name of candidates){let readmePath=join(localPath,name);if(existsSync(readmePath))try{let content=readFileSync(readmePath,"utf-8");return content.length>MAX_INLINE_FILE_CHARS2?`${content.slice(0,MAX_INLINE_FILE_CHARS2)}
|
|
89
50
|
|
|
90
51
|
[README truncated at 100K chars. Full file: ${readmePath}]`:content}catch{continue}}return null}function generateContent(localPath,info){let lines=[];if(lines.push(`Repository cloned to: ${localPath}`),lines.push(""),info.type==="root"){lines.push("## Structure"),lines.push(buildTree(localPath)),lines.push("");let readme=readReadme(localPath);return readme&&(lines.push("## README.md"),lines.push(readme),lines.push("")),lines.push("Use `read` and `bash` tools at the path above to explore further."),
|
|
91
52
|
lines.join(`
|
|
92
|
-
`)}if(info.type==="tree"){let dirPath=info.path||"",fullDirPath=resolveWithinRepo(localPath,dirPath);return!fullDirPath||!
|
|
93
|
-
|
|
94
|
-
`)}if(info.type==="blob"){let filePath=info.path||"",fullFilePath=resolveWithinRepo(localPath,filePath);if(!fullFilePath||!existsSync2(fullFilePath))return lines.push(`Path \`${filePath}\` not found in clone. Showing repository root instead.`),lines.push(""),lines.push("## Structure"),lines.push(buildTree(localPath)),lines.push(""),lines.push("Use `read` and `bash` tools at the path above to explore further."),lines.join(`
|
|
53
|
+
`)}if(info.type==="tree"){let dirPath=info.path||"",fullDirPath=resolveWithinRepo(localPath,dirPath);return!fullDirPath||!existsSync(fullDirPath)?(lines.push(`Path \`${dirPath}\` not found in clone. Showing repository root instead.`),lines.push(""),lines.push("## Structure"),lines.push(buildTree(localPath))):(lines.push(`## ${dirPath||"/"}`),lines.push(buildDirListing(localPath,dirPath))),lines.push(""),lines.push("Use `read` and `bash` tools at the path above to explore further."),lines.join(`
|
|
54
|
+
`)}if(info.type==="blob"){let filePath=info.path||"",fullFilePath=resolveWithinRepo(localPath,filePath);if(!fullFilePath||!existsSync(fullFilePath))return lines.push(`Path \`${filePath}\` not found in clone. Showing repository root instead.`),lines.push(""),lines.push("## Structure"),lines.push(buildTree(localPath)),lines.push(""),lines.push("Use `read` and `bash` tools at the path above to explore further."),lines.join(`
|
|
95
55
|
`);let stat;try{stat=statSync(fullFilePath)}catch(err){let message=err instanceof Error?err.message:String(err);return lines.push(`Could not inspect \`${filePath}\`: ${message}`),lines.push(""),lines.push("Use `read` and `bash` tools at the path above to explore further."),lines.join(`
|
|
96
56
|
`)}if(stat.isDirectory())return lines.push(`## ${filePath||"/"}`),lines.push(buildDirListing(localPath,filePath)),lines.push(""),lines.push("Use `read` and `bash` tools at the path above to explore further."),lines.join(`
|
|
97
57
|
`);if(isBinaryFile(fullFilePath)){let ext=extname(filePath).replace(".","");return lines.push(`## ${filePath}`),lines.push(`Binary file (${ext}, ${formatFileSize(stat.size)}). Use \`read\` or \`bash\` tools at the path above to inspect.`),lines.join(`
|
|
@@ -105,21 +65,21 @@ if(signal?.aborted)return activityMonitor.logComplete(activityId,0),null;if(size
|
|
|
105
65
|
signal);return signal?.aborted?activityMonitor.logComplete(activityId,0):cachedResult?activityMonitor.logComplete(activityId,200):activityMonitor.logError(activityId,"clone failed"),cachedResult}let destination=cloneDestination(config,owner,repo,info.ref);if(!destination){let apiFallback=await fetchViaApi(url,owner,repo,info);return apiFallback?activityMonitor.logComplete(activityId,200):activityMonitor.logError(activityId,"invalid clone destination"),apiFallback}let clonePromise=cloneRepo(owner,
|
|
106
66
|
repo,info.ref,config,destination,signal),entry={destination,clonePromise,lastUsedAt:Date.now(),settled:!1};cloneCache.set(key,entry),clonePromise.finally(()=>{entry.settled=!0});let result=await clonePromise;if(signal?.aborted)return result||cloneCache.delete(key),activityMonitor.logComplete(activityId,0),null;if(!result){if(cloneCache.delete(key),signal?.aborted)return activityMonitor.logComplete(activityId,0),null;let apiFallback=await fetchViaApi(url,owner,repo,info);return apiFallback?(activityMonitor.
|
|
107
67
|
logComplete(activityId,200),apiFallback):(activityMonitor.logError(activityId,"clone and API fallback failed"),null)}activityMonitor.logComplete(activityId,200);let content=generateContent(result,info),title=info.path?`${owner}/${repo} - ${info.path}`:`${owner}/${repo}`;return{url,title,content,error:null}}function touchClones(urls){let now=Date.now();for(let url of urls){let info=parseGitHubUrl(url);if(!info)continue;let entry=cloneCache.get(cacheKey(info.owner,info.repo,info.ref));entry&&(entry.
|
|
108
|
-
lastUsedAt=now)}}function releaseClonesUnusedSince(time){for(let[key,entry]of cloneCache)!entry.settled||entry.lastUsedAt>=time||(removeCloneDestination(entry.destination),cloneCache.delete(key))}function clearCloneCache(){for(let entry of cloneCache.values())removeCloneDestination(entry.destination);cloneCache.clear(),cloneRuntime&&removeCloneRuntime(cloneRuntime.parentPath,cloneRuntime.rootPath),cloneRuntime=null,cachedConfig=null}import{exec,execFile as execFile3}from"node:child_process";import{existsSync as
|
|
68
|
+
lastUsedAt=now)}}function releaseClonesUnusedSince(time){for(let[key,entry]of cloneCache)!entry.settled||entry.lastUsedAt>=time||(removeCloneDestination(entry.destination),cloneCache.delete(key))}function clearCloneCache(){for(let entry of cloneCache.values())removeCloneDestination(entry.destination);cloneCache.clear(),cloneRuntime&&removeCloneRuntime(cloneRuntime.parentPath,cloneRuntime.rootPath),cloneRuntime=null,cachedConfig=null}import{exec,execFile as execFile3}from"node:child_process";import{existsSync as existsSync2}from"node:fs";import{promisify}from"node:util";var execAsync=promisify(exec),execFileAsync=promisify(execFile3),COMMAND_TIMEOUT_MS=5e3,MAX_CREDENTIAL_BYTES=16384,ENV_SOURCE=/^\$(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)\})$/,OP_SESSION_NAME=/^OP_SESSION_[A-Za-z0-9_]+$/,LEGACY_WSL_BASH=/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/i,COMMAND_ENVIRONMENT_NAMES=["HOME","USER","LOGNAME","OP\
|
|
109
69
|
_SERVICE_ACCOUNT_TOKEN","PATH","LANG","LC_ALL","LC_CTYPE","TERM","TMPDIR","XDG_CONFIG_HOME","XDG_RUNTIME_DIR","DBUS_SESSION_BUS_ADDRESS","SSH_AUTH_SOCK","WSL_DISTRO_NAME","WSL_INTEROP","SystemRoot","windir","ComSpec","PATHEXT","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","TEMP","TMP","ProgramData","ProgramFiles","ProgramFiles(x86)"],CredentialResolutionError=class extends Error{provider;category;constructor(provider,category){let suffix=category==="command-aborted"?"aborted":category===
|
|
110
70
|
"oauth-credential-rejected"?"OAuth token exchange rejected the credentials":category;super(`${provider} credential resolution failed: ${suffix}`),this.name="CredentialResolutionError",this.provider=provider,this.category=category}};function redactCredential(text2,credential){return credential?text2.split(credential).join("[redacted]"):text2}function normalize(value){if(typeof value!="string")return null;let normalized=value.trim();return normalized.length>0?normalized:null}function commandEnvironment(source){
|
|
111
71
|
let environment={};for(let name of COMMAND_ENVIRONMENT_NAMES){let value=source[name];value!==void 0&&(environment[name]=value)}for(let[name,value]of Object.entries(source))value!==void 0&&OP_SESSION_NAME.test(name)&&(environment[name]=value);return environment}function configuredSource(options){return normalize(options.configuredValue)}function explicitEnvironmentName(source){let match=source.match(ENV_SOURCE);return match?match[1]??match[2]:null}function escapedSource(source){return source.startsWith(
|
|
112
72
|
"$$")||source.startsWith("$!")?source.slice(1):null}function isMalformedExplicitSource(source){return source.startsWith("$")&&escapedSource(source)===null&&explicitEnvironmentName(source)===null}async function bashOnPath(signal,timeoutMs){try{let{stdout}=await execFileAsync("where",["bash.exe"],{encoding:"utf8",signal,timeout:timeoutMs,windowsHide:!0});return stdout.trim().split(/\r?\n/)[0]||null}catch{return null}}async function findWindowsBash(environment,exists,findOnPath){for(let root of[environment.
|
|
113
|
-
ProgramFiles,environment["ProgramFiles(x86)"]]){let candidate=root?`${root}\\Git\\bin\\bash.exe`:null;if(candidate&&exists(candidate))return candidate}let found=await findOnPath();return found&&exists(found)&&!LEGACY_WSL_BASH.test(found.replace(/\//g,"\\"))?found:null}async function defaultRunCommand(command,options){let deadline=Date.now()+options.timeoutMs,bash=process.platform==="win32"?await findWindowsBash(process.env,
|
|
73
|
+
ProgramFiles,environment["ProgramFiles(x86)"]]){let candidate=root?`${root}\\Git\\bin\\bash.exe`:null;if(candidate&&exists(candidate))return candidate}let found=await findOnPath();return found&&exists(found)&&!LEGACY_WSL_BASH.test(found.replace(/\//g,"\\"))?found:null}async function defaultRunCommand(command,options){let deadline=Date.now()+options.timeoutMs,bash=process.platform==="win32"?await findWindowsBash(process.env,existsSync2,()=>bashOnPath(options.signal,options.timeoutMs)):null,execOptions={
|
|
114
74
|
encoding:"utf8",env:options.environment,maxBuffer:options.maxOutputBytes+1,signal:options.signal,timeout:Math.max(1,deadline-Date.now()),windowsHide:!0};return{stdout:(bash?await execFileAsync(bash,["-c",command],execOptions):await execAsync(command,execOptions)).stdout}}function commandFailureCategory(error,signal){if(signal?.aborted)return"command-aborted";if(error&&typeof error=="object"){let code=error.code;if(code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return"command-output-too-large";if(error.
|
|
115
75
|
killed||code==="ETIMEDOUT")return"command-timeout"}return"command-failed"}function hasCredentialSource(options){let source=configuredSource(options);return source?.startsWith("!")||source?.startsWith("$")?!0:normalize(options.environmentValue)!==null||source!==null}async function resolveCredential(options){let source=configuredSource(options),escaped=source?escapedSource(source):null;if(escaped!==null)return escaped;if(source?.startsWith("!")){let command=source.slice(1).trim();if(!command)throw new CredentialResolutionError(
|
|
116
76
|
options.provider,"invalid-source");let result;try{result=await(options.runCommand??defaultRunCommand)(command,{signal:options.signal,timeoutMs:COMMAND_TIMEOUT_MS,maxOutputBytes:MAX_CREDENTIAL_BYTES,environment:commandEnvironment(options.environment??process.env)})}catch(error){throw new CredentialResolutionError(options.provider,commandFailureCategory(error,options.signal))}let stdout=Buffer.isBuffer(result.stdout)?result.stdout.toString("utf8"):result.stdout;if(Buffer.byteLength(stdout,"utf8")>
|
|
117
77
|
MAX_CREDENTIAL_BYTES)throw new CredentialResolutionError(options.provider,"command-output-too-large");let value=stdout.trim();if(!value)throw new CredentialResolutionError(options.provider,"command-empty");if(/[\0-\x1f\x7f]/.test(value))throw new CredentialResolutionError(options.provider,"command-invalid-output");return value}if(source&&isMalformedExplicitSource(source))throw new CredentialResolutionError(options.provider,"invalid-source");if(source?.startsWith("$")){let name=explicitEnvironmentName(
|
|
118
|
-
source);if(!name)throw new CredentialResolutionError(options.provider,"invalid-source");let value=normalize((options.environment??process.env)[name]);if(!value)throw new CredentialResolutionError(options.provider,"environment-empty");return value}return normalize(options.environmentValue)??source}import{execFile as execFile4}from"node:child_process";import{pbkdf2Sync,createDecipheriv}from"node:crypto";import{copyFileSync,existsSync as
|
|
78
|
+
source);if(!name)throw new CredentialResolutionError(options.provider,"invalid-source");let value=normalize((options.environment??process.env)[name]);if(!value)throw new CredentialResolutionError(options.provider,"environment-empty");return value}return normalize(options.environmentValue)??source}import{execFile as execFile4}from"node:child_process";import{pbkdf2Sync,createDecipheriv}from"node:crypto";import{copyFileSync,existsSync as existsSync4,mkdtempSync as mkdtempSync2,readdirSync as readdirSync2,readFileSync as readFileSync3,realpathSync as realpathSync2,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir2,homedir}from"node:os";import{isAbsolute,join as join2,sep}from"node:path";import{existsSync as existsSync3,readFileSync as readFileSync2}from"node:fs";var CONFIG_PATH2=getWebSearchConfigPath(),BROWSER_COOKIE_PRESETS=["helium","chrome","brave","arc","chromium","edge"],cachedConfig2=null;function normalizeChromeProfile(value){if(typeof value!="string")return;let normalized=value.trim();return normalized.length>0?normalized:void 0}function parseBrowserCookies(value){if(value===void 0)return;if(!value||typeof value!="object"||Array.isArray(value))throw new Error(`browserCookies in ${CONFIG_PATH2} must be an object`);let raw=value;if("profilePath"in
|
|
119
79
|
raw)throw new Error(`browserCookies.profilePath is not supported; use a browser preset and profile directory name in ${CONFIG_PATH2}`);let browser;if(raw.browser!==void 0){if(typeof raw.browser!="string")throw new Error(`browserCookies.browser in ${CONFIG_PATH2} must be a supported browser name`);let normalized=raw.browser.trim().toLowerCase(),preset=BROWSER_COOKIE_PRESETS.find(candidate=>candidate===normalized);if(!preset)throw new Error(`Unsupported browserCookies.browser ${JSON.stringify(raw.
|
|
120
80
|
browser)} in ${CONFIG_PATH2}`);browser=preset}if(raw.profile!==void 0&&typeof raw.profile!="string")throw new Error(`browserCookies.profile in ${CONFIG_PATH2} must be a profile directory name`);let profile=normalizeChromeProfile(raw.profile);if(profile&&(profile==="."||profile===".."||profile.includes("/")||profile.includes("\\")))throw new Error(`browserCookies.profile in ${CONFIG_PATH2} must be a profile directory name, not a path`);return{...browser?{browser}:{},...profile?{profile}:{}}}function loadConfig(){
|
|
121
|
-
if(cachedConfig2)return cachedConfig2;if(!
|
|
122
|
-
raw.browserCookies),allowBrowserCookies:raw.allowBrowserCookies===!0},cachedConfig2}function getBrowserCookieSelectionFromConfig(){return{...loadConfig().browserCookies}}function isBrowserCookieAccessAllowed(){if(process.env.PI_ALLOW_BROWSER_COOKIES==="1"||process.env.FEYNMAN_ALLOW_BROWSER_COOKIES==="1")return!0;if(!
|
|
81
|
+
if(cachedConfig2)return cachedConfig2;if(!existsSync3(CONFIG_PATH2))return cachedConfig2={},cachedConfig2;let rawText=readFileSync2(CONFIG_PATH2,"utf-8"),raw;try{raw=JSON.parse(rawText)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH2}: ${message}`)}if(raw.chromeProfile!==void 0)throw new Error(`chromeProfile in ${CONFIG_PATH2} is no longer supported; use browserCookies.profile`);return cachedConfig2={browserCookies:parseBrowserCookies(
|
|
82
|
+
raw.browserCookies),allowBrowserCookies:raw.allowBrowserCookies===!0},cachedConfig2}function getBrowserCookieSelectionFromConfig(){return{...loadConfig().browserCookies}}function isBrowserCookieAccessAllowed(){if(process.env.PI_ALLOW_BROWSER_COOKIES==="1"||process.env.FEYNMAN_ALLOW_BROWSER_COOKIES==="1")return!0;if(!existsSync3(CONFIG_PATH2))return!1;let rawText=readFileSync2(CONFIG_PATH2,"utf-8"),raw;try{raw=JSON.parse(rawText)}catch(err){let message=err instanceof Error?err.message:String(err);
|
|
123
83
|
throw new Error(`Failed to parse ${CONFIG_PATH2}: ${message}`)}return raw.allowBrowserCookies===!0}var GOOGLE_ORIGINS=["https://gemini.google.com","https://accounts.google.com","https://www.google.com"],ALL_COOKIE_NAMES=new Set(["__Secure-1PSID","__Secure-1PSIDTS","__Secure-1PSIDCC","__Secure-1PAPISID","NID","AEC","SOCS","__Secure-BUCKET","__Secure-ENID","SID","HSID","SSID","APISID","SAPISID","__Secure-3PSID","__Secure-3PSIDTS","__Secure-3PAPISID","SIDCC"]),MACOS_BROWSER_CONFIGS=[{id:"helium",name:"Helium",baseDir:"Library/Application Support/net.imput.helium",keychainService:"Helium Storage \
|
|
124
84
|
Key",keychainAccount:"Helium"},{id:"chrome",name:"Chrome",baseDir:"Library/Application Support/Google/Chrome",keychainService:"Chrome Safe Storage",keychainAccount:"Chrome"},{id:"brave",name:"Brave",baseDir:"Library/Application Support/BraveSoftware/Brave-Browser",keychainService:"Brave Safe Storage",keychainAccount:"Brave"},{id:"arc",name:"Arc",baseDir:"Library/Application Support/Arc/User Data",keychainService:"Arc Safe Storage",keychainAccount:"Arc"}],LINUX_BROWSER_CONFIGS=[{id:"chromium",name:"\
|
|
125
85
|
Chromium",baseDir:".config/chromium",secretToolApp:"chromium",kwalletFolder:"Chromium Keys",kwalletEntry:"Chromium Safe Storage"},{id:"chrome",name:"Chrome",baseDir:".config/google-chrome",secretToolApp:"chrome",kwalletFolder:"Chrome Keys",kwalletEntry:"Chrome Safe Storage"}],WINDOWS_BROWSER_CONFIGS=[{id:"chrome",name:"Chrome",baseDir:"Google/Chrome/User Data",usesLocalAppData:!0},{id:"edge",name:"Edge",baseDir:"Microsoft/Edge/User Data",usesLocalAppData:!0}],browserPasswordCache=new Map,lastCookieDiagnostic=null,
|
|
@@ -128,7 +88,7 @@ requiredCookies,cookieNames:ALL_COOKIE_NAMES,requiredLabel:"Gemini"})}async func
|
|
|
128
88
|
"win32"?WINDOWS_BROWSER_CONFIGS:[],configs=options.browser?platformConfigs.filter(config=>config.id===options.browser):platformConfigs;if(options.browser&&configs.length===0)return setCookieDiagnostic(`Browser preset '${options.browser}' is not supported on this platform.`),null;if(configs.length===0)return setCookieDiagnostic("Chromium cookie extraction is unsupported on this platform."),null;let warningSet=new Set,rawProfile=typeof options.profile=="string"?options.profile.trim():"",requestedProfile=normalizeProfileName(
|
|
129
89
|
options.profile);if(rawProfile&&!requestedProfile)return setCookieDiagnostic("Configured Chromium profile must be a profile directory name, not a path."),null;let requiredCookies=normalizeCookieNames(options.requiredCookies),cookieNames=normalizeCookieNames(options.cookieNames?[...options.cookieNames]:void 0),hosts=normalizeHosts(options.hosts);if(hosts.length===0)return setCookieDiagnostic("No valid cookie hosts were requested."),null;let attempts=[],home=currentPlatform==="win32"?process.env.USERPROFILE||
|
|
130
90
|
homedir():homedir(),sawCookieDatabase=!1,sawRequiredCookies=!1,sawAnyHostCookie=!1,sawBackendFailure,sawUnsafeProfilePath=!1,sawWindowsAppBoundCookie=!1,sawDecryptionFailure=!1;for(let config of configs){let profiles=requestedProfile?[requestedProfile]:listBrowserProfiles(home,config);for(let profile of profiles){let profilePath=resolveProfilePath(home,config,profile);if(profilePath==="outside-root"){sawUnsafeProfilePath=!0,recordCookieAttempt(attempts,config,profile,"unsafe-profile");continue}if(!profilePath){
|
|
131
|
-
recordCookieAttempt(attempts,config,profile,"missing-database");continue}let cookiesPath=cookieDatabasePath(profilePath,config);if(!cookiesPath){recordCookieAttempt(attempts,config,profile,"missing-database");continue}sawCookieDatabase=!0;let tempDir=mkdtempSync2(
|
|
91
|
+
recordCookieAttempt(attempts,config,profile,"missing-database");continue}let cookiesPath=cookieDatabasePath(profilePath,config);if(!cookiesPath){recordCookieAttempt(attempts,config,profile,"missing-database");continue}sawCookieDatabase=!0;let tempDir=mkdtempSync2(join2(tmpdir2(),"pi-chrome-cookies-"));try{let tempDb=join2(tempDir,"Cookies");if(copyFileSync(cookiesPath,tempDb),copySidecar(cookiesPath,tempDb,"-wal"),copySidecar(cookiesPath,tempDb,"-shm"),requiredCookies?.length){let preflight=await hasCookieNames(
|
|
132
92
|
tempDb,hosts,requiredCookies);if(preflight.failure){sawBackendFailure=preflight.failure,recordCookieAttempt(attempts,config,profile,preflight.failure==="unavailable"?"sqlite-unavailable":"sqlite-query-failed");continue}if(!preflight.present){recordCookieAttempt(attempts,config,profile,"missing-required-cookies");continue}sawRequiredCookies=!0}let browserPasswords=currentPlatform==="win32"?[]:await readBrowserPasswords(config,currentPlatform);for(let password of browserPasswords)password.warning&&
|
|
133
93
|
warningSet.add(password.warning);let windowsKey=currentPlatform==="win32"?await readWindowsEncryptionKey(config,home):null,browserKeys=browserPasswords.flatMap(password=>password.value?[pbkdf2Sync(password.value,"saltysalt",currentPlatform==="darwin"?1003:1,16,"sha1")]:[]);if(currentPlatform==="win32"?!windowsKey:browserKeys.length===0){warningSet.add(currentPlatform==="win32"?`Could not read ${config.name} Windows cookie encryption key`:`Could not read ${config.name} cookie encryption password`),
|
|
134
94
|
recordCookieAttempt(attempts,config,profile,"password-read-failed");continue}let metaVersion=await readMetaVersion(tempDb);if(metaVersion.failure&&(sawBackendFailure=metaVersion.failure,recordCookieAttempt(attempts,config,profile,metaVersion.failure==="unavailable"?"sqlite-unavailable":"sqlite-query-failed")),metaVersion.value===null)continue;let rowsResult=await queryCookieRows(tempDb,hosts,cookieNames??null,!!options.requestUrl);if(rowsResult.status==="failure"){sawBackendFailure=rowsResult.failure,
|
|
@@ -140,16 +100,16 @@ includes(name)&&requiredDecryptFailures.add(name)}if(!value)continue;let path=ty
|
|
|
140
100
|
force:!0})}}}return sawBackendFailure==="unavailable"?setCookieDiagnostic("SQLite backend unavailable: install sqlite3 or use a runtime with SQLite support.",attempts):sawBackendFailure==="query"?setCookieDiagnostic("SQLite query failed while reading the copied Chromium cookie database.",attempts):sawUnsafeProfilePath?setCookieDiagnostic("Configured Chromium profile must resolve inside the browser profile root.",attempts):sawCookieDatabase?requiredCookies?.length&&!sawRequiredCookies?setCookieDiagnostic(
|
|
141
101
|
`No detected Chromium profile contains the required ${options.requiredLabel??"browser"} cookies.`,attempts):sawWindowsAppBoundCookie?setCookieDiagnostic("Windows Chromium v20 app-bound cookies are not supported.",attempts):warningSet.size>0?setCookieDiagnostic([...warningSet][0],attempts):setCookieDiagnostic(sawDecryptionFailure?`Required ${options.requiredLabel??"browser"} cookies could not be decrypted.`:sawAnyHostCookie?"Required Gemini cookies were not available or could not be decrypted.":options.
|
|
142
102
|
requestUrl?"No detected Chromium profile contains cookies for the requested URL.":"No detected Chromium profile contains cookies for the requested host.",attempts):setCookieDiagnostic(requestedProfile?`Chromium profile '${requestedProfile}' does not contain a cookie database.`:"No detected Chromium profile contains a cookie database.",attempts),null}function setCookieDiagnostic(message,attempts=[]){lastCookieDiagnostic=message,lastCookieDiagnosticDetails={message,attempts}}function recordCookieAttempt(attempts,config,profile,status){
|
|
143
|
-
attempts.push({browser:config.name,profile,status})}function normalizeProfileName(value){if(typeof value!="string")return;let normalized=value.trim();if(normalized&&!(isAbsolute(normalized)||normalized==="."||normalized===".."||normalized.includes("/")||normalized.includes("\\")))return normalized}function resolveProfilePath(home,config,profile){let basePath=browserBasePath(home,config),profilePath=
|
|
144
|
-
basePath),profileRealPath=realpathSync2(profilePath);return profileRealPath!==baseRealPath&&!profileRealPath.startsWith(`${baseRealPath}${sep}`)?"outside-root":profileRealPath}catch{return null}}function cookieDatabasePath(profilePath,config){let networkCookies=
|
|
145
|
-
return config.usesLocalAppData?
|
|
146
|
-
function listBrowserProfiles(home,config){let basePath=browserBasePath(home,config);if(!
|
|
103
|
+
attempts.push({browser:config.name,profile,status})}function normalizeProfileName(value){if(typeof value!="string")return;let normalized=value.trim();if(normalized&&!(isAbsolute(normalized)||normalized==="."||normalized===".."||normalized.includes("/")||normalized.includes("\\")))return normalized}function resolveProfilePath(home,config,profile){let basePath=browserBasePath(home,config),profilePath=join2(basePath,profile);if(!cookieDatabasePath(profilePath,config))return null;try{let baseRealPath=realpathSync2(
|
|
104
|
+
basePath),profileRealPath=realpathSync2(profilePath);return profileRealPath!==baseRealPath&&!profileRealPath.startsWith(`${baseRealPath}${sep}`)?"outside-root":profileRealPath}catch{return null}}function cookieDatabasePath(profilePath,config){let networkCookies=join2(profilePath,"Network","Cookies");if(config.usesLocalAppData&&existsSync4(networkCookies))return networkCookies;let legacyCookies=join2(profilePath,"Cookies");return existsSync4(legacyCookies)?legacyCookies:null}function browserBasePath(home,config){
|
|
105
|
+
return config.usesLocalAppData?join2(process.env.LOCALAPPDATA||join2(home,"AppData","Local"),config.baseDir):join2(home,config.baseDir)}function normalizeCookieNames(names){if(!names?.length)return;let normalized=names.filter(name=>typeof name=="string").map(name=>name.trim()).filter(Boolean);return normalized.length>0?[...new Set(normalized)]:void 0}function normalizeHosts(hosts){return[...new Set(hosts.map(host=>host.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")).filter(Boolean))]}
|
|
106
|
+
function listBrowserProfiles(home,config){let basePath=browserBasePath(home,config);if(!existsSync4(basePath))return["Default"];let profiles=new Set;try{for(let entry of readdirSync2(basePath,{withFileTypes:!0}))entry.isDirectory()&&cookieDatabasePath(join2(basePath,entry.name),config)&&profiles.add(entry.name)}catch{}return profiles.size===0?["Default"]:[...profiles].sort(compareProfileNames)}function compareProfileNames(a,b){let key=name=>{if(name==="Default")return[0,0];let profile=/^Profile\s+(\d+)$/i.
|
|
147
107
|
exec(name);if(profile)return[1,Number(profile[1])];let person=/^Person\s+(\d+)$/i.exec(name);return person?[2,Number(person[1])]:[3,Number.MAX_SAFE_INTEGER]},[ap,ai]=key(a),[bp,bi]=key(b);return ap-bp||ai-bi||a.localeCompare(b,void 0,{sensitivity:"base",numeric:!0})}function decryptCookieValue(encrypted,key,stripHash){let buf=Buffer.from(encrypted);if(buf.length<3||!/^v\d\d$/.test(buf.subarray(0,3).toString("utf8")))return null;let ciphertext=buf.subarray(3);if(!ciphertext.length)return"";try{let decipher=createDecipheriv(
|
|
148
108
|
"aes-128-cbc",key,Buffer.alloc(16,32));decipher.setAutoPadding(!1);let unpadded=removePkcs7Padding(Buffer.concat([decipher.update(ciphertext),decipher.final()])),bytes=stripHash&&unpadded.length>=32?unpadded.subarray(32):unpadded,decoded=new TextDecoder("utf-8",{fatal:!0}).decode(bytes),i=0;for(;i<decoded.length&&decoded.charCodeAt(i)<32;)i++;return decoded.slice(i)}catch{return null}}function decryptWindowsCookieValue(encrypted,key,stripHash){let buf=Buffer.from(encrypted);if(buf.subarray(0,3).
|
|
149
109
|
toString("utf8")!=="v10"||buf.length<31)return null;try{let nonce=buf.subarray(3,15),ciphertext=buf.subarray(15,-16),decipher=createDecipheriv("aes-256-gcm",key,nonce);decipher.setAuthTag(buf.subarray(-16));let plaintext=Buffer.concat([decipher.update(ciphertext),decipher.final()]);return new TextDecoder("utf-8",{fatal:!0}).decode(stripHash&&plaintext.length>=32?plaintext.subarray(32):plaintext)}catch{return null}}function removePkcs7Padding(buf){if(!buf.length)return buf;let padding=buf[buf.length-
|
|
150
110
|
1];return!padding||padding>16?buf:buf.subarray(0,buf.length-padding)}function passwordCacheKey(config,currentPlatform){return`${currentPlatform}:${config.name}`}function readBrowserPasswords(config,currentPlatform){let cacheKey2=passwordCacheKey(config,currentPlatform),cached=browserPasswordCache.get(cacheKey2);if(cached)return cached;let passwordPromise=(currentPlatform==="darwin"?config.keychainAccount&&config.keychainService?readKeychainPassword(config.keychainAccount,config.keychainService).
|
|
151
|
-
then(value=>({value,cacheable:!!value})):Promise.resolve({value:null,cacheable:!1}):currentPlatform==="linux"?readLinuxPassword(config):Promise.resolve({value:null,cacheable:!1})).then(({cacheable,...password})=>(cacheable||browserPasswordCache.delete(cacheKey2),[password]),error=>{throw browserPasswordCache.delete(cacheKey2),error});return browserPasswordCache.set(cacheKey2,passwordPromise),passwordPromise}async function readWindowsEncryptionKey(config,home){try{let encodedKey=JSON.parse(
|
|
152
|
-
|
|
111
|
+
then(value=>({value,cacheable:!!value})):Promise.resolve({value:null,cacheable:!1}):currentPlatform==="linux"?readLinuxPassword(config):Promise.resolve({value:null,cacheable:!1})).then(({cacheable,...password})=>(cacheable||browserPasswordCache.delete(cacheKey2),[password]),error=>{throw browserPasswordCache.delete(cacheKey2),error});return browserPasswordCache.set(cacheKey2,passwordPromise),passwordPromise}async function readWindowsEncryptionKey(config,home){try{let encodedKey=JSON.parse(readFileSync3(
|
|
112
|
+
join2(browserBasePath(home,config),"Local State"),"utf8")).os_crypt?.encrypted_key;if(typeof encodedKey!="string")return null;let protectedKey=Buffer.from(encodedKey,"base64");if(protectedKey.subarray(0,5).toString("utf8")!=="DPAPI")return null;let decrypted=await unprotectWindowsData(protectedKey.subarray(5));return decrypted?.length===32?decrypted:null}catch{return null}}function unprotectWindowsData(protectedData){return new Promise(resolve=>{let encoded=Buffer.from("Add-Type -AssemblyName Sy\
|
|
153
113
|
stem.Security;$data=[Convert]::FromBase64String($env:PIWA_PROTECTED);$clear=[System.Security.Cryptography.ProtectedData]::Unprotect($data,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);[Console]::Write([Convert]::ToBase64String($clear))","utf16le").toString("base64");execFile4("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",encoded],{timeout:5e3,maxBuffer:1024*1024,env:{...process.env,PIWA_PROTECTED:protectedData.toString("base64")}},(err,stdout)=>{if(err){
|
|
154
114
|
resolve(null);return}try{resolve(Buffer.from(stdout.trim(),"base64"))}catch{resolve(null)}})})}function readKeychainPassword(account,service){return new Promise(resolve=>{execFile4("security",["find-generic-password","-w","-a",account,"-s",service],{timeout:5e3},(err,stdout)=>{if(err){resolve(null);return}resolve(stdout.trim()||null)})})}function readLinuxCommandPassword(command,args){return new Promise(resolve=>{execFile4(command,args,{timeout:5e3},(err,stdout)=>resolve({value:err?null:stdout.trim()||
|
|
155
115
|
null,failed:!!err}))})}function isKdeSession(){let desktop=process.env.XDG_CURRENT_DESKTOP?.toLowerCase().split(":")??[];return process.env.KDE_FULL_SESSION?.toLowerCase()==="true"||desktop.includes("kde")}async function readKWalletPassword(config){if(!isKdeSession()||!config.kwalletFolder||!config.kwalletEntry)return{value:null};let result=await readLinuxCommandPassword("kwallet-query",["-f",config.kwalletFolder,"-r",config.kwalletEntry,"kdewallet"]);return{value:result.value,source:result.value?
|
|
@@ -170,42 +130,42 @@ columns.columns.has("expires_utc")?` AND (${expiresExpr} = 0 OR ${expiresExpr} >
|
|
|
170
130
|
let result=await runSqliteQuery(dbPath,"PRAGMA table_info(cookies)");return result.status==="failure"?result:{status:"success",columns:new Set(result.rows.map(row=>typeof row.name=="string"?row.name:""))}}function chromeExpiryMillisExpr(){return"CASE WHEN expires_utc = 0 THEN 0 ELSE CAST(expires_utc / 1000 AS INTEGER) + CASE WHEN expires_utc % 1000 = 0 THEN 0 ELSE 1 END END"}function chromeExpiryNowMillis(){return Date.now()+116444736e5}function unpartitionedCookieFilter(columns){let clauses=[];
|
|
171
131
|
return columns.has("top_frame_site_key")&&clauses.push("(top_frame_site_key IS NULL OR top_frame_site_key = '')"),columns.has("partition_key")&&clauses.push("(partition_key IS NULL OR partition_key = '')"),columns.has("is_partitioned")&&clauses.push("(is_partitioned IS NULL OR is_partitioned = 0)"),clauses.length>0?` AND ${clauses.join(" AND ")}`:""}function buildCookieHeader(entries){return entries.sort((a,b)=>b.path.length-a.path.length).map(({name,value})=>`${name}=${value}`).join("; ")}function pathMatches(requestPath,cookiePath){
|
|
172
132
|
return requestPath===cookiePath?!0:requestPath.startsWith(cookiePath)?cookiePath.endsWith("/")?!0:requestPath[cookiePath.length]==="/":!1}function buildCookieWhere(hosts,cookieNames){let hostClauses=[];for(let host of hosts){let escapedHost=escapeSqlString(host);hostClauses.push(`host_key = '${escapedHost}'`);for(let candidate of domainCookieHosts(host))hostClauses.push(`host_key = '.${escapeSqlString(candidate)}'`)}let where=`(${[...new Set(hostClauses)].join(" OR ")})`,names=cookieNames?[...cookieNames].
|
|
173
|
-
filter(Boolean):[];return names.length&&(where+=` AND name IN (${names.map(name=>`'${escapeSqlString(name)}'`).join(", ")})`),where}function escapeSqlString(value){return value.replaceAll("'","''")}function domainCookieHosts(host){let parts=host.split(".").filter(Boolean);if(parts.length<=1)return[];let candidates=new Set;for(let i=0;i<=parts.length-2;i++)candidates.add(parts.slice(i).join("."));return[...candidates]}function copySidecar(srcDb,targetDb,suffix){let sidecar=`${srcDb}${suffix}`;if(
|
|
174
|
-
sidecar))try{copyFileSync(sidecar,`${targetDb}${suffix}`)}catch{}}import{lookup as dnsLookup}from"node:dns/promises";import{existsSync as
|
|
175
|
-
signature===signature)return cachedConfigRoot.value;let raw;try{raw=
|
|
133
|
+
filter(Boolean):[];return names.length&&(where+=` AND name IN (${names.map(name=>`'${escapeSqlString(name)}'`).join(", ")})`),where}function escapeSqlString(value){return value.replaceAll("'","''")}function domainCookieHosts(host){let parts=host.split(".").filter(Boolean);if(parts.length<=1)return[];let candidates=new Set;for(let i=0;i<=parts.length-2;i++)candidates.add(parts.slice(i).join("."));return[...candidates]}function copySidecar(srcDb,targetDb,suffix){let sidecar=`${srcDb}${suffix}`;if(existsSync4(
|
|
134
|
+
sidecar))try{copyFileSync(sidecar,`${targetDb}${suffix}`)}catch{}}import{lookup as dnsLookup}from"node:dns/promises";import{existsSync as existsSync5,readFileSync as readFileSync4,statSync as statSync2}from"node:fs";import net from"node:net";var DEFAULT_MAX_REDIRECTS=5,REDIRECT_STATUSES=new Set([301,302,303,307,308]),LOOPBACK_ALLOW_RANGES=["127.0.0.0/8","::1","::ffff:127.0.0.0/104"],REMOTE_DNS_PROXY_PROTOCOLS=new Set(["http:","https:","socks4a:","socks5h:"]),WEB_SEARCH_CONFIG_PATH=getWebSearchConfigPath(),cachedConfigRoot=null;function loadConfigRoot(){if(!existsSync5(WEB_SEARCH_CONFIG_PATH))return null;let signature;try{let stat=statSync2(WEB_SEARCH_CONFIG_PATH);signature=`${stat.mtimeMs}:${stat.size}`}catch{return null}if(cachedConfigRoot?.
|
|
135
|
+
signature===signature)return cachedConfigRoot.value;let raw;try{raw=readFileSync4(WEB_SEARCH_CONFIG_PATH,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`)}let value=parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:null;return cachedConfigRoot={signature,value},value}var DEFAULT_DOMAIN_POLICY={allow:[],deny:[]};function loadFetchContentConfig(){
|
|
176
136
|
let parsed=loadConfigRoot();if(!parsed)return;let fetchContent=parsed.fetchContent;if(fetchContent!=null){if(typeof fetchContent!="object"||Array.isArray(fetchContent))throw new Error(`fetchContent in ${WEB_SEARCH_CONFIG_PATH} must be an object`);return fetchContent}}function loadFetchContentRedirectPolicy(){let redirects=loadFetchContentConfig()?.redirects;if(redirects!=null){if(redirects!=="same-origin")throw new Error(`fetchContent.redirects in ${WEB_SEARCH_CONFIG_PATH} must be "same-origin"`);
|
|
177
137
|
return redirects}}var DEFAULT_FETCH_CONTENT_USER_AGENT="OpenAI File Downloader, XaiImageApiFetch/1.0";function loadFetchContentUserAgent(){return loadConfiguredFetchContentUserAgent()??DEFAULT_FETCH_CONTENT_USER_AGENT}function loadConfiguredFetchContentUserAgent(){let userAgent=loadFetchContentConfig()?.userAgent;if(userAgent!=null){if(typeof userAgent!="string"||userAgent.trim().length===0||!/^[\t\x20-\x7e]+$/.test(userAgent))throw new Error(`fetchContent.userAgent in ${WEB_SEARCH_CONFIG_PATH} \
|
|
178
138
|
must be a non-empty string of printable ASCII characters`);return userAgent.trim()}}function loadFetchContentCurl(){let curl=loadFetchContentConfig()?.curl;if(curl==null)return null;let command=typeof curl=="string"?[curl]:Array.isArray(curl)?curl:null;if(!command||command.length===0||command.some(part=>typeof part!="string"||part.trim().length===0||part.includes("\0")))throw new Error(`fetchContent.curl in ${WEB_SEARCH_CONFIG_PATH} must be a command name or path, or a non-empty array of a comma\
|
|
179
139
|
nd and its arguments`);return command.map(part=>part.trim())}function loadFetchContentDomainPolicy(){let policy=loadFetchContentConfig()?.domainPolicy;if(policy==null)return{...DEFAULT_DOMAIN_POLICY};if(typeof policy!="object"||Array.isArray(policy))throw new Error(`fetchContent.domainPolicy in ${WEB_SEARCH_CONFIG_PATH} must be an object`);let config=policy;return{allow:parseDomainEntries(config.allow,"allow"),deny:parseDomainEntries(config.deny,"deny")}}function parseDomainEntries(value,field){
|
|
180
|
-
if(value==null)return[];if(!Array.isArray(value))throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hostnames`);return value.map((entry,index)=>{if(typeof entry!="string")throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames; entry ${index+1} is ${typeof entry}`);let
|
|
181
|
-
contains an invalid hostname: ${JSON.stringify(entry)}`);return
|
|
182
|
-
|
|
183
|
-
must be a boolean`);let allowRanges=(Array.isArray(config.allowRanges)?config.allowRanges:[]).map((entry,index)=>{if(typeof entry!="string")throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must contain only CIDR strings; entry ${index+1} is ${typeof entry}`);return entry.trim()}).filter(Boolean);return parseAllowRanges(allowRanges),{allowRanges,trustEnvProxy:config.trustEnvProxy===!0}}async function defaultLookup(
|
|
184
|
-
let url=rawUrl instanceof URL?rawUrl:new URL(rawUrl);if(url.protocol!=="http:"&&url.protocol!=="https:")throw new Error("Only HTTP and HTTPS URLs can be fetched remotely");let
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
140
|
+
if(value==null)return[];if(!Array.isArray(value))throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hostnames`);return value.map((entry,index)=>{if(typeof entry!="string")throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames; entry ${index+1} is ${typeof entry}`);let hostname=normalizeDomainEntry(entry);if(!hostname)throw new Error(`fetchContent.domainPolicy.${field} in ${WEB_SEARCH_CONFIG_PATH}\
|
|
141
|
+
contains an invalid hostname: ${JSON.stringify(entry)}`);return hostname})}function normalizeDomainEntry(entry){let hostname=normalizeHostname(entry.trim());return!hostname||/\s|[\\/?:#@]/.test(hostname)?null:net.isIP(hostname)?hostname:hostname.length>253||!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(hostname)?null:hostname}function loadSsrfConfig(){let parsed=loadConfigRoot();if(!parsed)return{allowRanges:[],trustEnvProxy:!1};let ssrf=parsed.ssrf;
|
|
142
|
+
if(ssrf==null)return{allowRanges:[],trustEnvProxy:!1};if(typeof ssrf!="object"||Array.isArray(ssrf))throw new Error(`ssrf in ${WEB_SEARCH_CONFIG_PATH} must be an object`);let config=ssrf;if(config.allowRanges!==void 0&&config.allowRanges!==null&&!Array.isArray(config.allowRanges))throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must be an array of CIDR strings`);if(config.trustEnvProxy!==void 0&&typeof config.trustEnvProxy!="boolean")throw new Error(`ssrf.trustEnvProxy in ${WEB_SEARCH_CONFIG_PATH}\
|
|
143
|
+
must be a boolean`);let allowRanges=(Array.isArray(config.allowRanges)?config.allowRanges:[]).map((entry,index)=>{if(typeof entry!="string")throw new Error(`ssrf.allowRanges in ${WEB_SEARCH_CONFIG_PATH} must contain only CIDR strings; entry ${index+1} is ${typeof entry}`);return entry.trim()}).filter(Boolean);return parseAllowRanges(allowRanges),{allowRanges,trustEnvProxy:config.trustEnvProxy===!0}}async function defaultLookup(hostname){return dnsLookup(hostname,{all:!0,verbatim:!0})}async function validateRemoteUrl(rawUrl,options={}){
|
|
144
|
+
let url=rawUrl instanceof URL?rawUrl:new URL(rawUrl);if(url.protocol!=="http:"&&url.protocol!=="https:")throw new Error("Only HTTP and HTTPS URLs can be fetched remotely");let hostname=normalizeHostname(url.hostname);if(!hostname)throw new Error("URL must include a hostname");if(hostname==="localhost"){if(options.allowLoopback===!0)return url;throw new Error(`Blocked internal hostname: ${hostname}`)}if(hostname.endsWith(".localhost"))throw new Error(`Blocked internal hostname: ${hostname}`);let allowRanges=parseAllowRanges(
|
|
145
|
+
options.allowRanges);if(assertDomainPolicy(hostname,options.domainPolicy),net.isIP(hostname)){let addressAllowRanges=options.allowLoopback===!0?[...allowRanges,...parseAllowRanges(LOOPBACK_ALLOW_RANGES)]:allowRanges;return assertPublicAddress(hostname,hostname,addressAllowRanges),url}let trustProxy=options.trustEnvProxy===!0,proxy=options.proxy!==void 0?normalizeProxyUrl(options.proxy,"proxy"):hasScopedProxyDecision()?getActiveProxy():void 0;if(proxy===void 0?shouldTrustEnvProxy(url,trustProxy):
|
|
146
|
+
trustProxy&&isConfiguredRemoteDnsProxy(url,proxy))return url;let addresses;try{addresses=await(options.lookup??defaultLookup)(hostname)}catch(err){let message=err instanceof Error?err.message:String(err),hint=!trustProxy&&proxy&&isConfiguredRemoteDnsProxy(url,proxy)?". If your configured proxy resolves hostnames, set ssrf.trustEnvProxy to true in web-search.json.":"";throw new Error(`Failed to resolve ${hostname}: ${message}${hint}`)}if(addresses.length===0)throw new Error(`Failed to resolve ${hostname}\
|
|
147
|
+
: no addresses returned`);for(let{address}of addresses)assertPublicAddress(address,hostname,allowRanges);return url}async function fetchRemoteUrl(url,init={},options={}){let fetchImpl=options.fetch??fetch,maxRedirects=options.maxRedirects??DEFAULT_MAX_REDIRECTS,current=await validateRemoteUrl(url,options),configuredOrigin=current.origin,requestInit=init;for(let redirects=0;redirects<=maxRedirects;redirects++){let response=await fetchImpl(current,{...requestInit,redirect:"manual"});if(!REDIRECT_STATUSES.
|
|
148
|
+
has(response.status))return response;let location=response.headers.get("location");if(!location)return response;if(redirects===maxRedirects)throw new Error(`Too many redirects fetching ${current.toString()}`);let from=current,next=new URL(location,current);if(options.redirects==="same-origin"&&next.origin!==configuredOrigin)throw new Error(`Refused cross-origin redirect by fetch_content redirect policy: ${configuredOrigin} -> ${next.origin}`);if(current=await validateRemoteUrl(next,next.origin===
|
|
149
|
+
configuredOrigin?options:{...options,allowLoopback:!1}),response.status===303||(response.status===301||response.status===302)&&requestInit.method?.toUpperCase()==="POST"){let{body:_body,...nextInit}=requestInit;requestInit={...nextInit,method:"GET"}}options.onRedirect&&(requestInit=options.onRedirect({from,to:current,init:requestInit,response}))}throw new Error(`Too many redirects fetching ${current.toString()}`)}function normalizeHostname(hostname){return hostname.toLowerCase().replace(/^\[|\]$/g,
|
|
150
|
+
"").replace(/\.$/,"")}function assertDomainPolicy(hostname,policy){if(policy){if(policy.deny.some(entry=>domainMatches(hostname,entry)))throw new Error(`Blocked hostname by fetch_content domain policy: ${hostname}`);if(policy.allow.length>0&&!policy.allow.some(entry=>domainMatches(hostname,entry)))throw new Error(`Hostname not allowed by fetch_content domain policy: ${hostname}`)}}function domainMatches(hostname,entry){return hostname===entry||hostname.endsWith(`.${entry}`)}function getProxyForProtocol(protocol){
|
|
151
|
+
let candidates=protocol==="http:"?[process.env.HTTP_PROXY,process.env.http_proxy,process.env.ALL_PROXY,process.env.all_proxy]:protocol==="https:"?[process.env.HTTPS_PROXY,process.env.https_proxy,process.env.HTTP_PROXY,process.env.http_proxy,process.env.ALL_PROXY,process.env.all_proxy]:[];for(let candidate of candidates){let value=candidate?.trim();if(value)try{let proxyUrl=new URL(value);if((proxyUrl.protocol==="http:"||proxyUrl.protocol==="https:")&&proxyUrl.hostname)return value}catch{}}return""}
|
|
152
|
+
function hostnameMatchesNoProxy(hostname,port,entry){let trimmed=entry.trim();if(!trimmed)return!1;if(trimmed==="*")return!0;let hostEntry=trimmed,entryPort;if(hostEntry.startsWith("[")){let closingBracket=hostEntry.indexOf("]");if(closingBracket>=0){let suffix2=hostEntry.slice(closingBracket+1);/^:\\d+$/.test(suffix2)&&(entryPort=suffix2.slice(1)),hostEntry=hostEntry.slice(0,closingBracket+1)}}else{let colon=hostEntry.lastIndexOf(":");colon>-1&&/^\d+$/.test(hostEntry.slice(colon+1))&&(entryPort=
|
|
153
|
+
hostEntry.slice(colon+1),hostEntry=hostEntry.slice(0,colon))}if(entryPort!==void 0&&entryPort!==port)return!1;let normalizedEntry=normalizeHostname(hostEntry);if(!normalizedEntry)return!1;if(normalizedEntry===hostname)return!0;let suffix=normalizedEntry.startsWith("*.")?normalizedEntry.slice(1):normalizedEntry.startsWith(".")?normalizedEntry:`.${normalizedEntry}`;return hostname.endsWith(suffix)}function shouldTrustEnvProxy(url,enabled){if(!enabled||!getProxyForProtocol(url.protocol))return!1;let hostname=normalizeHostname(
|
|
154
|
+
url.hostname),port=url.port||(url.protocol==="https:"?"443":"80");return!(process.env.NO_PROXY||process.env.no_proxy||"").split(",").some(entry=>hostnameMatchesNoProxy(hostname,port,entry))}function trustedEnvProxyFor(url,trustEnvProxy){return net.isIP(normalizeHostname(url.hostname))?null:shouldTrustEnvProxy(url,trustEnvProxy)?getProxyForProtocol(url.protocol):null}function isConfiguredRemoteDnsProxy(url,proxy){return proxy!==null&&REMOTE_DNS_PROXY_PROTOCOLS.has(new URL(proxy).protocol)&&!isProxyBypassedUrl(
|
|
155
|
+
url)&&proxy===loadConfiguredProxy()}function assertPublicAddress(address,hostname,allowRanges=[]){let normalized=normalizeHostname(address),ipVersion=net.isIP(normalized);if(ipVersion===0)throw new Error(`Resolved non-IP address for ${hostname}: ${address}`);if(!isInAllowedRange(normalized,ipVersion,allowRanges)){if(ipVersion===4&&isBlockedIPv4(normalized)){let hint=isFakeIpProxyAddress(normalized)?'. This address is in 198.18.0.0/15, commonly used by TUN/fake-IP proxies. If that matches your se\
|
|
156
|
+
tup, configure ssrf.allowRanges with ["198.18.0.0/15"] in web-search.json.':"";throw new Error(`Blocked internal address for ${hostname}: ${normalized}${hint}`)}if(ipVersion===6&&isBlockedIPv6(normalized))throw new Error(`Blocked internal address for ${hostname}: ${normalized}`)}}function isFakeIpProxyAddress(address){let[a,b]=address.split(".").map(part=>Number(part));return a===198&&(b===18||b===19)}function isBlockedIPv4(address){let parts=address.split(".").map(part=>Number(part));if(parts.length!==
|
|
157
|
+
4||parts.some(part=>!Number.isInteger(part)||part<0||part>255))return!0;let[a,b]=parts;return a===0||a===10||a===127||a===100&&b>=64&&b<=127||a===169&&b===254||a===172&&b>=16&&b<=31||a===192&&b===168||isFakeIpProxyAddress(address)||a>=224}function isBlockedIPv6(address){let groups=parseIPv6(address);if(!groups)return!0;let first=groups[0];if(groups.every(group=>group===0)||groups.slice(0,7).every(group=>group===0)&&groups[7]===1||(first&65024)===64512||(first&65472)===65152)return!0;if(groups.slice(
|
|
158
|
+
0,5).every(group=>group===0)&&groups[5]===65535){let ipv4=[groups[6]>>8,groups[6]&255,groups[7]>>8,groups[7]&255].join(".");return isBlockedIPv4(ipv4)}return!1}function parseIPv6(address){if(address.includes(".")){let lastColon=address.lastIndexOf(":"),ipv4=address.slice(lastColon+1);if(net.isIP(ipv4)!==4)return null;let octets=ipv4.split(".").map(part=>Number(part));address=`${address.slice(0,lastColon)}:${(octets[0]<<8|octets[1]).toString(16)}:${(octets[2]<<8|octets[3]).toString(16)}`}let pieces=address.
|
|
159
|
+
split("::");if(pieces.length>2)return null;let left=pieces[0]?pieces[0].split(":"):[],right=pieces.length===2&&pieces[1]?pieces[1].split(":"):[],missing=8-left.length-right.length;if(pieces.length===1&&missing!==0||pieces.length===2&&missing<0)return null;let groups=[...left,...Array(missing).fill("0"),...right].map(part=>/^[0-9a-f]{1,4}$/i.test(part)?parseInt(part,16):-1);return groups.length===8&&groups.every(group=>group>=0&&group<=65535)?groups:null}function parseAllowRanges(input){if(input==
|
|
160
|
+
null)return[];if(!Array.isArray(input))throw new Error("ssrf.allowRanges must be an array of CIDR strings");let rules=[];for(let entry of input){if(typeof entry!="string")throw new Error(`ssrf.allowRanges entries must be strings, got ${typeof entry}`);let rule=parseCidr(entry.trim());if(!rule)throw new Error(`Invalid CIDR notation in ssrf.allowRanges: "${entry}"`);rules.push(rule)}return rules}function parseCidr(raw){if(!raw)return null;let slash=raw.lastIndexOf("/"),addrPart=slash>=0?raw.slice(
|
|
161
|
+
0,slash):raw,prefixPart=slash>=0?raw.slice(slash+1):null;if(prefixPart!==null&&!/^\d+$/.test(prefixPart))return null;let version=net.isIP(addrPart);if(version===4){let bytes=ipv4ToBytes(addrPart);if(!bytes)return null;let prefix=prefixPart===null?32:Number(prefixPart);return!Number.isInteger(prefix)||prefix<1||prefix>32?null:{bytes,prefix}}if(version===6){let groups=parseIPv6(addrPart);if(!groups)return null;let prefix=prefixPart===null?128:Number(prefixPart);return!Number.isInteger(prefix)||prefix<
|
|
162
|
+
1||prefix>128?null:{bytes:ipv6GroupsToBytes(groups),prefix}}return null}function ipv4ToBytes(address){let parts=address.split(".");if(parts.length!==4)return null;let bytes=new Uint8Array(4);for(let i=0;i<4;i++){let octet=Number(parts[i]);if(!Number.isInteger(octet)||octet<0||octet>255)return null;bytes[i]=octet}return bytes}function ipv6GroupsToBytes(groups){let bytes=new Uint8Array(16);for(let i=0;i<8;i++)bytes[i*2]=groups[i]>>8,bytes[i*2+1]=groups[i]&255;return bytes}function ipToBytes(address,version){
|
|
163
|
+
if(version===4)return ipv4ToBytes(address);if(version===6){let groups=parseIPv6(address);return groups?ipv6GroupsToBytes(groups):null}return null}function isInAllowedRange(address,ipVersion,allowRanges){if(allowRanges.length===0)return!1;let addrBytes=ipToBytes(address,ipVersion);if(!addrBytes)return!1;for(let rule of allowRanges)if(rule.bytes.length===addrBytes.length&&bytesMatchPrefix(addrBytes,rule.bytes,rule.prefix))return!0;return!1}function bytesMatchPrefix(addr,network,prefix){let fullBytes=prefix>>
|
|
164
|
+
3,remBits=prefix&7;for(let i=0;i<fullBytes;i++)if(addr[i]!==network[i])return!1;if(remBits>0&&fullBytes<addr.length){let mask=255<<8-remBits&255;if((addr[fullBytes]&mask)!==(network[fullBytes]&mask))return!1}return!0}import{existsSync as existsSync6,readFileSync as readFileSync5}from"node:fs";var EXA_API_BASE_URL="https://api.exa.ai",EXA_MCP_URL="https://mcp.exa.ai/mcp",CONFIG_PATH3=getWebSearchConfigPath(),EXA_MCP_ADVANCED_TOOL="web_search_advanced_exa",EXA_MCP_BASIC_TOOL="web_search_exa",CONTENTS_TIMEOUT_MS=6e4,MAX_LISTED_AUTHORS=3,cachedConfig3=null;function loadConfig2(){if(cachedConfig3)return cachedConfig3;if(!existsSync6(CONFIG_PATH3))return cachedConfig3={},cachedConfig3;let raw=readFileSync5(CONFIG_PATH3,"utf-8");try{return cachedConfig3=JSON.parse(raw),cachedConfig3}catch(err){
|
|
205
165
|
let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH3}: ${message}`)}}async function getApiKey(signal){return resolveCredential({provider:"Exa",configuredValue:loadConfig2().exaApiKey,environmentValue:process.env.EXA_API_KEY,signal})}function getApiBaseUrl(){return resolveApiBaseUrl({configKey:"exaBaseUrl",configuredValue:loadConfig2().exaBaseUrl,defaultValue:EXA_API_BASE_URL,environmentKey:"EXA_BASE_URL",environmentValue:process.env.EXA_BASE_URL})}
|
|
206
166
|
function exaApiHeaders(apiKey){return{"x-api-key":apiKey,"Content-Type":"application/json","x-exa-integration":"pi-web-access"}}function requestSignal(signal){let timeout=AbortSignal.timeout(6e4);return signal?AbortSignal.any([signal,timeout]):timeout}function recencyToStartDate(filter){let now=new Date,days={day:1,week:7,month:30,year:365}[filter]??0;return new Date(now.getTime()-days*864e5).toISOString()}function mapDomainFilter(domainFilter){if(!domainFilter?.length)return{};let includeDomains=domainFilter.
|
|
207
167
|
filter(d=>!d.startsWith("-")&&d.trim().length>0).map(d=>d.trim()),excludeDomains=domainFilter.filter(d=>d.startsWith("-")).map(d=>d.slice(1).trim()).filter(Boolean);return{...includeDomains.length?{includeDomains}:{},...excludeDomains.length?{excludeDomains}:{}}}function exaSearchArgs(query,options){let startDate=options.recencyFilter?recencyToStartDate(options.recencyFilter):null;return{query,type:"auto",numResults:options.numResults??5,...mapDomainFilter(options.domainFilter),...options.category?
|
|
208
|
-
{category:options.category}:{},...startDate?{startPublishedDate:startDate}:{}}}function normalizeHighlights(value){return Array.isArray(value)?value.filter(item=>typeof item=="string"&&item.trim().length>0):[]}function fallbackSourceLabel(url,index){try{let
|
|
168
|
+
{category:options.category}:{},...startDate?{startPublishedDate:startDate}:{}}}function normalizeHighlights(value){return Array.isArray(value)?value.filter(item=>typeof item=="string"&&item.trim().length>0):[]}function fallbackSourceLabel(url,index){try{let hostname=url?new URL(url).hostname:"";if(hostname)return hostname}catch{}return`Source ${index+1}`}function nonEmptyString(value){return typeof value=="string"&&value.trim().length>0&&value.trim()!=="N/A"?value.trim():null}function publicationProperties(entities){
|
|
209
169
|
let entity=Array.isArray(entities)?entities.find(item=>isRecord(item)&&item.type==="publication"):void 0;return isRecord(entity)&&isRecord(entity.properties)?entity.properties:null}function listAuthors(names){if(names.length===0)return null;let listed=names.slice(0,MAX_LISTED_AUTHORS).join(", ");return names.length>MAX_LISTED_AUTHORS?`${listed} et al.`:listed}function formatResultMetadata(item){let paper=publicationProperties(item.entities),parts=[],date=(nonEmptyString(item.publishedDate)??nonEmptyString(
|
|
210
170
|
paper?.date))?.slice(0,10)??(typeof paper?.year=="number"?String(paper.year):null);date&&parts.push(`Published: ${date}`);let paperAuthors=Array.isArray(paper?.authors)?paper.authors.flatMap(author=>nonEmptyString(isRecord(author)?author.name:null)??[]):[],authors=listAuthors(paperAuthors)??listAuthors(nonEmptyString(item.author)?.split(", ").map(name=>name.trim()).filter(Boolean)??[]);authors&&parts.push(`Authors: ${authors}`),typeof paper?.citationCount=="number"&&parts.push(`Citations: ${paper.
|
|
211
171
|
citationCount}`);let doi=nonEmptyString(paper?.doi);return doi&&parts.push(`DOI: ${doi}`),parts.length>0?`
|
|
@@ -234,8 +194,9 @@ redactedMessage)}}async function extractWithExa(url,signal,options={}){let apiKe
|
|
|
234
194
|
lookup?{lookup:options.lookup}:{}});let response=await fetchWithCredentialRedirects(`${getApiBaseUrl()}/contents`,{method:"POST",headers:exaApiHeaders(apiKey),body:JSON.stringify({urls:[url],text:!0}),signal:signal?AbortSignal.any([timeoutSignal,signal]):timeoutSignal},["x-api-key"]);if(!response.ok)throw new Error(`Exa contents error ${response.status}: ${redactCredential(await response.text(),apiKey).slice(0,300)}`);let data=await response.json();if(!isRecord(data)||!Array.isArray(data.results))
|
|
235
195
|
throw new Error("Exa contents returned an unexpected response shape");let failed=Array.isArray(data.statuses)?data.statuses.find(status=>isRecord(status)&&status.status==="error"):void 0;if(failed){let detail=isRecord(failed.error)?failed.error:{},tag=typeof detail.tag=="string"?detail.tag:"unknown error",httpStatus=typeof detail.httpStatusCode=="number"?` (HTTP ${detail.httpStatusCode})`:"";throw new Error(`Exa could not read ${url}: ${tag}${httpStatus}`)}let page=data.results[0],content=isRecord(
|
|
236
196
|
page)&&typeof page.text=="string"?page.text.trim():"";return activityMonitor.logComplete(activityId,response.status),content?{url,title:isRecord(page)&&typeof page.title=="string"?page.title.trim():"",content,error:null}:null}catch(err){if(signal?.aborted)throw activityMonitor.logComplete(activityId,0),new Error("Aborted");let message=timeoutSignal.aborted||err instanceof Error&&err.name==="TimeoutError"?`Exa contents request timed out after ${Math.round(timeoutMs/1e3)}s`:redactCredential(err instanceof
|
|
237
|
-
Error?err.message:String(err),apiKey);throw activityMonitor.logError(activityId,message),new Error(message)}}import{existsSync as
|
|
238
|
-
|
|
197
|
+
Error?err.message:String(err),apiKey);throw activityMonitor.logError(activityId,message),new Error(message)}}import{existsSync as existsSync7,readFileSync as readFileSync6}from"node:fs";function normalizeDomain(value){let input=value.trim().toLowerCase();if(!input||(input.startsWith("-")&&(input=input.slice(1).trim()),!input))return null;try{input=(input.includes("://")?new URL(input):new URL(`https://${input}`)).hostname}catch{input=input.split("/")[0]?.split(":")[0]??""}return input=input.replace(/^\.+|\.+$/g,""),/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(input)?input:null}function applyDomainFilter(results,domainFilter){if(!domainFilter?.length)return results;let includes=[],excludes=[];
|
|
198
|
+
for(let raw of domainFilter){let normalized=normalizeDomain(raw);normalized&&(raw.trim().startsWith("-")?excludes.push(normalized):includes.push(normalized))}return!includes.length&&!excludes.length?results:results.filter(result=>{let host;try{host=new URL(result.url).hostname.toLowerCase()}catch{return!1}let matches=domain=>host===domain||host.endsWith(`.${domain}`);return!(excludes.some(matches)||includes.length&&!includes.some(matches))})}var PARALLEL_API_BASE_URL="https://api.parallel.ai",CONFIG_PATH4=getWebSearchConfigPath(),MIN_PARALLEL_API_KEY_LENGTH=8,MIN_USEFUL_CONTENT=500,SEARCH_TIMEOUT_MS=6e4,PLACEHOLDER_API_KEY_DENYLIST=new Set(["replace_with_your_parallel_api_key","parallel_api_key","your-key","your-key-here","your-api-key-here","dummy","placeholder","changeme","insert-your-key","insert-your-key-here","api-key","xxx"]),cachedConfig4=null;function loadConfig3(){if(cachedConfig4)return cachedConfig4;if(!existsSync7(CONFIG_PATH4))
|
|
199
|
+
return cachedConfig4={},cachedConfig4;let raw=readFileSync6(CONFIG_PATH4,"utf-8");try{return cachedConfig4=JSON.parse(raw),cachedConfig4}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH4}: ${message}`)}}function normalizeApiKey(value){if(typeof value!="string")return null;let normalized=value.trim();return normalized.length>0?normalized:null}function isPlaceholderApiKey(key){let normalized=key.trim();return normalized.length<MIN_PARALLEL_API_KEY_LENGTH||PLACEHOLDER_API_KEY_DENYLIST.has(normalized.toLowerCase())}async function resolveParallelApiKey(signal){let configKey=normalizeApiKey(loadConfig3().parallelApiKey);if(configKey?.startsWith("$")||configKey?.startsWith("!")){let resolved=await resolveCredential(
|
|
239
200
|
{provider:"Parallel",configuredValue:configKey,environmentValue:process.env.PARALLEL_API_KEY,signal});return resolved&&!isPlaceholderApiKey(resolved)?resolved:null}let envKey=normalizeApiKey(process.env.PARALLEL_API_KEY);return envKey&&!isPlaceholderApiKey(envKey)?envKey:configKey&&!isPlaceholderApiKey(configKey)?configKey:null}function hasConfiguredApiKey(){let configKey=normalizeApiKey(loadConfig3().parallelApiKey);if(configKey?.startsWith("$")||configKey?.startsWith("!"))return hasCredentialSource(
|
|
240
201
|
{provider:"Parallel",configuredValue:configKey,environmentValue:process.env.PARALLEL_API_KEY});let envKey=normalizeApiKey(process.env.PARALLEL_API_KEY);return envKey!==null&&!isPlaceholderApiKey(envKey)||configKey!==null&&!isPlaceholderApiKey(configKey)}async function getApiKey2(signal){let key=await resolveParallelApiKey(signal);if(!key)throw new Error(`Parallel API key not found. Either:
|
|
241
202
|
1. Create ${CONFIG_PATH4} with { "parallelApiKey": "your-key" }
|
|
@@ -259,8 +220,8 @@ results);inlineContent.length>0&&(response.inlineContent=inlineContent)}return r
|
|
|
259
220
|
let apiKey=await getApiKey2(signal),activityId=activityMonitor.logStart(activityContext(url,body)),response;try{response=await fetchWithCredentialRedirects(url,{method:"POST",headers:{"x-api-key":apiKey,"Content-Type":"application/json"},body:JSON.stringify(body),signal:requestSignal2(signal)},["x-api-key"])}catch(err){let message=errorMessage(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.
|
|
260
221
|
logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}if(!response.ok){activityMonitor.logComplete(activityId,response.status);let errorText=redactCredential(await response.text(),apiKey);throw new Error(`Parallel API error ${response.status}: ${errorText.slice(0,300)}`)}try{let data=await response.json();return activityMonitor.logComplete(activityId,response.status),
|
|
261
222
|
data}catch(err){throw activityMonitor.logComplete(activityId,response.status),new Error(`Parallel API returned invalid JSON: ${errorMessage(err)}`)}}var PARALLEL_MCP_URL="https://search.parallel.ai/mcp",CONFIG_PATH5=getWebSearchConfigPath(),REQUEST_TIMEOUT_MS=6e4;function requestSignal3(signal){let timeout=AbortSignal.timeout(REQUEST_TIMEOUT_MS);return signal?AbortSignal.any([signal,timeout]):timeout}function errorMessage2(err){return err instanceof Error?err.message:String(err)}function normalizeDomain2(value){let input=value.trim().toLowerCase();if(input.startsWith("-")&&(input=input.slice(1).trim()),!input)return null;try{input=(input.includes(
|
|
262
|
-
"://")?new URL(input):new URL(`https://${input}`)).hostname}catch{input=input.split("/")[0]?.split(":")[0]??""}return input=input.replace(/^\.+|\.+$/g,""),/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(input)?input:null}function domainMatches2(
|
|
263
|
-
|
|
223
|
+
"://")?new URL(input):new URL(`https://${input}`)).hostname}catch{input=input.split("/")[0]?.split(":")[0]??""}return input=input.replace(/^\.+|\.+$/g,""),/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(input)?input:null}function domainMatches2(hostname,domain){return hostname===domain||hostname.endsWith(`.${domain}`)}function filterResults(results,domainFilter){if(!domainFilter?.length)return results;let included=domainFilter.filter(value=>!value.trim().startsWith("-")).map(normalizeDomain2).filter(value=>value!==
|
|
224
|
+
null),excluded=domainFilter.filter(value=>value.trim().startsWith("-")).map(normalizeDomain2).filter(value=>value!==null);return results.filter(result=>{let hostname;try{hostname=new URL(result.url).hostname.toLowerCase()}catch{return!1}return(included.length===0||included.some(domain=>domainMatches2(hostname,domain)))&&!excluded.some(domain=>domainMatches2(hostname,domain))})}function buildSearchQuery(query,options){let parts=[query];for(let raw of options.domainFilter??[]){let domain=normalizeDomain2(
|
|
264
225
|
raw);domain&&parts.push(raw.trim().startsWith("-")?`-site:${domain}`:`site:${domain}`)}if(options.recencyFilter){let labels={day:"past 24 hours",week:"past week",month:"past month",year:"past year"};parts.push(labels[options.recencyFilter])}return parts.join(" ")}async function callParallelMcp(toolName,args,signal){let apiKey=await resolveParallelApiKey(signal),headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream","User-Agent":"pi-web-access"};apiKey&&(headers.Authorization=
|
|
265
226
|
`Bearer ${apiKey}`);let response;try{response=await fetch(PARALLEL_MCP_URL,{method:"POST",headers,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:toolName,arguments:args}}),signal:requestSignal3(signal)})}catch(err){let message=apiKey?redactCredential(errorMessage2(err),apiKey):errorMessage2(err);throw message===errorMessage2(err)?err:new Error(message)}let body=await response.text(),safeBody=apiKey?redactCredential(body,apiKey):body;if(!response.ok)throw response.status===
|
|
266
227
|
429?new Error(`Parallel MCP rate limit reached (429). Add parallelApiKey to ${CONFIG_PATH5} or set PARALLEL_API_KEY for higher limits: ${safeBody.slice(0,200)}`):new Error(`Parallel MCP error ${response.status}: ${safeBody.slice(0,300)}`);let parsed=null;for(let candidateText of[...body.split(`
|
|
@@ -277,10 +238,10 @@ Source: ${result.title||`Source ${index+1}`} (${result.url})`]:[]}).join(`
|
|
|
277
238
|
`);return content?[{url:result.url,title:result.title||"",content,error:null}]:[]});inlineContent.length&&(response.inlineContent=inlineContent)}return response}catch(err){let message=errorMessage2(err);throw message.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,message),err}}async function extractWithParallelMcp(url,signal,options={}){let activityId=activityMonitor.logStart({type:"fetch",url});try{let objective=options.prompt?.trim(),
|
|
278
239
|
payload=await callParallelMcp("web_fetch",{urls:[url],...objective?{objective:objective.slice(0,200)}:{},full_content:!0},signal),result=getResults(payload).find(item=>item.url===url)??getResults(payload)[0];if(!result)return activityMonitor.logComplete(activityId,200),null;let content=(typeof result.full_content=="string"?result.full_content.trim():"")||excerpts(result).join(`
|
|
279
240
|
|
|
280
|
-
`);return activityMonitor.logComplete(activityId,200),content?{url:result.url,title:result.title||"",content,error:null}:null}catch(err){let message=errorMessage2(err);throw message.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,message),err}}import{existsSync as
|
|
241
|
+
`);return activityMonitor.logComplete(activityId,200),content?{url:result.url,title:result.title||"",content,error:null}:null}catch(err){let message=errorMessage2(err);throw message.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,message),err}}import{existsSync as existsSync8,readFileSync as readFileSync7}from"node:fs";function formatSearchResultsAsAnswer(results){return results.map(result=>result.snippet?`${result.snippet}
|
|
281
242
|
Source: ${result.title} (${result.url})`:`Source: ${result.title} (${result.url})`).join(`
|
|
282
243
|
|
|
283
|
-
`)}function normalizeSearchResultCount(value){return typeof value!="number"||!Number.isFinite(value)?5:Math.max(1,Math.min(Math.floor(value),20))}var TINYFISH_SEARCH_URL="https://api.search.tinyfish.ai",TINYFISH_FETCH_URL="https://api.fetch.tinyfish.ai",CONFIG_PATH6=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS2=6e4,FETCH_TIMEOUT_MS=15e4,MAX_FETCH_URLS=10,MAX_FETCH_PER_URL_TIMEOUT_MS=11e4,cachedConfig5=null;function loadConfig4(){if(cachedConfig5)return cachedConfig5;if(!
|
|
244
|
+
`)}function normalizeSearchResultCount(value){return typeof value!="number"||!Number.isFinite(value)?5:Math.max(1,Math.min(Math.floor(value),20))}var TINYFISH_SEARCH_URL="https://api.search.tinyfish.ai",TINYFISH_FETCH_URL="https://api.fetch.tinyfish.ai",CONFIG_PATH6=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS2=6e4,FETCH_TIMEOUT_MS=15e4,MAX_FETCH_URLS=10,MAX_FETCH_PER_URL_TIMEOUT_MS=11e4,cachedConfig5=null;function loadConfig4(){if(cachedConfig5)return cachedConfig5;if(!existsSync8(CONFIG_PATH6))return cachedConfig5={},cachedConfig5;let raw=readFileSync7(CONFIG_PATH6,"utf-8");try{return cachedConfig5=JSON.parse(raw),cachedConfig5}catch(err){
|
|
284
245
|
let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH6}: ${message}`)}}async function getApiKey3(signal){let key=await resolveCredential({provider:"TinyFish",configuredValue:loadConfig4().tinyfishApiKey,environmentValue:process.env.TINYFISH_API_KEY,signal});if(!key)throw new Error(`TinyFish API key not found. Either:
|
|
285
246
|
1. Create ${CONFIG_PATH6} with { "tinyfishApiKey": "your-key" }
|
|
286
247
|
2. Set TINYFISH_API_KEY environment variable
|
|
@@ -297,7 +258,7 @@ options.numResults),activityId=activityMonitor.logStart({type:"api",query});try{
|
|
|
297
258
|
combined,numResults),response={answer:formatSearchResultsAsAnswer(results),results};if(options.includeContent&&results.length>0){let inlineContent=await fetchInlineContent(results.map(result=>result.url),apiKey,options.signal);inlineContent.length>0&&(response.inlineContent=inlineContent)}return activityMonitor.logComplete(activityId,200),response}catch(err){let message=errorMessage3(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.
|
|
298
259
|
logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}async function extractWithTinyFish(url,signal,options={}){let apiKey=await getApiKey3(signal),activityId=activityMonitor.logStart({type:"fetch",url});try{let data=await fetchBatch([url],apiKey,signal,options);if(!Array.isArray(data.results)||!Array.isArray(data.errors))
|
|
299
260
|
throw new Error("TinyFish Fetch API returned an unexpected response shape");let result=data.results.find(item=>item?.url===url||item?.final_url===url)??data.results[0],mapped=mapFetchResult(result,url);if(mapped)return activityMonitor.logComplete(activityId,200),mapped;let fetchError=findFetchError(data.errors,url);if(fetchError){let status=typeof fetchError.status=="number"?` (HTTP ${fetchError.status})`:"";throw new Error(`TinyFish Fetch failed for ${url}: ${fetchError.error||"unknown error"}${status}`)}
|
|
300
|
-
return activityMonitor.logComplete(activityId,200),null}catch(err){let message=errorMessage3(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as
|
|
261
|
+
return activityMonitor.logComplete(activityId,200),null}catch(err){let message=errorMessage3(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as existsSync9,readFileSync as readFileSync8}from"node:fs";var SEARCH1API_SEARCH_URL="https://api.search1api.com/search",SEARCH1API_CRAWL_URL="https://api.search1api.com/crawl",CONFIG_PATH7=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS3=6e4,CRAWL_TIMEOUT_MS=6e4,cachedConfig6=null;function loadConfig5(){if(cachedConfig6)return cachedConfig6;if(!existsSync9(CONFIG_PATH7))return cachedConfig6={},cachedConfig6;let raw=readFileSync8(CONFIG_PATH7,"utf-8"),parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(
|
|
301
262
|
`Failed to parse ${CONFIG_PATH7}: ${message}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH7}: expected a JSON object`);return cachedConfig6=parsed,cachedConfig6}async function getApiKey4(signal){let key=await resolveCredential({provider:"Search1API",configuredValue:loadConfig5().search1apiApiKey,environmentValue:process.env.SEARCH1API_KEY,signal});if(!key)throw new Error(`Search1API key not found. Either:
|
|
302
263
|
1. Create ${CONFIG_PATH7} with { "search1apiApiKey": "your-key" }
|
|
303
264
|
2. Set SEARCH1API_KEY environment variable
|
|
@@ -310,7 +271,7 @@ trim():""}]})}function mapInlineContent3(results){return Array.isArray(results)?
|
|
|
310
271
|
try{let data=await search1APIJsonRequest("Search",SEARCH1API_SEARCH_URL,apiKey,buildSearchBody(query,options),SEARCH_TIMEOUT_MS3,options.signal),results=mapSearchResults3(data.results),response={answer:formatSearchResultsAsAnswer(results),results};if(options.includeContent){let inlineContent=mapInlineContent3(data.results);inlineContent.length>0&&(response.inlineContent=inlineContent)}return activityMonitor.logComplete(activityId,200),response}catch(err){let message=errorMessage4(err),redactedMessage=redactCredential(
|
|
311
272
|
message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}async function extractWithSearch1API(url,signal,options={}){let apiKey=await getApiKey4(signal),activityId=activityMonitor.logStart({type:"fetch",url});try{let result=(await search1APIJsonRequest(
|
|
312
273
|
"Crawl",SEARCH1API_CRAWL_URL,apiKey,{url},typeof options.timeoutMs=="number"&&Number.isFinite(options.timeoutMs)?Math.max(1,Math.floor(options.timeoutMs)):CRAWL_TIMEOUT_MS,signal)).results;if(!result||typeof result!="object")throw new Error("Search1API Crawl API returned an unexpected response shape");let content=typeof result.content=="string"?result.content.trim():"";return content?(activityMonitor.logComplete(activityId,200),{url,title:typeof result.title=="string"?result.title.trim():"",content,
|
|
313
|
-
error:null}):(activityMonitor.logComplete(activityId,200),null)}catch(err){let message=errorMessage4(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as
|
|
274
|
+
error:null}):(activityMonitor.logComplete(activityId,200),null)}catch(err){let message=errorMessage4(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as existsSync10,readFileSync as readFileSync9}from"node:fs";var QUERIT_SEARCH_URL="https://api.querit.ai/v1/search",QUERIT_CONTENTS_URL="https://api.querit.ai/v1/contents",CONFIG_PATH8=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS4=6e4,CONTENTS_TIMEOUT_MS2=6e4,MAX_CONTENT_URLS=10,cachedConfig7=null;function loadConfig6(){if(cachedConfig7)return cachedConfig7;if(!existsSync10(CONFIG_PATH8))return cachedConfig7={},cachedConfig7;let raw=readFileSync9(CONFIG_PATH8,"utf-8"),parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof Error?err.message:
|
|
314
275
|
String(err);throw new Error(`Failed to parse ${CONFIG_PATH8}: ${message}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH8}: expected a JSON object`);return cachedConfig7=parsed,cachedConfig7}async function getApiKey5(signal){let key=await resolveCredential({provider:"Querit",configuredValue:loadConfig6().queritApiKey,environmentValue:process.env.QUERIT_API_KEY,signal});if(!key)throw new Error(`Querit API key not found. Either:
|
|
315
276
|
1. Create ${CONFIG_PATH8} with { "queritApiKey": "your-key" }
|
|
316
277
|
2. Set QUERIT_API_KEY environment variable
|
|
@@ -328,7 +289,7 @@ let content=[];for(let offset=0;offset<urls.length;offset+=MAX_CONTENT_URLS){let
|
|
|
328
289
|
activityId=activityMonitor.logStart({type:"api",query});try{let data=await queritJsonRequest("Search",QUERIT_SEARCH_URL,apiKey,buildSearchBody2(query,options),SEARCH_TIMEOUT_MS4,options.signal);assertApiSuccess("Search",data);let results=mapSearchResults4(data),response={answer:formatSearchResultsAsAnswer(results),results};if(options.includeContent&&results.length>0){let inlineContent=await fetchInlineContent2(results.map(result=>result.url),apiKey,options.signal);inlineContent.length>0&&(response.
|
|
329
290
|
inlineContent=inlineContent)}return activityMonitor.logComplete(activityId,200),response}catch(err){let message=errorMessage5(err),redactedMessage=redactCredential(message,apiKey);if(options.signal?.aborted?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}async function extractWithQuerit(url,signal,options={}){
|
|
330
291
|
let apiKey=await getApiKey5(signal),activityId=activityMonitor.logStart({type:"fetch",url});try{let data=await fetchContentsBatch([url],apiKey,signal,options),result=findContentResult(data,url,0,1),mapped=mapContentResult(result,url);if(mapped)return activityMonitor.logComplete(activityId,200),mapped;if(failedContentStatus(data,result,0))throw new Error(`Querit Contents API failed to crawl ${url}`);return activityMonitor.logComplete(activityId,200),null}catch(err){let message=errorMessage5(err),
|
|
331
|
-
redactedMessage=redactCredential(message,apiKey);if(signal?.aborted?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as
|
|
292
|
+
redactedMessage=redactCredential(message,apiKey);if(signal?.aborted?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as existsSync11,readFileSync as readFileSync10}from"node:fs";var TABSTACK_RESEARCH_URL="https://api.tabstack.ai/v1/research",TABSTACK_EXTRACT_URL="https://api.tabstack.ai/v1/extract/markdown",CONFIG_PATH9=getWebSearchConfigPath(),RESEARCH_MODES=["fast","balanced"],RESEARCH_TIMEOUT_MS={fast:12e4,balanced:3e5},EXTRACT_TIMEOUT_MS=9e4,cachedConfig8=null;function loadConfig7(){if(cachedConfig8)return cachedConfig8;if(!existsSync11(CONFIG_PATH9))return cachedConfig8={},cachedConfig8;let parsed;try{parsed=JSON.parse(readFileSync10(CONFIG_PATH9,"utf-8"))}catch{throw new Error(
|
|
332
293
|
`Failed to parse ${CONFIG_PATH9}: expected valid JSON`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH9}: expected a JSON object`);return cachedConfig8=parsed,cachedConfig8}async function getApiKey6(signal){let key=await resolveCredential({provider:"Tabstack",configuredValue:loadConfig7().tabstackApiKey,environmentValue:process.env.TABSTACK_API_KEY,signal});if(!key)throw new Error(`Tabstack API key not found. Either:
|
|
333
294
|
1. Create ${CONFIG_PATH9} with { "tabstackApiKey": "your-key" }
|
|
334
295
|
2. Set TABSTACK_API_KEY environment variable
|
|
@@ -345,7 +306,7 @@ ype":"application/json"},body:JSON.stringify(body),signal:requestSignal7(signal,
|
|
|
345
306
|
answer:complete.report.trim(),results:mapCitedPages(complete.metadata?.citedPages)};return activityMonitor.logComplete(activityId,200),response}catch(err){let message=errorMessage6(err),redactedMessage=redactCredential(message,apiKey);if(options.signal?.aborted?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}
|
|
346
307
|
function normalizeTimeoutMs2(value){return typeof value!="number"||!Number.isFinite(value)?EXTRACT_TIMEOUT_MS:Math.max(1,Math.floor(value))}async function extractWithTabstack(url,signal,options={}){let apiKey=await getApiKey6(signal),activityId=activityMonitor.logStart({type:"fetch",url});try{let raw=await tabstackRequest("Extract",TABSTACK_EXTRACT_URL,apiKey,{url,metadata:!0},"application/json",normalizeTimeoutMs2(options.timeoutMs),signal),data;try{data=JSON.parse(raw)}catch(err){throw new Error(
|
|
347
308
|
`Tabstack Extract API returned invalid JSON: ${errorMessage6(err)}`)}if(!data||typeof data!="object"||typeof data.content!="string")throw new Error("Tabstack Extract API returned an unexpected response shape");activityMonitor.logComplete(activityId,200);let content=data.content.trim();if(!content)return null;let title=data.metadata&&typeof data.metadata.title=="string"?data.metadata.title.trim():"";return{url,title,content,error:null}}catch(err){let message=errorMessage6(err),redactedMessage=redactCredential(
|
|
348
|
-
message,apiKey);if(signal?.aborted?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as
|
|
309
|
+
message,apiKey);if(signal?.aborted?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}import{existsSync as existsSync12,readFileSync as readFileSync11}from"node:fs";var CONFIG_PATH10=getWebSearchConfigPath(),DEFAULT_API_VERSION="v2",EXTRACT_TIMEOUT_MS2=6e4,SEARCH_TIMEOUT_MS5=6e4,DEFAULT_MAX_REDIRECTS2=5,REDIRECT_STATUSES2=new Set([301,302,303,307,308]),SUPPORTED_API_VERSIONS=["v1","v2"],cachedConfig9=null;function loadConfig8(){if(cachedConfig9)return cachedConfig9;if(!existsSync12(CONFIG_PATH10))return cachedConfig9={},cachedConfig9;let raw=readFileSync11(CONFIG_PATH10,"utf8"),parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof Error?err.
|
|
349
310
|
message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH10}: ${message}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH10}: expected a JSON object`);return cachedConfig9=parsed,cachedConfig9}function normalizeBaseUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();if(!trimmed)return null;let parsed;try{parsed=new URL(trimmed)}catch{throw new Error(`Invalid Firecrawl base URL in ${CONFIG_PATH10}: expected an HTTP or HTTPS URL`)}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:")throw new Error(`Invalid Firecrawl base URL in ${CONFIG_PATH10}: expected an HTTP or HTTPS URL`);if(parsed.username||parsed.password)throw new Error(`Invalid Firecrawl base URL in ${CONFIG_PATH10}\
|
|
350
311
|
: URL credentials are not allowed`);return parsed.pathname=parsed.pathname.replace(/\/+$/,""),parsed.search="",parsed.hash="",parsed.toString().replace(/\/+$/,"")}function getBaseUrl(){return normalizeBaseUrl(process.env.FIRECRAWL_BASE_URL)??normalizeBaseUrl(loadConfig8().firecrawlBaseUrl)}function requireBaseUrl(){let baseUrl=getBaseUrl();if(!baseUrl)throw new Error(`Firecrawl base URL not configured. Either:
|
|
351
312
|
1. Set firecrawlBaseUrl in ${CONFIG_PATH10}
|
|
@@ -361,7 +322,7 @@ err)}function isAbortError(err){return errorMessage7(err).toLowerCase().includes
|
|
|
361
322
|
Authorization,delete next.authorization,delete next.Cookie,delete next.cookie,delete next["X-API-Key"],delete next["x-api-key"],next}async function fetchFirecrawlApi(url,init,options){let allowLoopback=isLoopbackHostname(new URL(url).hostname),current=await validateRemoteUrl(url,firecrawlApiSsrfOptions(options,allowLoopback)),headers=init.headers;for(let redirects=0;redirects<=DEFAULT_MAX_REDIRECTS2;redirects++){let response=await fetch(current,{...init,headers,redirect:"manual"});if(!REDIRECT_STATUSES2.
|
|
362
323
|
has(response.status))return response;let location=response.headers.get("location");if(!location)return response;if(redirects===DEFAULT_MAX_REDIRECTS2)throw new Error(`Too many redirects fetching ${current.toString()}`);let next=await validateRemoteUrl(new URL(location,current),firecrawlApiSsrfOptions(options,allowLoopback));next.origin!==current.origin&&(headers=withoutSensitiveHeaders(headers)),current=next}throw new Error(`Too many redirects fetching ${current.toString()}`)}function scrapeBody(url){
|
|
363
324
|
return{url,formats:["markdown"],onlyMainContent:!0,...allowFreshScrape()?{}:{lockdown:!0},...pdfParserOptions()}}function parseDomainFilter(domainFilter){let filters={include:[],exclude:[]};for(let raw of domainFilter??[]){let domain=normalizeDomain(raw);if(!domain)continue;let target=raw.trim().startsWith("-")?filters.exclude:filters.include;target.includes(domain)||target.push(domain)}return filters}function passesDomainFilters(url,filters){if(filters.include.length===0&&filters.exclude.length===
|
|
364
|
-
0)return!0;let
|
|
325
|
+
0)return!0;let hostname;try{hostname=new URL(url).hostname.toLowerCase()}catch{return!1}let matches=domain=>hostname===domain||hostname.endsWith(`.${domain}`);return filters.exclude.some(matches)?!1:filters.include.length===0||filters.include.some(matches)}function mapRecencyFilter2(value){switch(value){case"day":return"qdr:d";case"week":return"qdr:w";case"month":return"qdr:m";case"year":return"qdr:y";default:return}}function searchBody(query,options,numResults,filters){let parserOptions=pdfParserOptions();
|
|
365
326
|
return{query,limit:numResults,sources:["web"],...filters.include.length>0?{includeDomains:filters.include}:{},...filters.include.length===0&&filters.exclude.length>0?{excludeDomains:filters.exclude}:{},...mapRecencyFilter2(options.recencyFilter)?{tbs:mapRecencyFilter2(options.recencyFilter)}:{},...options.includeContent?{scrapeOptions:{formats:["markdown"],onlyMainContent:!0,...allowFreshScrape()?{}:{lockdown:!0},...parserOptions}}:{}}}function firstString(...values){for(let value of values)if(typeof value==
|
|
366
327
|
"string"&&value.trim())return value.trim();return null}function mapSearchResults5(data,numResults,filters){let web=Array.isArray(data)?data:data&&typeof data=="object"?data.web:void 0;if(!Array.isArray(web))throw new Error("Firecrawl search returned an unexpected web result shape");let results=[],inlineContent=[],seen=new Set;for(let rawItem of web){if(!rawItem||typeof rawItem!="object"||Array.isArray(rawItem))continue;let item=rawItem,url=firstString(item.url,item.metadata?.sourceURL,item.metadata?.
|
|
367
328
|
url);if(!url||seen.has(url)||!passesDomainFilters(url,filters))continue;seen.add(url);let title=firstString(item.title,item.metadata?.title)??url,snippet=firstString(item.description,item.snippet,item.metadata?.description)??"";results.push({title,url,snippet});let markdown=firstString(item.markdown);if(markdown&&inlineContent.push({url,title,content:withPdfTruncationNotice(markdown,item.metadata),error:null}),results.length>=numResults)break}return{results,inlineContent}}async function firecrawlFetch(endpoint,body,signal,options,label=endpoint,activity=void 0){
|
|
@@ -370,7 +331,7 @@ ok){let text2=await response.text().catch(()=>"");throw new Error(`Firecrawl ${l
|
|
|
370
331
|
"string"&&envelope.error.trim()?envelope.error:"unknown error";throw new Error(`Firecrawl ${label} unsuccessful: ${redactCredential(reason,apiKey)}`)}if(envelope.success!==!0)throw new Error(`Firecrawl ${label} returned an unexpected response shape`);return activityMonitor.logComplete(activityId,response.status),envelope}catch(err){throw isAbortError(err)?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,errorMessage7(err)),err}}function isFirecrawlAvailable(){return getBaseUrl()!==
|
|
371
332
|
null}async function searchWithFirecrawl(query,options={}){requireBaseUrl();let numResults=normalizeSearchResultCount(options.numResults),filters=parseDomainFilter(options.domainFilter),envelope=await firecrawlFetch("search",searchBody(query,options,numResults,filters),options.signal,{...options,timeoutMs:options.timeoutMs??SEARCH_TIMEOUT_MS5},"search",{type:"api",query}),mapped=mapSearchResults5(envelope.data,numResults,filters),response={answer:formatSearchResultsAsAnswer(mapped.results),results:mapped.
|
|
372
333
|
results};return options.includeContent&&mapped.inlineContent.length>0&&(response.inlineContent=mapped.inlineContent),response}async function extractWithFirecrawl(url,signal,options){requireBaseUrl(),await validateRemoteUrl(url,ssrfOptions(options));let data=(await firecrawlFetch("scrape",scrapeBody(url),signal,options)).data;if(!data||typeof data!="object"||Array.isArray(data))throw new Error("Firecrawl scrape returned an unexpected data shape");let scrape=data;if(typeof scrape.markdown!="string")
|
|
373
|
-
throw new Error("Firecrawl scrape returned markdown in an unexpected shape");let content=scrape.markdown.trim();if(!content)return null;let metadataTitle=scrape.metadata?.title,title=typeof metadataTitle=="string"&&metadataTitle.trim()?metadataTitle.trim():typeof scrape.title=="string"?scrape.title.trim():"";return{url,title,content:withPdfTruncationNotice(content,scrape.metadata),error:null}}import{existsSync as
|
|
334
|
+
throw new Error("Firecrawl scrape returned markdown in an unexpected shape");let content=scrape.markdown.trim();if(!content)return null;let metadataTitle=scrape.metadata?.title,title=typeof metadataTitle=="string"&&metadataTitle.trim()?metadataTitle.trim():typeof scrape.title=="string"?scrape.title.trim():"";return{url,title,content:withPdfTruncationNotice(content,scrape.metadata),error:null}}import{existsSync as existsSync13,readFileSync as readFileSync12}from"node:fs";var KAGI_SEARCH_URL="https://kagi.com/api/v1/search",KAGI_EXTRACT_URL="https://kagi.com/api/v1/extract",CONFIG_PATH11=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS6=6e4,cachedConfig10=null;function loadConfig9(){if(cachedConfig10)return cachedConfig10;if(!existsSync13(CONFIG_PATH11))return cachedConfig10={},cachedConfig10;let raw=readFileSync12(CONFIG_PATH11,"utf-8"),parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to pars\
|
|
374
335
|
e ${CONFIG_PATH11}: ${message}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH11}: expected a JSON object`);return cachedConfig10=parsed,cachedConfig10}async function getApiKey8(signal){return resolveCredential({provider:"Kagi",configuredValue:loadConfig9().kagiApiKey,environmentValue:process.env.KAGI_API_KEY,signal})}async function requireApiKey(signal){let apiKey=await getApiKey8(signal);if(!apiKey)throw new Error(`Kagi API key not \
|
|
375
336
|
found. Either:
|
|
376
337
|
1. Create ${CONFIG_PATH11} with { "kagiApiKey": "your-key" }
|
|
@@ -388,7 +349,7 @@ return mapped}function isKagiExtractAvailable(){return isKagiAvailable()}async f
|
|
|
388
349
|
await fetchRemoteUrl(resolveProviderApiUrl("kagi",KAGI_EXTRACT_URL,loadConfig9().kagiBaseUrl),{method:"POST",headers:{Authorization:`Bearer ${apiKey}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({pages:[{url}]}),signal:signal?AbortSignal.any([AbortSignal.timeout(options.timeoutMs??SEARCH_TIMEOUT_MS6),signal]):AbortSignal.timeout(options.timeoutMs??SEARCH_TIMEOUT_MS6)},{allowRanges:ssrf.allowRanges,trustEnvProxy:ssrf.trustEnvProxy,onRedirect:({from,to,init})=>to.
|
|
389
350
|
origin===from.origin?init:{...init,headers:{"Content-Type":"application/json",Accept:"application/json"}},...options.lookup?{lookup:options.lookup}:{}})}catch(err){let message=errorMessage8(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.
|
|
390
351
|
name=err.name),redactedError}if(!response.ok){activityMonitor.logComplete(activityId,response.status);let errorText=redactCredential(await response.text(),apiKey);throw new Error(`Kagi Extract API error ${response.status}: ${errorText.slice(0,300)}`)}let rawData;try{rawData=await response.json()}catch(err){throw activityMonitor.logComplete(activityId,response.status),new Error(`Kagi Extract API returned invalid JSON: ${errorMessage8(err)}`)}let parsed=parseExtractResponse(rawData,url);return activityMonitor.
|
|
391
|
-
logComplete(activityId,response.status),parsed}import{existsSync as
|
|
352
|
+
logComplete(activityId,response.status),parsed}import{existsSync as existsSync14,readFileSync as readFileSync13}from"node:fs";var OLLAMA_SEARCH_URL="https://ollama.com/api/web_search",OLLAMA_FETCH_URL="https://ollama.com/api/web_fetch",CONFIG_PATH12=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS7=6e4,cachedConfig11=null;function loadConfig10(){if(cachedConfig11)return cachedConfig11;if(!existsSync14(CONFIG_PATH12))return cachedConfig11={},cachedConfig11;let raw=readFileSync13(CONFIG_PATH12,"utf-8"),parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed \
|
|
392
353
|
to parse ${CONFIG_PATH12}: ${message}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH12}: expected a JSON object`);return cachedConfig11=parsed,cachedConfig11}async function getApiKey9(signal){return resolveCredential({provider:"Ollama",configuredValue:loadConfig10().ollamaApiKey,environmentValue:process.env.OLLAMA_API_KEY,signal})}async function requireApiKey2(signal){let apiKey=await getApiKey9(signal);if(!apiKey)throw new Error(`Ol\
|
|
393
354
|
lama API key not found. Either:
|
|
394
355
|
1. Create ${CONFIG_PATH12} with { "ollamaApiKey": "your-key" }
|
|
@@ -404,44 +365,61 @@ includeContent){let inlineContent=data.results.slice(0,numResults).filter(result
|
|
|
404
365
|
{allowRanges:ssrf.allowRanges,trustEnvProxy:ssrf.trustEnvProxy,domainPolicy,...options.lookup?{lookup:options.lookup}:{}});let apiKey=await requireApiKey2(signal),activityId=activityMonitor.logStart({type:"api",query:`ollama fetch: ${url}`}),response;try{response=await fetchRemoteUrl(resolveProviderApiUrl("ollama",OLLAMA_FETCH_URL,loadConfig10().ollamaBaseUrl),{method:"POST",headers:{Authorization:`Bearer ${apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({url}),signal:signal?AbortSignal.
|
|
405
366
|
any([AbortSignal.timeout(options.timeoutMs??SEARCH_TIMEOUT_MS7),signal]):AbortSignal.timeout(options.timeoutMs??SEARCH_TIMEOUT_MS7)},{allowRanges:ssrf.allowRanges,trustEnvProxy:ssrf.trustEnvProxy,onRedirect:({from,to,init})=>to.origin===from.origin?init:{...init,headers:{"Content-Type":"application/json"}},...options.lookup?{lookup:options.lookup}:{}})}catch(err){let message=errorMessage9(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.
|
|
406
367
|
logComplete(activityId,0):activityMonitor.logError(activityId,redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}if(!response.ok){activityMonitor.logComplete(activityId,response.status);let errorText=redactCredential(await response.text(),apiKey);throw new Error(`Ollama Web Fetch error ${response.status}: ${errorText.slice(0,300)}`)}let rawData;try{rawData=await response.json()}catch(err){
|
|
407
|
-
throw activityMonitor.logComplete(activityId,response.status),new Error(`Ollama Web Fetch returned invalid JSON: ${errorMessage9(err)}`)}let data=parseFetchResponse(rawData);activityMonitor.logComplete(activityId,response.status);let content=data.content.trim();return content?{url,title:data.title,content,error:null}:null}import{existsSync as
|
|
408
|
-
|
|
368
|
+
throw activityMonitor.logComplete(activityId,response.status),new Error(`Ollama Web Fetch returned invalid JSON: ${errorMessage9(err)}`)}let data=parseFetchResponse(rawData);activityMonitor.logComplete(activityId,response.status);let content=data.content.trim();return content?{url,title:data.title,content,error:null}:null}import{existsSync as existsSync15,readFileSync as readFileSync14}from"node:fs";var SPECSTREAM_SEARCH_URL="https://api.specstream.ai/v1/web-search",SPECSTREAM_EXTRACT_URL="https://api.specstream.ai/v1/extract",CONFIG_PATH13=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS8=6e4,EXTRACT_TIMEOUT_MS3=6e4,MAX_QUERY_CHARS=2e3,cachedConfig12=null;function loadConfig11(){if(cachedConfig12)return cachedConfig12;if(!existsSync15(CONFIG_PATH13))return cachedConfig12={},cachedConfig12;let raw=readFileSync14(CONFIG_PATH13,"utf-8"),parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof
|
|
369
|
+
Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH13}: ${message}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH13}: expected a JSON object`);return cachedConfig12=parsed,cachedConfig12}async function getApiKey10(signal){return resolveCredential({provider:"SpecStream",configuredValue:loadConfig11().specstreamApiKey,environmentValue:process.env.SPECSTREAM_API_KEY,signal})}async function requireApiKey3(signal){
|
|
370
|
+
let apiKey=await getApiKey10(signal);if(!apiKey)throw new Error(`SpecStream API key not found. Either:
|
|
371
|
+
1. Create ${CONFIG_PATH13} with { "specstreamApiKey": "your-key" }
|
|
372
|
+
2. Set SPECSTREAM_API_KEY environment variable
|
|
373
|
+
Get a key at https://specstream.ai`);return apiKey}function parseDomainFilter2(domainFilter){let filters={include:[],exclude:[]};for(let raw of domainFilter??[]){let domain=normalizeDomain(raw);if(!domain)continue;let target=raw.trim().startsWith("-")?filters.exclude:filters.include;target.includes(domain)||target.push(domain)}return filters}function passesDomainFilters2(url,filters){if(filters.include.length===0&&filters.exclude.length===0)return!0;let hostname=url.hostname.toLowerCase(),matches=domain=>hostname===
|
|
374
|
+
domain||hostname.endsWith(`.${domain}`);return filters.exclude.some(matches)?!1:filters.include.length===0||filters.include.some(matches)}function errorMessage10(err){return err instanceof Error?err.message:String(err)}function invalidResponse3(message){return new Error(`SpecStream returned invalid response: ${message}`)}function redactError(err,apiKey){let message=errorMessage10(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage===message&&err instanceof Error)return err;let redactedError=new Error(
|
|
375
|
+
redactedMessage);return err instanceof Error&&(redactedError.name=err.name),redactedError}async function readJson(response){try{return await response.json()}catch(err){throw err instanceof SyntaxError?new Error(`SpecStream returned invalid JSON: ${errorMessage10(err)}`):err}}function unwrapEnvelope(value){if(!value||typeof value!="object"||Array.isArray(value))throw invalidResponse3("expected an object envelope");let envelope=value,data=envelope.data;if(data&&typeof data=="object"&&!Array.isArray(
|
|
376
|
+
data))return data;let error=envelope.error;if(data===null&&error&&typeof error=="object"){let message=error.message;throw new Error(`SpecStream error: ${typeof message=="string"&&message?message:"request failed"}`)}return envelope}function parseSearchResponse3(value){let data=unwrapEnvelope(value);if(!Array.isArray(data.sources))throw invalidResponse3("expected sources array");return data.sources}function parseExtractResponse2(value){let data=unwrapEnvelope(value);if(!Array.isArray(data.results))
|
|
377
|
+
throw invalidResponse3("expected results array");return data.results}function isSpecStreamAvailable(){return hasCredentialSource({provider:"SpecStream",configuredValue:loadConfig11().specstreamApiKey,environmentValue:process.env.SPECSTREAM_API_KEY})}async function searchWithSpecStream(query,options={}){let apiKey=await requireApiKey3(options.signal),numResults=normalizeSearchResultCount(options.numResults),filters=parseDomainFilter2(options.domainFilter),endpoint=new URL(resolveProviderApiUrl("s\
|
|
378
|
+
pecstream",SPECSTREAM_SEARCH_URL,loadConfig11().specstreamBaseUrl));endpoint.searchParams.set("q",query.slice(0,MAX_QUERY_CHARS));let activityId=activityMonitor.logStart({type:"api",query}),timeoutSignal=AbortSignal.timeout(SEARCH_TIMEOUT_MS8),response,entries;try{if(response=await fetchWithCredentialRedirects(endpoint.toString(),{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${apiKey}`,"User-Agent":"pi-web-access"},signal:options.signal?AbortSignal.any([timeoutSignal,options.
|
|
379
|
+
signal]):timeoutSignal},["Authorization"]),!response.ok){let errorText=await response.text();throw new Error(`SpecStream error ${response.status}: ${redactCredential(errorText,apiKey).slice(0,300)}`)}entries=parseSearchResponse3(await readJson(response))}catch(err){if(options.signal?.aborted)throw activityMonitor.logComplete(activityId,0),new Error("Aborted");let outgoing=timeoutSignal.aborted||err instanceof Error&&err.name==="TimeoutError"?new Error(`SpecStream request timed out after ${Math.round(
|
|
380
|
+
SEARCH_TIMEOUT_MS8/1e3)}s`):redactError(err,apiKey);throw activityMonitor.logError(activityId,redactCredential(errorMessage10(outgoing),apiKey)),outgoing}activityMonitor.logComplete(activityId,response.status);let results=[];for(let entry of entries){if(!entry||typeof entry!="object"||typeof entry.url!="string"||!entry.url)continue;let resultUrl;try{resultUrl=new URL(entry.url)}catch{continue}if(!(resultUrl.protocol!=="http:"&&resultUrl.protocol!=="https:")&&passesDomainFilters2(resultUrl,filters)&&
|
|
381
|
+
(results.push({title:typeof entry.title=="string"&&entry.title.trim()?entry.title.trim():`Source ${results.length+1}`,url:resultUrl.href,snippet:typeof entry.snippet=="string"?entry.snippet:""}),results.length>=numResults))break}return{answer:formatSearchResultsAsAnswer(results),results}}async function extractWithSpecStream(url,signal,options={}){let apiKey=await requireApiKey3(signal),timeoutMs=typeof options.timeoutMs=="number"&&Number.isFinite(options.timeoutMs)?Math.max(1,Math.floor(options.
|
|
382
|
+
timeoutMs)):EXTRACT_TIMEOUT_MS3,activityId=activityMonitor.logStart({type:"fetch",url}),timeoutSignal=AbortSignal.timeout(timeoutMs);try{let response=await fetchWithCredentialRedirects(resolveProviderApiUrl("specstream",SPECSTREAM_EXTRACT_URL,loadConfig11().specstreamBaseUrl),{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${apiKey}`,"Content-Type":"application/json","User-Agent":"pi-web-access"},body:JSON.stringify({urls:[url],format:"markdown"}),signal:signal?AbortSignal.
|
|
383
|
+
any([timeoutSignal,signal]):timeoutSignal},["Authorization"]);if(!response.ok){let errorText=await response.text();throw new Error(`SpecStream Extract error ${response.status}: ${redactCredential(errorText,apiKey).slice(0,300)}`)}let[result]=parseExtractResponse2(await readJson(response));if(!result||typeof result!="object")throw invalidResponse3("expected one result for the URL");if(activityMonitor.logComplete(activityId,response.status),result.status!=="ok"){if(result.status==="failed"||result.
|
|
384
|
+
status==="blocked")throw new Error(`SpecStream Extract could not read the page: ${String(result.status)}`);return null}let content=typeof result.text=="string"?result.text.trim():"";return content?{url,title:typeof result.title=="string"?result.title.trim():"",content,error:null}:null}catch(err){if(signal?.aborted)throw activityMonitor.logComplete(activityId,0),err;let outgoing=timeoutSignal.aborted?new Error(`SpecStream Extract request timed out after ${Math.round(timeoutMs/1e3)}s`):redactError(
|
|
385
|
+
err,apiKey);throw activityMonitor.logError(activityId,redactCredential(errorMessage10(outgoing),apiKey)),outgoing}}import{existsSync as existsSync16,readFileSync as readFileSync15}from"node:fs";var DEEPSEEK_SEARCH_URL="https://api.deepseek.com/v1/tools/search",DEEPSEEK_FETCH_URL="https://api.deepseek.com/v1/tools/fetch",CONFIG_PATH14=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS9=3e4,FETCH_TIMEOUT_MS2=6e4,MAX_QUERY_CHARS2=128,MAX_SNIPPET_CHARS=800,RECENCY_DAYS={day:1,week:7,month:30,year:365},cachedConfig13=null;function loadConfig12(){if(cachedConfig13)return cachedConfig13;if(!existsSync16(CONFIG_PATH14))return cachedConfig13={},cachedConfig13;let raw=readFileSync15(CONFIG_PATH14,"utf-8"),
|
|
386
|
+
parsed;try{parsed=JSON.parse(raw)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH14}: ${message}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error(`Invalid config in ${CONFIG_PATH14}: expected a JSON object`);return cachedConfig13=parsed,cachedConfig13}async function requireApiKey4(signal){let apiKey=await resolveCredential({provider:"DeepSeek",configuredValue:loadConfig12().deepseekApiKey,environmentValue:process.
|
|
409
387
|
env.DEEPSEEK_API_KEY,signal});if(!apiKey)throw new Error(`DeepSeek API key not found. Either:
|
|
410
|
-
1. Create ${
|
|
388
|
+
1. Create ${CONFIG_PATH14} with { "deepseekApiKey": "your-key" }
|
|
411
389
|
2. Set DEEPSEEK_API_KEY environment variable
|
|
412
390
|
Get a key at https://platform.deepseek.com/api_keys`);return apiKey}function buildQuery(query,options){let include=[],exclude=[];for(let raw of options.domainFilter??[]){let domain=normalizeDomain(raw);if(!domain)continue;let target=raw.trim().startsWith("-")?exclude:include;target.includes(domain)||target.push(domain)}let parts=[query.trim()];include.length>0&&parts.push(include.map(domain=>`site:${domain}`).join(" OR "));for(let domain of exclude)parts.push(`-site:${domain}`);if(options.recencyFilter){
|
|
413
|
-
let after=new Date(Date.now()-RECENCY_DAYS[options.recencyFilter]*864e5).toISOString().slice(0,10);parts.push(`after:${after}`)}let built=parts.join(" "),length=[...built].length;if(length>
|
|
391
|
+
let after=new Date(Date.now()-RECENCY_DAYS[options.recencyFilter]*864e5).toISOString().slice(0,10);parts.push(`after:${after}`)}let built=parts.join(" "),length=[...built].length;if(length>MAX_QUERY_CHARS2)throw new Error(`DeepSeek invalid request: the query is ${length} characters with domain and date filters; DeepSeek accepts at most ${MAX_QUERY_CHARS2}`);return built}function text(value){return typeof value=="string"?value.replace(/\s+/g," ").trim():""}function errorMessage11(err){return err instanceof
|
|
414
392
|
Error?err.message:String(err)}function unescapeMarkdownSegment(segment){return segment.replace(/\\([/.,:()&+#>|!_\-"'])/g,(match,char,offset,whole)=>char==="!"&&whole[offset+2]==="["?match:char)}function normalizeInlineMarkdown(line){return line.split(/(`+[^`]*`+)/g).map((part,index)=>index%2===0?unescapeMarkdownSegment(part):part).join("")}function normalizeDeepSeekMarkdown(markdown){let fence=null;return markdown.split(`
|
|
415
393
|
`).map(line=>{let match=line.match(/^\s{0,3}(`{3,}|~{3,})/);if(match){let marker=match[1];return fence===null?fence={char:marker[0],length:marker.length}:marker[0]===fence.char&&marker.length>=fence.length&&line.slice(match[0].length).trim()===""&&(fence=null),line}return fence===null?normalizeInlineMarkdown(line):line}).join(`
|
|
416
394
|
`)}var ERROR_TITLE=/^(?:404\b|page not found\b|not found\b)/i;function firstMarkdownHeading(content){let fence=null;for(let line of content.split(`
|
|
417
395
|
`)){let fenceMatch=line.match(/^\s{0,3}(`{3,}|~{3,})/);if(fenceMatch){let marker=fenceMatch[1];fence===null?fence={char:marker[0],length:marker.length}:marker[0]===fence.char&&marker.length>=fence.length&&line.slice(fenceMatch[0].length).trim()===""&&(fence=null);continue}if(fence!==null)continue;let heading=line.match(/^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$/);if(heading)return heading[1].trim()}return""}function isUnusableDeepSeekPage(title,content){if(content.length>=500)return!1;let heading=firstMarkdownHeading(
|
|
418
396
|
content);return heading!==""&&ERROR_TITLE.test(heading)?!0:ERROR_TITLE.test(text(title))&&/\b(?:404|page not found|not found)\b/i.test(content.slice(0,200))}function parseResponse(value){let results=value&&typeof value=="object"&&!Array.isArray(value)?value.results:void 0;if(!Array.isArray(results))throw new Error("DeepSeek returned invalid response: expected a results array");return results}function describeError(body){try{let error=JSON.parse(body).error,message=text(error?.message);if(message)
|
|
419
|
-
return message}catch{}return body}function isDeepSeekAvailable(){return hasCredentialSource({provider:"DeepSeek",configuredValue:
|
|
420
|
-
response,entries;try{if(response=await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek",DEEPSEEK_SEARCH_URL,
|
|
421
|
-
describeError(await response.text()),apiKey).slice(0,300);throw new Error(`DeepSeek error ${response.status}: ${errorText}`)}let rawData;try{rawData=await response.json()}catch(err){throw err instanceof Error&&err.name==="TimeoutError"?err:new Error(`DeepSeek returned invalid JSON: ${
|
|
422
|
-
aborted||err instanceof Error&&err.name==="TimeoutError"?new Error(`DeepSeek request timed out after ${Math.round(
|
|
397
|
+
return message}catch{}return body}function isDeepSeekAvailable(){return hasCredentialSource({provider:"DeepSeek",configuredValue:loadConfig12().deepseekApiKey,environmentValue:process.env.DEEPSEEK_API_KEY})}async function searchWithDeepSeek(query,options={}){let builtQuery=buildQuery(query,options),apiKey=await requireApiKey4(options.signal),numResults=normalizeSearchResultCount(options.numResults),activityId=activityMonitor.logStart({type:"api",query}),timeoutSignal=AbortSignal.timeout(SEARCH_TIMEOUT_MS9),
|
|
398
|
+
response,entries;try{if(response=await fetchWithCredentialRedirects(resolveProviderApiUrl("deepseek",DEEPSEEK_SEARCH_URL,loadConfig12().deepseekBaseUrl),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${apiKey}`},body:JSON.stringify({query:builtQuery,count:numResults,...options.includeContent?{need_content:!0}:{}}),signal:options.signal?AbortSignal.any([timeoutSignal,options.signal]):timeoutSignal},["Authorization"]),!response.ok){let errorText=redactCredential(
|
|
399
|
+
describeError(await response.text()),apiKey).slice(0,300);throw new Error(`DeepSeek error ${response.status}: ${errorText}`)}let rawData;try{rawData=await response.json()}catch(err){throw err instanceof Error&&err.name==="TimeoutError"?err:new Error(`DeepSeek returned invalid JSON: ${errorMessage11(err)}`)}entries=parseResponse(rawData)}catch(err){if(options.signal?.aborted)throw activityMonitor.logComplete(activityId,0),new Error("Aborted");let message=errorMessage11(err),outgoing=timeoutSignal.
|
|
400
|
+
aborted||err instanceof Error&&err.name==="TimeoutError"?new Error(`DeepSeek request timed out after ${Math.round(SEARCH_TIMEOUT_MS9/1e3)}s`):(()=>{let redactedMessage=redactCredential(message,apiKey);if(redactedMessage===message&&err instanceof Error)return err;let redactedError=new Error(redactedMessage);return err instanceof Error&&(redactedError.name=err.name),redactedError})();throw activityMonitor.logError(activityId,redactCredential(errorMessage11(outgoing),apiKey)),outgoing}activityMonitor.
|
|
423
401
|
logComplete(activityId,response.status);let results=[],inlineContent=[],seen=new Set;for(let entry of entries){if(!entry||typeof entry!="object"||typeof entry.url!="string"||!entry.url)continue;let resultUrl;try{resultUrl=new URL(entry.url)}catch{continue}if(resultUrl.protocol!=="http:"&&resultUrl.protocol!=="https:"||seen.has(resultUrl.href))continue;seen.add(resultUrl.href);let title=text(entry.title)||`Source ${results.length+1}`;if(results.push({title,url:resultUrl.href,snippet:(text(entry.summary)||
|
|
424
402
|
text(entry.snippet)).slice(0,MAX_SNIPPET_CHARS)}),options.includeContent){let content=typeof entry.content=="string"?entry.content.trim():"";content&&inlineContent.push({url:resultUrl.href,title,content,error:null})}if(results.length>=numResults)break}if(entries.length>0&&results.length===0)throw new Error("DeepSeek returned invalid response: no result had an http(s) URL");let searchResponse={answer:formatSearchResultsAsAnswer(results),results};return inlineContent.length>0&&(searchResponse.inlineContent=
|
|
425
|
-
inlineContent),searchResponse}async function extractWithDeepSeek(url,signal,options={}){let apiKey=await
|
|
426
|
-
resolveProviderApiUrl("deepseek",DEEPSEEK_FETCH_URL,
|
|
427
|
-
try{rawData=await response.json()}catch(err){throw err instanceof Error&&err.name==="TimeoutError"?err:new Error(`DeepSeek Fetch returned invalid JSON: ${
|
|
428
|
-
title,content)?(activityMonitor.logComplete(activityId,response.status),null):(activityMonitor.logComplete(activityId,response.status),{url,title,content,error:null})}catch(err){let message=
|
|
403
|
+
inlineContent),searchResponse}async function extractWithDeepSeek(url,signal,options={}){let apiKey=await requireApiKey4(signal),activityId=activityMonitor.logStart({type:"fetch",url}),timeoutMs=options.timeoutMs??FETCH_TIMEOUT_MS2,timeoutSignal=AbortSignal.timeout(timeoutMs);try{let ssrf=loadSsrfConfig();await validateRemoteUrl(url,{allowRanges:ssrf.allowRanges,trustEnvProxy:ssrf.trustEnvProxy,domainPolicy:loadFetchContentDomainPolicy(),...options.lookup?{lookup:options.lookup}:{}});let response=await fetchWithCredentialRedirects(
|
|
404
|
+
resolveProviderApiUrl("deepseek",DEEPSEEK_FETCH_URL,loadConfig12().deepseekBaseUrl),{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${apiKey}`},body:JSON.stringify({url}),signal:signal?AbortSignal.any([timeoutSignal,signal]):timeoutSignal},["Authorization"]);if(!response.ok){let errorText=redactCredential(describeError(await response.text()),apiKey).slice(0,300);throw new Error(`DeepSeek Fetch error ${response.status}: ${errorText}`)}let rawData;
|
|
405
|
+
try{rawData=await response.json()}catch(err){throw err instanceof Error&&err.name==="TimeoutError"?err:new Error(`DeepSeek Fetch returned invalid JSON: ${errorMessage11(err)}`)}if(!rawData||typeof rawData!="object"||Array.isArray(rawData))throw new Error("DeepSeek Fetch returned an unexpected response shape");let page=rawData,title=typeof page.title=="string"?page.title.trim():"",content=typeof page.content=="string"?normalizeDeepSeekMarkdown(page.content).trim():"";return!content||isUnusableDeepSeekPage(
|
|
406
|
+
title,content)?(activityMonitor.logComplete(activityId,response.status),null):(activityMonitor.logComplete(activityId,response.status),{url,title,content,error:null})}catch(err){let message=errorMessage11(err);if(signal?.aborted)throw activityMonitor.logComplete(activityId,0),new Error("Aborted");if(activityMonitor.logError(activityId,redactCredential(message,apiKey)),err instanceof Error&&err.name==="TimeoutError")throw new Error(`DeepSeek Fetch request timed out after ${Math.round(timeoutMs/1e3)}\
|
|
429
407
|
s`);let redactedMessage=redactCredential(message,apiKey);if(redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}}var Node=class{value;next;constructor(value){this.value=value}},Queue=class{#head;#tail;#size;constructor(){this.clear()}enqueue(value){let node=new Node(value);this.#head?(this.#tail.next=node,this.#tail=node):(this.#head=node,this.#tail=node),this.#size++}dequeue(){let current=this.#head;if(current)return this.#head=this.#head.next,this.#size--,this.#head||(this.#tail=void 0),current.value}peek(){if(this.#head)return this.#head.value}clear(){this.#head=void 0,this.#tail=void 0,this.#size=0}get size(){
|
|
430
408
|
return this.#size}*[Symbol.iterator](){let current=this.#head;for(;current;)yield current.value,current=current.next}*drain(){for(;this.#head;)yield this.dequeue()}};function pLimit(concurrency){let rejectOnClear=!1;if(typeof concurrency=="object"&&({concurrency,rejectOnClear=!1}=concurrency),validateConcurrency(concurrency),typeof rejectOnClear!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let queue=new Queue,activeCount=0,resumeNext=()=>{activeCount<concurrency&&queue.size>0&&(activeCount++,queue.dequeue().run())},next=()=>{activeCount--,resumeNext()},run=async(function_,resolve,arguments_)=>{let result=(async()=>function_(...arguments_))();
|
|
431
409
|
resolve(result);try{await result}catch{}next()},enqueue=(function_,resolve,reject,arguments_)=>{let queueItem={reject};new Promise(internalResolve=>{queueItem.run=internalResolve,queue.enqueue(queueItem)}).then(run.bind(void 0,function_,resolve,arguments_)),activeCount<concurrency&&resumeNext()},generator=(function_,...arguments_)=>new Promise((resolve,reject)=>{enqueue(function_,resolve,reject,arguments_)});return Object.defineProperties(generator,{activeCount:{get:()=>activeCount},pendingCount:{
|
|
432
410
|
get:()=>queue.size},clearQueue:{value(){if(!rejectOnClear){queue.clear();return}let abortError=AbortSignal.abort().reason;for(;queue.size>0;)queue.dequeue().reject(abortError)}},concurrency:{get:()=>concurrency,set(newConcurrency){validateConcurrency(newConcurrency),concurrency=newConcurrency,queueMicrotask(()=>{for(;activeCount<concurrency&&queue.size>0;)resumeNext()})}},map:{async value(iterable,function_){let promises=[];try{Array.from(iterable,(value,index)=>{let promise=generator(function_,
|
|
433
411
|
value,index);return promises.push(promise),promise})}catch(error){for(let promise of promises)promise.catch(()=>{});throw error}return Promise.all(promises)}}}),generator}function validateConcurrency(concurrency){if(!((Number.isInteger(concurrency)||concurrency===Number.POSITIVE_INFINITY)&&concurrency>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up")}import{existsSync as existsSync17,readFileSync as readFileSync16}from"node:fs";var WEB_SEARCH_CONFIG_PATH2=getWebSearchConfigPath(),AUTH_PROFILE_NAME_PATTERN=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function resolveAuthFetchProfile(request){let profiles=loadAuthFetchProfiles();if(profiles.length===0)throw new Error(`auth requires at least one authFetch profile in ${WEB_SEARCH_CONFIG_PATH2}`);if(request===!0){if(profiles.length!==1)throw new Error("auth: true requires exactly one authFetch profile; use a profile name instead");return profiles[0]}let name=request.trim(),profile=profiles.
|
|
434
|
-
find(candidate=>candidate.name===name);if(!profile)throw new Error(`Unknown authFetch profile: ${name}`);return profile}function assertAuthFetchUrl(profile,rawUrl){let url;try{url=new URL(rawUrl)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Authenticated fetch requires an HTTPS URL: ${message}`)}if(url.protocol!=="https:")throw new Error("Authenticated fetch requires an HTTPS URL");let
|
|
435
|
-
|
|
412
|
+
find(candidate=>candidate.name===name);if(!profile)throw new Error(`Unknown authFetch profile: ${name}`);return profile}function assertAuthFetchUrl(profile,rawUrl){let url;try{url=new URL(rawUrl)}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Authenticated fetch requires an HTTPS URL: ${message}`)}if(url.protocol!=="https:")throw new Error("Authenticated fetch requires an HTTPS URL");let hostname=normalizeHostname2(url.hostname);if(!profile.hosts.some(host=>hostMatches(
|
|
413
|
+
hostname,host)))throw new Error(`URL host ${hostname} is not allowed by authFetch profile ${profile.name}`);return url}function authFetchRedirectGuard(profile,from,to){if(profile.redirects==="same-origin"&&to.origin!==from.origin)throw new Error(`Authenticated fetch refused cross-origin redirect: ${from.origin} -> ${to.origin}`)}function loadAuthFetchProfiles(){if(!existsSync17(WEB_SEARCH_CONFIG_PATH2))return[];let raw=readFileSync16(WEB_SEARCH_CONFIG_PATH2,"utf-8"),parsed;try{let value=JSON.parse(
|
|
436
414
|
raw);if(!value||typeof value!="object"||Array.isArray(value))throw new Error("expected a JSON object");parsed=value}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH2}: ${message}`)}if(parsed.authFetch===void 0||parsed.authFetch===null)return[];if(typeof parsed.authFetch!="object"||Array.isArray(parsed.authFetch))throw new Error(`authFetch in ${WEB_SEARCH_CONFIG_PATH2} must be an object`);return Object.entries(parsed.authFetch).
|
|
437
415
|
map(([name,value])=>parseProfile(name,value))}function parseProfile(name,value){if(!AUTH_PROFILE_NAME_PATTERN.test(name))throw new Error(`authFetch profile name ${JSON.stringify(name)} must start with a letter and contain only letters, numbers, underscores, or hyphens`);if(Array.isArray(value))return{name,hosts:parseHosts(value,`authFetch.${name}`),redirects:"same-origin",cache:"session"};if(!value||typeof value!="object")throw new Error(`authFetch.${name} in ${WEB_SEARCH_CONFIG_PATH2} must be a\
|
|
438
416
|
n array of hosts or an object`);let config=value;if(!Array.isArray(config.hosts))throw new Error(`authFetch.${name}.hosts in ${WEB_SEARCH_CONFIG_PATH2} must be a non-empty array of hostnames`);let redirects=config.redirects??"same-origin";if(redirects!=="same-origin")throw new Error(`authFetch.${name}.redirects in ${WEB_SEARCH_CONFIG_PATH2} must be "same-origin"`);let cache=config.cache??"session";if(cache!=="session"&&cache!=="off")throw new Error(`authFetch.${name}.cache in ${WEB_SEARCH_CONFIG_PATH2}\
|
|
439
417
|
must be "session" or "off"`);let chromeProfile=parseChromeProfile(config.chromeProfile,`authFetch.${name}.chromeProfile`);return{name,hosts:parseHosts(config.hosts,`authFetch.${name}.hosts`),...chromeProfile?{chromeProfile}:{},redirects,cache}}function parseHosts(value,label){if(value.length===0)throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH2} must be a non-empty array of hostnames`);let hosts=value.map(entry=>{if(typeof entry!="string")throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH2}\
|
|
440
418
|
must contain only hostnames`);return parseHost(entry,label)});return[...new Set(hosts)]}function parseHost(value,label){let host=normalizeHostname2(value.trim());if(!host||host.startsWith(".")||host.endsWith(".")||/\s|[\\/?:#@*]/.test(host))throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH2} contains an invalid hostname: ${JSON.stringify(value)}`);if(host.length>253||!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(host))throw new Error(`${label} in\
|
|
441
419
|
${WEB_SEARCH_CONFIG_PATH2} contains an invalid hostname: ${JSON.stringify(value)}`);return host}function parseChromeProfile(value,label){if(value==null)return;if(typeof value!="string")throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH2} must be a string`);let normalized=value.trim();if(!normalized||normalized==="."||normalized===".."||normalized.includes("/")||normalized.includes("\\"))throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH2} must be a profile directory name, not a path`);return normalized}
|
|
442
|
-
function normalizeHostname2(
|
|
443
|
-
parse(raw);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("config root must be an object");
|
|
444
|
-
return(
|
|
420
|
+
function normalizeHostname2(hostname){return hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function hostMatches(hostname,allowedHost){return hostname===allowedHost||hostname.endsWith(`.${allowedHost}`)}import{existsSync as existsSync18,readFileSync as readFileSync17}from"node:fs";import{createSign}from"node:crypto";import{homedir as homedir2}from"node:os";import{join as join3}from"node:path";var CONFIG_PATH15=getWebSearchConfigPath(),DEFAULT_ADC_PATH=join3(homedir2(),".config","gcloud","application_default_credentials.json"),TOKEN_ENDPOINT="https://oauth2.googleapis.com/token",VERTEX_HOST="https://aiplatform.googleapis.com",VERTEX_API_VERSION="v1",REFRESH_SKEW_MS=6e4,cachedConfig14=null;function loadConfig13(){if(cachedConfig14)return cachedConfig14;if(!existsSync18(CONFIG_PATH15))return cachedConfig14={},cachedConfig14;let raw=readFileSync17(CONFIG_PATH15,"utf-8");try{let parsed=JSON.
|
|
421
|
+
parse(raw);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("config root must be an object");cachedConfig14=parsed}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH15}: ${message}`)}return cachedConfig14}function normalizeIdentifier(value,envName){if(typeof value=="string"){let trimmed=value.trim();if(trimmed)return trimmed}let fromEnv=process.env[envName]?.trim();return fromEnv||null}function isAdcAuthSelected(){
|
|
422
|
+
return(loadConfig13().geminiAuth??"").toString().trim().toLowerCase()==="adc"}function getAdcProject(){return normalizeIdentifier(loadConfig13().geminiProject,"GOOGLE_CLOUD_PROJECT")??normalizeIdentifier(null,"GCLOUD_PROJECT")}function getAdcLocation(){return normalizeIdentifier(loadConfig13().geminiLocation,"GOOGLE_CLOUD_LOCATION")}function getAdcPath(){return process.env.GOOGLE_APPLICATION_CREDENTIALS?.trim()||DEFAULT_ADC_PATH}function hasExplicitAdcPath(){return!!process.env.GOOGLE_APPLICATION_CREDENTIALS?.
|
|
445
423
|
trim()}function isOnGcp(){if(process.env.METADATA_SERVER_DETECTION?.trim().toLowerCase()==="none")return!1;if(process.env.GCE_METADATA_HOST?.trim())return!0;try{return/Google/.test(readFileSync17("/sys/class/dmi/id/bios_vendor","utf8"))}catch{return!1}}function getVertexApiBase(project,location){return`${VERTEX_HOST}/${VERTEX_API_VERSION}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}/publishers/google`}function isVertexHost(origin){return origin===VERTEX_HOST}
|
|
446
424
|
function objectRecord(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:null}function stringField(record,name){let value=record[name];return typeof value=="string"?value:void 0}function requiredString(record,name,context){let value=stringField(record,name)?.trim();if(!value)throw new Error(`${context} is missing ${name}`);return value}function parseAdcFile(raw){let parsed=objectRecord(JSON.parse(raw));if(!parsed)throw new Error("credential root must be an object");let type=stringField(
|
|
447
425
|
parsed,"type")??"authorized_user";return type==="authorized_user"?{type,client_id:requiredString(parsed,"client_id","Gemini ADC authorized_user file"),client_secret:requiredString(parsed,"client_secret","Gemini ADC authorized_user file"),refresh_token:requiredString(parsed,"refresh_token","Gemini ADC authorized_user file"),universe_domain:stringField(parsed,"universe_domain")}:type==="service_account"?{type,client_email:requiredString(parsed,"client_email","Gemini ADC service_account file"),private_key:requiredString(
|
|
@@ -453,28 +431,28 @@ if(!cfg.client_email||!cfg.private_key)throw new Error("Gemini ADC service_accou
|
|
|
453
431
|
signer.end();let signature=signer.sign(cfg.private_key,"base64url"),jwt=`${assertion}.${signature}`,body=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:jwt}),res=await fetch(TOKEN_ENDPOINT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body,signal}),text2=await res.text();return res.ok||throwOnTokenExchangeFailure(res,redactValues(text2,[jwt,cfg.private_key]),res.status),parseTokenExchangeResponse(text2,"Gemini ADC service acc\
|
|
454
432
|
ount token exchange")}async function fetchMetadataToken(signal){let url=`${getMetadataServerOrigin()}/computeMetadata/v1/instance/service-accounts/default/token`,res,text2;try{res=await fetch(url,{headers:{"Metadata-Flavor":"Google"},redirect:"error",signal}),text2=await res.text()}catch{throw new Error("Gemini ADC metadata server token request failed")}if(!res.ok)throw res.status===401||res.status===403?new CredentialResolutionError("Gemini ADC","oauth-credential-rejected"):new Error(`Gemini AD\
|
|
455
433
|
C metadata server token request failed (HTTP ${res.status})`);return parseTokenExchangeResponse(text2,"Gemini ADC metadata server token")}async function getAdcAccessToken(signal){if(cachedToken&&cachedToken.expiresAt>Date.now())return cachedToken.token;if(!hasExplicitAdcPath()&&!existsSync18(DEFAULT_ADC_PATH)&&isOnGcp())return cachedToken=await fetchMetadataToken(signal),cachedToken.token;let cfg=await loadAdcFile(),type=cfg.type??"authorized_user";if(type==="authorized_user")cachedToken=await exchangeRefreshToken(
|
|
456
|
-
cfg,signal);else if(type==="service_account")cachedToken=await exchangeServiceAccountJwt(cfg,signal);else throw new Error(`Gemini ADC unsupported credential type "${type}" (expected authorized_user or service_account)`);return cachedToken.token}function isGeminiAdcAvailable(){return!isAdcAuthSelected()||hasGeminiApiKeySource()||hasExplicitApiBase()||!getAdcProject()||!getAdcLocation()?!1:existsSync18(getAdcPath())?!0:!hasExplicitAdcPath()&&isOnGcp()}function hasGeminiApiKeySource(){let configured=
|
|
457
|
-
geminiApiKey;return typeof configured=="string"&&configured.trim()?!0:!!process.env.GEMINI_API_KEY?.trim()}function hasExplicitApiBase(){if(process.env.GOOGLE_GEMINI_BASE_URL?.trim())return!0;let configured=
|
|
458
|
-
Error?err.message:String(err);throw new Error(`Failed to parse ${
|
|
459
|
-
length>0?normalized:null}function isCloudflareGateway(){return getApiHost().includes("gateway.ai.cloudflare.com")}async function
|
|
460
|
-
return isGeminiAdcAvailable()&&project&&location?getVertexApiBase(project,location):`${getApiHost()}/${API_VERSION}`}function getUploadBase(){return`${getApiHost()}/upload/${API_VERSION}`}function rewriteUploadUrlOrigin(url){try{let parsed=new URL(url),base=getApiHost();return parsed.origin===new URL(base).origin?url:`${base}${parsed.pathname}${parsed.search}`}catch{return url}}function getLegacyCloudflareApiKey(){return normalizeApiKey2(process.env.CLOUDFLARE_API_KEY)??normalizeApiKey2(
|
|
461
|
-
cloudflareApiKey)}async function resolveCloudflareApiKey(signal){return resolveCredential({provider:"Cloudflare",configuredValue:
|
|
434
|
+
cfg,signal);else if(type==="service_account")cachedToken=await exchangeServiceAccountJwt(cfg,signal);else throw new Error(`Gemini ADC unsupported credential type "${type}" (expected authorized_user or service_account)`);return cachedToken.token}function isGeminiAdcAvailable(){return!isAdcAuthSelected()||hasGeminiApiKeySource()||hasExplicitApiBase()||!getAdcProject()||!getAdcLocation()?!1:existsSync18(getAdcPath())?!0:!hasExplicitAdcPath()&&isOnGcp()}function hasGeminiApiKeySource(){let configured=loadConfig13().
|
|
435
|
+
geminiApiKey;return typeof configured=="string"&&configured.trim()?!0:!!process.env.GEMINI_API_KEY?.trim()}function hasExplicitApiBase(){if(process.env.GOOGLE_GEMINI_BASE_URL?.trim())return!0;let configured=loadConfig13().geminiBaseUrl;return typeof configured=="string"&&configured.trim().length>0}import{existsSync as existsSync19,readFileSync as readFileSync18}from"node:fs";var DEFAULT_API_HOST="https://generativelanguage.googleapis.com",API_VERSION="v1beta",API_BASE=`${DEFAULT_API_HOST}/${API_VERSION}`,CONFIG_PATH16=getWebSearchConfigPath(),DEFAULT_MODEL="gemini-3.6-flash",cachedConfig15=null;function loadConfig14(){if(cachedConfig15)return cachedConfig15;if(!existsSync19(CONFIG_PATH16))return cachedConfig15={},cachedConfig15;let raw=readFileSync18(CONFIG_PATH16,"utf-8");try{return cachedConfig15=JSON.parse(raw),cachedConfig15}catch(err){let message=err instanceof
|
|
436
|
+
Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH16}: ${message}`)}}function withTimeout(signal,timeoutMs){let timeout=AbortSignal.timeout(timeoutMs);return signal?AbortSignal.any([signal,timeout]):timeout}function normalizeApiKey2(value){if(typeof value!="string")return null;let normalized=value.trim();return normalized.length>0?normalized:null}function normalizeBaseUrl2(value){if(typeof value!="string")return null;let normalized=value.trim().replace(/\/+$/,"");return normalized.
|
|
437
|
+
length>0?normalized:null}function isCloudflareGateway(){return getApiHost().includes("gateway.ai.cloudflare.com")}async function getApiKey11(signal){return resolveCredential({provider:"Gemini",configuredValue:loadConfig14().geminiApiKey,environmentValue:process.env.GEMINI_API_KEY,signal})}function getApiHost(){return normalizeBaseUrl2(process.env.GOOGLE_GEMINI_BASE_URL)??normalizeBaseUrl2(loadConfig14().geminiBaseUrl)??DEFAULT_API_HOST}function getVersionedApiBase(){let project=getAdcProject(),location=getAdcLocation();
|
|
438
|
+
return isGeminiAdcAvailable()&&project&&location?getVertexApiBase(project,location):`${getApiHost()}/${API_VERSION}`}function getUploadBase(){return`${getApiHost()}/upload/${API_VERSION}`}function rewriteUploadUrlOrigin(url){try{let parsed=new URL(url),base=getApiHost();return parsed.origin===new URL(base).origin?url:`${base}${parsed.pathname}${parsed.search}`}catch{return url}}function getLegacyCloudflareApiKey(){return normalizeApiKey2(process.env.CLOUDFLARE_API_KEY)??normalizeApiKey2(loadConfig14().
|
|
439
|
+
cloudflareApiKey)}async function resolveCloudflareApiKey(signal){return resolveCredential({provider:"Cloudflare",configuredValue:loadConfig14().cloudflareApiKey,environmentValue:process.env.CLOUDFLARE_API_KEY,signal})}function isGatewayConfigured(){return isCloudflareGateway()&&hasCredentialSource({provider:"Cloudflare",configuredValue:loadConfig14().cloudflareApiKey,environmentValue:process.env.CLOUDFLARE_API_KEY})}function buildAuthHeaders(apiKey=null,cloudflareApiKey=getLegacyCloudflareApiKey()){return isCloudflareGateway()?cloudflareApiKey?{"cf-aig-authorization":`Bearer ${cloudflareApiKey}`}:{}:apiKey?{"x-goog-api-key":apiKey}:{}}function redactGeminiCredentials(text2,apiKey,cloudflareApiKey,adcToken){let out=redactCredential(
|
|
462
440
|
redactCredential(text2,apiKey),cloudflareApiKey);return adcToken&&(out=redactCredential(out,adcToken)),out}var responseCredentials=new WeakMap;function redactGeminiApiResponse(response,text2,apiKey,adcToken){let credentials=responseCredentials.get(response);return redactGeminiCredentials(text2,credentials?.apiKey??apiKey,credentials?.cloudflareApiKey,credentials?.adcToken??adcToken)}async function fetchGeminiApi(url,init={},apiKey){let parsedUrl=new URL(url);for(let name of parsedUrl.searchParams.
|
|
463
|
-
keys())if(["key","api_key"].includes(name.toLowerCase()))throw new Error("Gemini API credential query parameters are not allowed");let project=getAdcProject(),location=getAdcLocation(),adcMode=isGeminiAdcAvailable()&&!!project&&!!location&&isVertexHost(parsedUrl.origin),adcToken=null;adcMode&&(adcToken=await getAdcAccessToken(init.signal??void 0));let resolvedApiKey=adcMode?null:apiKey===void 0?await
|
|
441
|
+
keys())if(["key","api_key"].includes(name.toLowerCase()))throw new Error("Gemini API credential query parameters are not allowed");let project=getAdcProject(),location=getAdcLocation(),adcMode=isGeminiAdcAvailable()&&!!project&&!!location&&isVertexHost(parsedUrl.origin),adcToken=null;adcMode&&(adcToken=await getAdcAccessToken(init.signal??void 0));let resolvedApiKey=adcMode?null:apiKey===void 0?await getApiKey11(init.signal??void 0):apiKey,cloudflareApiKey=isCloudflareGateway()?await resolveCloudflareApiKey(
|
|
464
442
|
init.signal??void 0):null,allowedOrigins=new Set([new URL(getApiHost()).origin,new URL(DEFAULT_API_HOST).origin,...adcMode?[parsedUrl.origin]:[]]);if((resolvedApiKey||isGatewayConfigured()||adcMode)&&!allowedOrigins.has(parsedUrl.origin))throw new Error("Gemini API request host is not allowed");let headers=new Headers(init.headers);if(headers.delete("x-goog-api-key"),headers.delete("cf-aig-authorization"),headers.delete("authorization"),adcMode&&adcToken)headers.set("Authorization",`Bearer ${adcToken}`);else
|
|
465
443
|
for(let[name,value]of Object.entries(buildAuthHeaders(resolvedApiKey,cloudflareApiKey)))headers.set(name,value);try{let response=await fetch(parsedUrl,{...init,headers});return responseCredentials.set(response,{apiKey:resolvedApiKey,cloudflareApiKey,adcToken}),response}catch(error){let message=error instanceof Error?error.message:String(error),redactedMessage=redactGeminiCredentials(message,resolvedApiKey,cloudflareApiKey,adcToken);if(redactedMessage===message)throw error;let redactedError=new Error(
|
|
466
|
-
redactedMessage);throw error instanceof Error&&(redactedError.name=error.name),redactedError}}function hasGeminiApiKeySource2(){return hasCredentialSource({provider:"Gemini",configuredValue:
|
|
467
|
-
let signal=withTimeout(options.signal,options.timeoutMs??12e4),apiKey=isGeminiAdcAvailable()?null:options.apiKey??await
|
|
468
|
-
1. Configure geminiApiKey in ${
|
|
444
|
+
redactedMessage);throw error instanceof Error&&(redactedError.name=error.name),redactedError}}function hasGeminiApiKeySource2(){return hasCredentialSource({provider:"Gemini",configuredValue:loadConfig14().geminiApiKey,environmentValue:process.env.GEMINI_API_KEY})}function isGeminiApiAvailable(){return isGeminiAdcAvailable()||hasGeminiApiKeySource2()||isGatewayConfigured()}function isGeminiApiAvailableWithVideo(){return hasGeminiApiKeySource2()||isGatewayConfigured()}async function queryGeminiApiWithInlineData(prompt,data,mimeType,options={}){
|
|
445
|
+
let signal=withTimeout(options.signal,options.timeoutMs??12e4),apiKey=isGeminiAdcAvailable()?null:options.apiKey??await getApiKey11(signal);if(!apiKey&&!isGatewayConfigured()&&!isGeminiAdcAvailable())throw new Error(`Gemini API not configured. Either:
|
|
446
|
+
1. Configure geminiApiKey in ${CONFIG_PATH16} or set GEMINI_API_KEY
|
|
469
447
|
2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing
|
|
470
448
|
3. Set geminiAuth to "adc" with a Google Cloud ADC (GOOGLE_APPLICATION_CREDENTIALS) + project/location`);let model=options.model??DEFAULT_MODEL,url=`${getVersionedApiBase()}/models/${model}:generateContent`,res=await fetchGeminiApi(url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{role:"user",parts:[{inlineData:{mimeType,data}},{text:prompt}]}]}),signal},apiKey);if(!res.ok){let errorText=redactGeminiApiResponse(res,await res.text(),apiKey);throw new Error(
|
|
471
449
|
`Gemini API error ${res.status}: ${errorText.slice(0,300)}`)}let response=await res.json(),candidate=response.candidates?.[0];return{text:candidate?.content?.parts?.map(part=>part.text).filter(part=>typeof part=="string"&&part.length>0).join(`
|
|
472
|
-
`)??"",...candidate?.finishReason?{finishReason:candidate.finishReason}:{},...response.promptFeedback?.blockReason?{blockReason:response.promptFeedback.blockReason}:{}}}async function queryGeminiApiWithVideo(prompt,videoUri,options={}){let signal=withTimeout(options.signal,options.timeoutMs??12e4),apiKey=options.apiKey??await
|
|
473
|
-
1. Configure geminiApiKey in ${
|
|
450
|
+
`)??"",...candidate?.finishReason?{finishReason:candidate.finishReason}:{},...response.promptFeedback?.blockReason?{blockReason:response.promptFeedback.blockReason}:{}}}async function queryGeminiApiWithVideo(prompt,videoUri,options={}){let signal=withTimeout(options.signal,options.timeoutMs??12e4),apiKey=options.apiKey??await getApiKey11(signal);if(!apiKey&&!isGatewayConfigured())throw new Error(`Gemini API not configured. Either:
|
|
451
|
+
1. Configure geminiApiKey in ${CONFIG_PATH16} or set GEMINI_API_KEY
|
|
474
452
|
2. Set GOOGLE_GEMINI_BASE_URL + CLOUDFLARE_API_KEY for Cloudflare AI Gateway routing`);let model=options.model??DEFAULT_MODEL,url=`${getVersionedApiBase()}/models/${model}:generateContent`,fileData={fileUri:videoUri};options.mimeType&&(fileData.mimeType=options.mimeType);let res=await fetchGeminiApi(url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{role:"user",parts:[{fileData},{text:prompt}]}]}),signal},apiKey);if(!res.ok){let errorText=redactGeminiApiResponse(
|
|
475
453
|
res,await res.text(),apiKey);throw new Error(`Gemini API error ${res.status}: ${errorText.slice(0,300)}`)}let text2=(await res.json()).candidates?.[0]?.content?.parts?.map(p=>p.text).filter(Boolean).join(`
|
|
476
454
|
`);if(!text2)throw new Error("Gemini API returned empty response");return text2}import{readFileSync as readFileSync19}from"node:fs";import{basename as basename2}from"node:path";var GEMINI_APP_URL="https://gemini.google.com/app",GEMINI_STREAM_GENERATE_URL="https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate",GEMINI_UPLOAD_URL="https://content-push.googleapis.com/upload",GEMINI_UPLOAD_PUSH_ID="feeds/mcudyrk2a4khkz",GOOGLE_LIST_ACCOUNTS_URL="https://accounts.google.com/ListAccounts?gpsia=1&source=ChromiumBrowser&laf=b64bin&json=standard",USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \
|
|
477
|
-
Chrome/120.0.0.0 Safari/537.36",MODEL_HEADER_NAME="x-goog-ext-525001261-jspb",DEFAULT_GEMINI_WEB_MODEL="gemini-3.1-pro",MODEL_HEADERS={[DEFAULT_GEMINI_WEB_MODEL]:'[1,null,null,null,"9d8ca3786ebdfbea",null,null,0,[4]]',"gemini-2.5-pro":'[1,null,null,null,"4af6c7f5da75d65d",null,null,0,[4]]',"gemini-2.5-flash":'[1,null,null,null,"9ec249fc9ad08861",null,null,0,[4]]'},REQUIRED_COOKIES=["__Secure-1PSID","__Secure-1PSIDTS"],geminiFetchImpl=null;var geminiFetchOverride=null,GEMINI_MAX_HEADER_SIZE=4*1024*1024;function createGeminiFetch(undiciImpl){let agent=new undiciImpl.EnvHttpProxyAgent({allowH2:!1,connectTimeout:3e4,maxHeaderSize:GEMINI_MAX_HEADER_SIZE,pipelining:1});return(input,init)=>undiciImpl.fetch(input,{...init,dispatcher:agent})}async function resolveGeminiFetch(){if(geminiFetchOverride)return geminiFetchOverride;if(geminiFetchImpl)return geminiFetchImpl;let undici;try{undici=await import("./undici-
|
|
455
|
+
Chrome/120.0.0.0 Safari/537.36",MODEL_HEADER_NAME="x-goog-ext-525001261-jspb",DEFAULT_GEMINI_WEB_MODEL="gemini-3.1-pro",MODEL_HEADERS={[DEFAULT_GEMINI_WEB_MODEL]:'[1,null,null,null,"9d8ca3786ebdfbea",null,null,0,[4]]',"gemini-2.5-pro":'[1,null,null,null,"4af6c7f5da75d65d",null,null,0,[4]]',"gemini-2.5-flash":'[1,null,null,null,"9ec249fc9ad08861",null,null,0,[4]]'},REQUIRED_COOKIES=["__Secure-1PSID","__Secure-1PSIDTS"],geminiFetchImpl=null;var geminiFetchOverride=null,GEMINI_MAX_HEADER_SIZE=4*1024*1024;function createGeminiFetch(undiciImpl){let agent=new undiciImpl.EnvHttpProxyAgent({allowH2:!1,connectTimeout:3e4,maxHeaderSize:GEMINI_MAX_HEADER_SIZE,pipelining:1});return(input,init)=>undiciImpl.fetch(input,{...init,dispatcher:agent})}async function resolveGeminiFetch(){if(geminiFetchOverride)return geminiFetchOverride;if(geminiFetchImpl)return geminiFetchImpl;let undici;try{undici=await import("./undici-WVNE45GY.js")}catch{return geminiFetchImpl=
|
|
478
456
|
fetch,geminiFetchImpl}return geminiFetchImpl=createGeminiFetch(undici),geminiFetchImpl}async function isGeminiWebAvailable(chromeProfile){if(!isBrowserCookieAccessAllowed())return null;let configured=getBrowserCookieSelectionFromConfig(),result=await getGoogleCookies({browser:configured.browser,profile:normalizeChromeProfile(chromeProfile)??configured.profile,requiredCookies:REQUIRED_COOKIES});return result?result.cookies:null}function getGeminiWebAvailabilityDiagnostic(){return isBrowserCookieAccessAllowed()?
|
|
479
457
|
getLastGoogleCookieDiagnostic():null}function getGeminiWebAvailabilityDiagnosticDetails(){return isBrowserCookieAccessAllowed()?getLastGoogleCookieDiagnosticDetails():null}async function getActiveGoogleEmail(cookies){let cookieHeader=buildCookieHeader2(cookies);if(!cookieHeader)return null;try{let html=await fetchWithCookieRedirects(GEMINI_APP_URL,cookieHeader,10,AbortSignal.timeout(1e4)),email=extractEmailFromGeminiHtml(html);if(email)return email}catch{}try{let response=await fetchWithCookieRedirects(
|
|
480
458
|
GOOGLE_LIST_ACCOUNTS_URL,cookieHeader,10,AbortSignal.timeout(1e4));return extractEmailFromListAccounts(response)}catch{return null}}async function queryWithCookies(prompt,cookieMap,options={}){let model=options.model??DEFAULT_GEMINI_WEB_MODEL;if(!MODEL_HEADERS[model])throw new Error(`Gemini Web does not support model ${model}; configure Gemini API or choose a supported Gemini Web model.`);let timeoutMs=options.timeoutMs??12e4,fullPrompt=prompt;options.youtubeUrl&&(fullPrompt=`${fullPrompt}
|
|
@@ -498,20 +476,19 @@ let innerList=[uploaded.length>0?[prompt,0,null,uploaded.map(file=>[[file.id,1],
|
|
|
498
476
|
let current=value;for(let part of pathParts){if(current==null||!Array.isArray(current))return;current=current[part]}return current}function trimJsonEnvelope(text2){let start=text2.indexOf("["),end=text2.lastIndexOf("]");if(start===-1||end===-1||end<=start)throw new Error("Gemini response did not contain a JSON payload.");return text2.slice(start,end+1)}function extractErrorCode(responseJson){let code=getNestedValue(responseJson,[0,5,2,0,1,0]);return typeof code=="number"&&code>=0?code:void 0}function extractCandidateText(candidate){
|
|
499
477
|
let textRaw=getNestedValue(candidate,[1,0]),text2=typeof textRaw=="string"?textRaw:"";if(/^http:\/\/googleusercontent\.com\/card_content\/\d+/.test(text2)){let alt=getNestedValue(candidate,[22,0]);typeof alt=="string"&&alt.length>0&&(text2=alt)}return text2}function parseStreamGenerateResponse(rawText){let responseJson=JSON.parse(trimJsonEnvelope(rawText)),errorCode=extractErrorCode(responseJson),parts=Array.isArray(responseJson)?responseJson:[],firstCandidateSeen,latestNonEmptyText="";for(let i=0;i<
|
|
500
478
|
parts.length;i++){let partBody=getNestedValue(parts[i],[2]);if(!(!partBody||typeof partBody!="string"))try{let parsed=JSON.parse(partBody),candidateList=getNestedValue(parsed,[4]);if(!Array.isArray(candidateList)||candidateList.length===0)continue;let firstCandidate=candidateList[0];firstCandidateSeen===void 0&&(firstCandidateSeen=firstCandidate);let text3=extractCandidateText(firstCandidate);text3.length>0&&(latestNonEmptyText=text3)}catch{}}return{text:latestNonEmptyText.length>0?latestNonEmptyText:
|
|
501
|
-
extractCandidateText(firstCandidateSeen),errorCode}}import{existsSync as existsSync20,readFileSync as readFileSync20}from"node:fs";var PERPLEXITY_SEARCH_URL="https://api.perplexity.ai/search",PERPLEXITY_CHAT_URL="https://api.perplexity.ai/chat/completions",
|
|
502
|
-
|
|
503
|
-
1. Create ${
|
|
479
|
+
extractCandidateText(firstCandidateSeen),errorCode}}import{existsSync as existsSync20,readFileSync as readFileSync20}from"node:fs";var PERPLEXITY_SEARCH_URL="https://api.perplexity.ai/search",PERPLEXITY_CHAT_URL="https://api.perplexity.ai/chat/completions",CONFIG_PATH17=getWebSearchConfigPath(),SEARCH_TIMEOUT_MS10=3e4,RATE_LIMIT={maxRequests:10,windowMs:60*1e3},requestTimestamps=[],cachedConfig16=null;function loadConfig15(){if(cachedConfig16)return cachedConfig16;if(!existsSync20(CONFIG_PATH17))return cachedConfig16={},cachedConfig16;let content=readFileSync20(CONFIG_PATH17,"utf-8");try{return cachedConfig16=JSON.parse(content),
|
|
480
|
+
cachedConfig16}catch(err){let message=err instanceof Error?err.message:String(err);throw new Error(`Failed to parse ${CONFIG_PATH17}: ${message}`)}}async function getApiKey12(signal){let key=await resolveCredential({provider:"Perplexity",configuredValue:loadConfig15().perplexityApiKey,environmentValue:process.env.PERPLEXITY_API_KEY,signal});if(!key)throw new Error(`Perplexity API key not found. Either:
|
|
481
|
+
1. Create ${CONFIG_PATH17} with { "perplexityApiKey": "your-key" }
|
|
504
482
|
2. Set PERPLEXITY_API_KEY environment variable
|
|
505
483
|
Get a key at https://perplexity.ai/settings/api`);return key}function checkRateLimit(){let now=Date.now(),windowStart=now-RATE_LIMIT.windowMs;for(;requestTimestamps.length>0&&requestTimestamps[0]<windowStart;)requestTimestamps.shift();if(requestTimestamps.length>=RATE_LIMIT.maxRequests){let waitMs=requestTimestamps[0]+RATE_LIMIT.windowMs-now;throw new Error(`Rate limited. Try again in ${Math.ceil(waitMs/1e3)}s`)}requestTimestamps.push(now)}function validateDomainFilter(domains){return domains.filter(
|
|
506
|
-
d=>{let domain=d.startsWith("-")?d.slice(1):d;return/^[a-zA-Z0-9][a-zA-Z0-9-_.]*\.[a-zA-Z]{2,}$/.test(domain)})}function isPerplexityAvailable(){return hasCredentialSource({provider:"Perplexity",configuredValue:
|
|
507
|
-
activityQuery});activityMonitor.updateRateLimit({used:requestTimestamps.length,max:RATE_LIMIT.maxRequests,oldestTimestamp:requestTimestamps[0]??null,windowMs:RATE_LIMIT.windowMs});let apiKey=await
|
|
484
|
+
d=>{let domain=d.startsWith("-")?d.slice(1):d;return/^[a-zA-Z0-9][a-zA-Z0-9-_.]*\.[a-zA-Z]{2,}$/.test(domain)})}function isPerplexityAvailable(){return hasCredentialSource({provider:"Perplexity",configuredValue:loadConfig15().perplexityApiKey,environmentValue:process.env.PERPLEXITY_API_KEY})}async function postPerplexity(url,body,options){let apiUrl=resolveProviderApiUrl("perplexity",url,loadConfig15().perplexityBaseUrl);checkRateLimit();let activityId=activityMonitor.logStart({type:"api",query:options.
|
|
485
|
+
activityQuery});activityMonitor.updateRateLimit({used:requestTimestamps.length,max:RATE_LIMIT.maxRequests,oldestTimestamp:requestTimestamps[0]??null,windowMs:RATE_LIMIT.windowMs});let apiKey=await getApiKey12(options.signal),timeout=AbortSignal.timeout(SEARCH_TIMEOUT_MS10),timedOut=()=>timeout.aborted&&!options.signal?.aborted,timeoutError=()=>new Error("Perplexity API error 408: request timed out"),response;try{response=await fetchWithCredentialRedirects(apiUrl,{method:"POST",headers:{Authorization:`\
|
|
508
486
|
Bearer ${apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(body),signal:options.signal?AbortSignal.any([options.signal,timeout]):timeout},["Authorization"])}catch(err){if(timedOut())throw activityMonitor.logError(activityId,"request timed out"),timeoutError();let message=err instanceof Error?err.message:String(err),redactedMessage=redactCredential(message,apiKey);if(redactedMessage.toLowerCase().includes("abort")?activityMonitor.logComplete(activityId,0):activityMonitor.logError(activityId,
|
|
509
487
|
redactedMessage),redactedMessage===message)throw err;let redactedError=new Error(redactedMessage);throw err instanceof Error&&(redactedError.name=err.name),redactedError}if(activityMonitor.logComplete(activityId,response.status),!response.ok){let errorText;try{errorText=redactCredential(await response.text(),apiKey)}catch(err){throw timedOut()?timeoutError():err}throw new Error(`Perplexity API error ${response.status}: ${errorText}`)}try{return await response.json()}catch(err){if(timedOut())throw timeoutError();
|
|
510
488
|
let message=err instanceof Error?err.message:String(err);throw new Error(`Perplexity API returned invalid JSON: ${message}`)}}async function searchWithPerplexity(query,options={}){let numResults=typeof options.numResults=="number"&&Number.isFinite(options.numResults)?Math.max(1,Math.min(Math.floor(options.numResults),20)):5,requestBody={query,max_results:numResults,search_type:"fast",search_context_size:"medium"};if(options.recencyFilter&&(requestBody.search_recency_filter=options.recencyFilter),
|
|
511
489
|
options.domainFilter&&options.domainFilter.length>0){let validated=validateDomainFilter(options.domainFilter);validated.length>0&&(requestBody.search_domain_filter=validated)}let data=await postPerplexity(PERPLEXITY_SEARCH_URL,requestBody,{activityQuery:query,signal:options.signal}),results=[];for(let entry of Array.isArray(data.results)?data.results:[])if(!(!entry||typeof entry!="object"||typeof entry.url!="string"||!entry.url)&&(results.push({title:typeof entry.title=="string"&&entry.title.trim()?
|
|
512
490
|
entry.title.trim():`Source ${results.length+1}`,url:entry.url,snippet:typeof entry.snippet=="string"?entry.snippet.trim():""}),results.length>=numResults))break;return{answer:formatSearchResultsAsAnswer(results),results}}async function askPerplexity(prompt,options={}){let content=(await postPerplexity(PERPLEXITY_CHAT_URL,{model:"sonar",messages:[{role:"user",content:prompt}],max_tokens:1024,return_related_questions:!1},{activityQuery:prompt,signal:options.signal})).choices?.[0]?.message?.content;
|
|
513
|
-
return typeof content=="string"?content:""}export{
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
pLimit,resolveAuthFetchProfile,assertAuthFetchUrl,authFetchRedirectGuard};
|
|
491
|
+
return typeof content=="string"?content:""}export{activityMonitor,checkGhAvailable,showGhHint,parseGitHubUrl,extractGitHub,touchClones,releaseClonesUnusedSince,clearCloneCache,CredentialResolutionError,redactCredential,hasCredentialSource,resolveCredential,isGeminiAdcAvailable,DEFAULT_MODEL,getApiKey11 as getApiKey,getVersionedApiBase,getUploadBase,rewriteUploadUrlOrigin,isGatewayConfigured,redactGeminiApiResponse,fetchGeminiApi,isGeminiApiAvailable,isGeminiApiAvailableWithVideo,queryGeminiApiWithInlineData,queryGeminiApiWithVideo,isBrowserCookieAccessAllowed,
|
|
492
|
+
getLastBrowserCookieDiagnostic,getBrowserCookiesForHosts,isGeminiWebAvailable,getGeminiWebAvailabilityDiagnostic,getGeminiWebAvailabilityDiagnosticDetails,getActiveGoogleEmail,queryWithCookies,formatSearchResultsAsAnswer,isPerplexityAvailable,searchWithPerplexity,askPerplexity,normalizeDomain,applyDomainFilter,loadFetchContentRedirectPolicy,loadFetchContentUserAgent,loadConfiguredFetchContentUserAgent,loadFetchContentCurl,loadFetchContentDomainPolicy,loadSsrfConfig,validateRemoteUrl,fetchRemoteUrl,
|
|
493
|
+
trustedEnvProxyFor,isExaAvailable,hasExaApiKey,searchWithExa,extractWithExa,normalizeSearchResultCount,isParallelAvailable,searchWithParallel,extractWithParallel,isParallelMcpAvailable,searchWithParallelMcp,extractWithParallelMcp,isTinyFishAvailable,searchWithTinyFish,extractWithTinyFish,isSearch1APIAvailable,searchWithSearch1API,extractWithSearch1API,isQueritAvailable,searchWithQuerit,extractWithQuerit,isTabstackAvailable,searchWithTabstack,extractWithTabstack,isFirecrawlAvailable,searchWithFirecrawl,
|
|
494
|
+
extractWithFirecrawl,isKagiAvailable,searchWithKagi,isKagiExtractAvailable,extractWithKagi,isOllamaAvailable,searchWithOllama,isOllamaFetchAvailable,extractWithOllama,isSpecStreamAvailable,searchWithSpecStream,extractWithSpecStream,isDeepSeekAvailable,searchWithDeepSeek,extractWithDeepSeek,pLimit,resolveAuthFetchProfile,assertAuthFetchUrl,authFetchRedirectGuard};
|