@humain/terminal 0.0.2 → 0.0.3-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +251 -24
- package/README.md +143 -119
- package/dist/cli/args.d.ts +4 -2
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +37 -39
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-check.d.ts +19 -0
- package/dist/cli/auth-check.d.ts.map +1 -0
- package/dist/cli/auth-check.js +50 -0
- package/dist/cli/auth-check.js.map +1 -0
- package/dist/cli/auth-command.d.ts +24 -0
- package/dist/cli/auth-command.d.ts.map +1 -0
- package/dist/cli/auth-command.js +103 -0
- package/dist/cli/auth-command.js.map +1 -0
- package/dist/cli/config-selector.d.ts.map +1 -1
- package/dist/cli/config-selector.js +2 -2
- package/dist/cli/config-selector.js.map +1 -1
- package/dist/cli/credential-print.d.ts +5 -15
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +42 -83
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/cli/experimental/auth.d.ts +16 -0
- package/dist/cli/experimental/auth.d.ts.map +1 -0
- package/dist/cli/experimental/auth.js +13 -0
- package/dist/cli/experimental/auth.js.map +1 -0
- package/dist/cli/experimental/cli.d.ts +6 -0
- package/dist/cli/experimental/cli.d.ts.map +1 -0
- package/dist/cli/experimental/cli.js +5 -0
- package/dist/cli/experimental/cli.js.map +1 -0
- package/dist/cli/experimental/command-options.d.ts +17 -0
- package/dist/cli/experimental/command-options.d.ts.map +1 -0
- package/dist/cli/experimental/command-options.js +35 -0
- package/dist/cli/experimental/command-options.js.map +1 -0
- package/dist/cli/experimental/command.d.ts +63 -0
- package/dist/cli/experimental/command.d.ts.map +1 -0
- package/dist/cli/experimental/command.js +130 -0
- package/dist/cli/experimental/command.js.map +1 -0
- package/dist/cli/experimental/commands/client.d.ts +13 -0
- package/dist/cli/experimental/commands/client.d.ts.map +1 -0
- package/dist/cli/experimental/commands/client.js +25 -0
- package/dist/cli/experimental/commands/client.js.map +1 -0
- package/dist/cli/experimental/commands/pi.d.ts +15 -0
- package/dist/cli/experimental/commands/pi.d.ts.map +1 -0
- package/dist/cli/experimental/commands/pi.js +28 -0
- package/dist/cli/experimental/commands/pi.js.map +1 -0
- package/dist/cli/experimental/commands/server.d.ts +13 -0
- package/dist/cli/experimental/commands/server.d.ts.map +1 -0
- package/dist/cli/experimental/commands/server.js +25 -0
- package/dist/cli/experimental/commands/server.js.map +1 -0
- package/dist/cli/experimental/transport-address.d.ts +10 -0
- package/dist/cli/experimental/transport-address.d.ts.map +1 -0
- package/dist/cli/experimental/transport-address.js +38 -0
- package/dist/cli/experimental/transport-address.js.map +1 -0
- package/dist/cli/list-models.d.ts +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +2 -2
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli/startup-ui.d.ts +1 -1
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +2 -2
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +3 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/remote-session.d.ts +53 -0
- package/dist/client/remote-session.d.ts.map +1 -0
- package/dist/client/remote-session.js +340 -0
- package/dist/client/remote-session.js.map +1 -0
- package/dist/client/transcript.d.ts +12 -0
- package/dist/client/transcript.d.ts.map +1 -0
- package/dist/client/transcript.js +98 -0
- package/dist/client/transcript.js.map +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -3
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -10
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +72 -70
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +25 -9
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +237 -39
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +60 -41
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +2 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +3 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +27 -4
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +5 -0
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/keybindings.d.ts +45 -5
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-config.d.ts +29 -5
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +4 -0
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-registry.d.ts +5 -3
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +13 -10
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +4 -3
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +42 -10
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +30 -13
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +233 -73
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/models-store.d.ts +12 -7
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js +83 -14
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/package-manager.d.ts +6 -3
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +80 -61
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-manifest.d.ts +8 -0
- package/dist/core/pi-manifest.d.ts.map +1 -0
- package/dist/core/pi-manifest.js +28 -0
- package/dist/core/pi-manifest.js.map +1 -0
- package/dist/core/provider-composer.d.ts +4 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +36 -15
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +73 -67
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +2 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts +5 -5
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js +11 -8
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +2 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +3 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +12 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +40 -16
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +8 -0
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts +5 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +16 -15
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts +4 -0
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +11 -7
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +7 -0
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +16 -19
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +4 -0
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +5 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts +4 -0
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +5 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/read.d.ts +4 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +7 -3
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/write.d.ts +4 -0
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +6 -2
- package/dist/core/tools/write.js.map +1 -1
- package/dist/extensions/llama/index.d.ts.map +1 -1
- package/dist/extensions/llama/index.js +11 -2
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +21 -7
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/humain/agent-execution-protocol.d.ts +218 -0
- package/dist/humain/agent-execution-protocol.d.ts.map +1 -0
- package/dist/humain/agent-execution-protocol.js +204 -0
- package/dist/humain/agent-execution-protocol.js.map +1 -0
- package/dist/humain/agent-execution-runtime.d.ts +35 -0
- package/dist/humain/agent-execution-runtime.d.ts.map +1 -0
- package/dist/humain/agent-execution-runtime.js +170 -0
- package/dist/humain/agent-execution-runtime.js.map +1 -0
- package/dist/humain/index.d.ts.map +1 -1
- package/dist/humain/index.js +8 -7
- package/dist/humain/index.js.map +1 -1
- package/dist/humain/mcp-adapter/vendor/CHANGELOG.md +673 -0
- package/dist/humain/mcp-adapter/vendor/LICENSE +21 -0
- package/dist/humain/mcp-adapter/vendor/README.md +736 -0
- package/dist/humain/mcp-adapter/vendor/abort.ts +34 -0
- package/dist/humain/mcp-adapter/vendor/agent-dir.ts +68 -0
- package/dist/humain/mcp-adapter/vendor/agent-plugin-loader.ts +377 -0
- package/dist/humain/mcp-adapter/vendor/app-bridge.bundle.js +67 -0
- package/dist/humain/mcp-adapter/vendor/banner.png +0 -0
- package/dist/humain/mcp-adapter/vendor/cli.js +230 -0
- package/dist/humain/mcp-adapter/vendor/commands.ts +627 -0
- package/dist/humain/mcp-adapter/vendor/config.ts +1226 -0
- package/dist/humain/mcp-adapter/vendor/consent-manager.ts +64 -0
- package/dist/humain/mcp-adapter/vendor/direct-tools.ts +607 -0
- package/dist/humain/mcp-adapter/vendor/elicitation-handler.ts +348 -0
- package/dist/humain/mcp-adapter/vendor/error-signal.ts +21 -0
- package/dist/humain/mcp-adapter/vendor/errors.ts +223 -0
- package/dist/humain/mcp-adapter/vendor/glimpse-ui.ts +80 -0
- package/dist/humain/mcp-adapter/vendor/host-html-template.ts +461 -0
- package/dist/humain/mcp-adapter/vendor/index.bundle.d.mts +4 -0
- package/dist/humain/mcp-adapter/vendor/index.bundle.mjs +16279 -0
- package/dist/humain/mcp-adapter/vendor/index.ts +898 -0
- package/dist/humain/mcp-adapter/vendor/init.ts +649 -0
- package/dist/humain/mcp-adapter/vendor/json-schema-validator.ts +69 -0
- package/dist/humain/mcp-adapter/vendor/lifecycle.ts +147 -0
- package/dist/humain/mcp-adapter/vendor/logger.ts +169 -0
- package/dist/humain/mcp-adapter/vendor/mcp-auth-flow.ts +993 -0
- package/dist/humain/mcp-adapter/vendor/mcp-auth.ts +1000 -0
- package/dist/humain/mcp-adapter/vendor/mcp-callback-server.ts +510 -0
- package/dist/humain/mcp-adapter/vendor/mcp-code.ts +354 -0
- package/dist/humain/mcp-adapter/vendor/mcp-keyring-helper.cjs +89 -0
- package/dist/humain/mcp-adapter/vendor/mcp-oauth-provider.ts +616 -0
- package/dist/humain/mcp-adapter/vendor/mcp-output-guard.ts +408 -0
- package/dist/humain/mcp-adapter/vendor/mcp-panel.ts +1015 -0
- package/dist/humain/mcp-adapter/vendor/mcp-probe.ts +187 -0
- package/dist/humain/mcp-adapter/vendor/mcp-script-worker.mjs +130 -0
- package/dist/humain/mcp-adapter/vendor/mcp-setup-panel.ts +667 -0
- package/dist/humain/mcp-adapter/vendor/mcp-status.ts +109 -0
- package/dist/humain/mcp-adapter/vendor/mcp-trace.ts +306 -0
- package/dist/humain/mcp-adapter/vendor/metadata-cache.ts +363 -0
- package/dist/humain/mcp-adapter/vendor/npx-resolver.ts +543 -0
- package/dist/humain/mcp-adapter/vendor/oauth-handler.ts +30 -0
- package/dist/humain/mcp-adapter/vendor/oauth.ts +48 -0
- package/dist/humain/mcp-adapter/vendor/onboarding-state.ts +76 -0
- package/dist/humain/mcp-adapter/vendor/package.json +179 -0
- package/dist/humain/mcp-adapter/vendor/panel-keys.ts +53 -0
- package/dist/humain/mcp-adapter/vendor/prompts.ts +353 -0
- package/dist/humain/mcp-adapter/vendor/proxy-modes.ts +1331 -0
- package/dist/humain/mcp-adapter/vendor/request-headers-command.ts +336 -0
- package/dist/humain/mcp-adapter/vendor/resource-tools.ts +17 -0
- package/dist/humain/mcp-adapter/vendor/runtime-owner.ts +91 -0
- package/dist/humain/mcp-adapter/vendor/sampling-handler.ts +284 -0
- package/dist/humain/mcp-adapter/vendor/search-ranking.ts +206 -0
- package/dist/humain/mcp-adapter/vendor/server-manager.ts +1129 -0
- package/dist/humain/mcp-adapter/vendor/session-recovery.ts +151 -0
- package/dist/humain/mcp-adapter/vendor/skills/mcp-scripting/SKILL.md +38 -0
- package/dist/humain/mcp-adapter/vendor/state.ts +62 -0
- package/dist/humain/mcp-adapter/vendor/tool-approval.ts +182 -0
- package/dist/humain/mcp-adapter/vendor/tool-metadata.ts +296 -0
- package/dist/humain/mcp-adapter/vendor/tool-registrar.ts +253 -0
- package/dist/humain/mcp-adapter/vendor/tool-result-renderer.ts +423 -0
- package/dist/humain/mcp-adapter/vendor/ts-shape.ts +149 -0
- package/dist/humain/mcp-adapter/vendor/types.ts +942 -0
- package/dist/humain/mcp-adapter/vendor/ui-app-bridge-helpers.ts +40 -0
- package/dist/humain/mcp-adapter/vendor/ui-resource-handler.ts +250 -0
- package/dist/humain/mcp-adapter/vendor/ui-server.ts +866 -0
- package/dist/humain/mcp-adapter/vendor/ui-session.ts +570 -0
- package/dist/humain/mcp-adapter/vendor/ui-stream-types.ts +89 -0
- package/dist/humain/mcp-adapter/vendor/ui-tool-visibility.ts +25 -0
- package/dist/humain/mcp-adapter/vendor/unix-socket-transport.ts +85 -0
- package/dist/humain/mcp-adapter/vendor/utils.ts +310 -0
- package/dist/humain/mcp-adapter.d.ts +3 -0
- package/dist/humain/mcp-adapter.d.ts.map +1 -0
- package/dist/humain/mcp-adapter.js +5 -0
- package/dist/humain/mcp-adapter.js.map +1 -0
- package/dist/humain/pi-agent-execution-host.d.ts +34 -0
- package/dist/humain/pi-agent-execution-host.d.ts.map +1 -0
- package/dist/humain/pi-agent-execution-host.js +77 -0
- package/dist/humain/pi-agent-execution-host.js.map +1 -0
- package/dist/humain/web-access/host.d.ts +4 -0
- package/dist/humain/web-access/host.d.ts.map +1 -0
- package/dist/humain/web-access/host.js +3 -0
- package/dist/humain/web-access/host.js.map +1 -0
- package/dist/humain/web-access/index.d.ts +3 -0
- package/dist/humain/web-access/index.d.ts.map +1 -0
- package/dist/humain/web-access/index.js +5 -0
- package/dist/humain/web-access/index.js.map +1 -0
- package/dist/humain/web-access/vendor/activity.d.ts +34 -0
- package/dist/humain/web-access/vendor/activity.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/activity.js +68 -0
- package/dist/humain/web-access/vendor/activity.js.map +1 -0
- package/dist/humain/web-access/vendor/anysearch.d.ts +8 -0
- package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/anysearch.js +167 -0
- package/dist/humain/web-access/vendor/anysearch.js.map +1 -0
- package/dist/humain/web-access/vendor/auth-fetch.d.ts +13 -0
- package/dist/humain/web-access/vendor/auth-fetch.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/auth-fetch.js +134 -0
- package/dist/humain/web-access/vendor/auth-fetch.js.map +1 -0
- package/dist/humain/web-access/vendor/bocha.d.ts +4 -0
- package/dist/humain/web-access/vendor/bocha.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/bocha.js +219 -0
- package/dist/humain/web-access/vendor/bocha.js.map +1 -0
- package/dist/humain/web-access/vendor/brave.d.ts +4 -0
- package/dist/humain/web-access/vendor/brave.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/brave.js +194 -0
- package/dist/humain/web-access/vendor/brave.js.map +1 -0
- package/dist/humain/web-access/vendor/brightdata-unlocker.d.ts +12 -0
- package/dist/humain/web-access/vendor/brightdata-unlocker.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/brightdata-unlocker.js +230 -0
- package/dist/humain/web-access/vendor/brightdata-unlocker.js.map +1 -0
- package/dist/humain/web-access/vendor/brightdata.d.ts +8 -0
- package/dist/humain/web-access/vendor/brightdata.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/brightdata.js +519 -0
- package/dist/humain/web-access/vendor/brightdata.js.map +1 -0
- package/dist/humain/web-access/vendor/chrome-cookies.d.ts +23 -0
- package/dist/humain/web-access/vendor/chrome-cookies.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/chrome-cookies.js +522 -0
- package/dist/humain/web-access/vendor/chrome-cookies.js.map +1 -0
- package/dist/humain/web-access/vendor/content-find.d.ts +11 -0
- package/dist/humain/web-access/vendor/content-find.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/content-find.js +117 -0
- package/dist/humain/web-access/vendor/content-find.js.map +1 -0
- package/dist/humain/web-access/vendor/credential-source.d.ts +28 -0
- package/dist/humain/web-access/vendor/credential-source.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/credential-source.js +151 -0
- package/dist/humain/web-access/vendor/credential-source.js.map +1 -0
- package/dist/humain/web-access/vendor/curator-page.d.ts +30 -0
- package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/curator-page.js +3556 -0
- package/dist/humain/web-access/vendor/curator-page.js.map +1 -0
- package/dist/humain/web-access/vendor/curator-server.d.ts +94 -0
- package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/curator-server.js +690 -0
- package/dist/humain/web-access/vendor/curator-server.js.map +1 -0
- package/dist/humain/web-access/vendor/datalab-pdf-extract.d.ts +60 -0
- package/dist/humain/web-access/vendor/datalab-pdf-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/datalab-pdf-extract.js +416 -0
- package/dist/humain/web-access/vendor/datalab-pdf-extract.js.map +1 -0
- package/dist/humain/web-access/vendor/declared-web-links.d.ts +16 -0
- package/dist/humain/web-access/vendor/declared-web-links.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/declared-web-links.js +168 -0
- package/dist/humain/web-access/vendor/declared-web-links.js.map +1 -0
- package/dist/humain/web-access/vendor/duckduckgo.d.ts +4 -0
- package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/duckduckgo.js +123 -0
- package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -0
- package/dist/humain/web-access/vendor/exa.d.ts +10 -0
- package/dist/humain/web-access/vendor/exa.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/exa.js +426 -0
- package/dist/humain/web-access/vendor/exa.js.map +1 -0
- package/dist/humain/web-access/vendor/extract.d.ts +48 -0
- package/dist/humain/web-access/vendor/extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/extract.js +1126 -0
- package/dist/humain/web-access/vendor/extract.js.map +1 -0
- package/dist/humain/web-access/vendor/feature-config.d.ts +3 -0
- package/dist/humain/web-access/vendor/feature-config.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/feature-config.js +27 -0
- package/dist/humain/web-access/vendor/feature-config.js.map +1 -0
- package/dist/humain/web-access/vendor/fetch-params.d.ts +27 -0
- package/dist/humain/web-access/vendor/fetch-params.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/fetch-params.js +71 -0
- package/dist/humain/web-access/vendor/fetch-params.js.map +1 -0
- package/dist/humain/web-access/vendor/firecrawl.d.ts +19 -0
- package/dist/humain/web-access/vendor/firecrawl.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/firecrawl.js +370 -0
- package/dist/humain/web-access/vendor/firecrawl.js.map +1 -0
- package/dist/humain/web-access/vendor/gemini-api.d.ts +27 -0
- package/dist/humain/web-access/vendor/gemini-api.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/gemini-api.js +230 -0
- package/dist/humain/web-access/vendor/gemini-api.js.map +1 -0
- package/dist/humain/web-access/vendor/gemini-pdf-extract.d.ts +9 -0
- package/dist/humain/web-access/vendor/gemini-pdf-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/gemini-pdf-extract.js +85 -0
- package/dist/humain/web-access/vendor/gemini-pdf-extract.js.map +1 -0
- package/dist/humain/web-access/vendor/gemini-search.d.ts +40 -0
- package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/gemini-search.js +832 -0
- package/dist/humain/web-access/vendor/gemini-search.js.map +1 -0
- package/dist/humain/web-access/vendor/gemini-url-context.d.ts +4 -0
- package/dist/humain/web-access/vendor/gemini-url-context.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/gemini-url-context.js +101 -0
- package/dist/humain/web-access/vendor/gemini-url-context.js.map +1 -0
- package/dist/humain/web-access/vendor/gemini-web-config.d.ts +4 -0
- package/dist/humain/web-access/vendor/gemini-web-config.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/gemini-web-config.js +42 -0
- package/dist/humain/web-access/vendor/gemini-web-config.js.map +1 -0
- package/dist/humain/web-access/vendor/gemini-web.d.ts +18 -0
- package/dist/humain/web-access/vendor/gemini-web.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/gemini-web.js +385 -0
- package/dist/humain/web-access/vendor/gemini-web.js.map +1 -0
- package/dist/humain/web-access/vendor/github-api.d.ts +7 -0
- package/dist/humain/web-access/vendor/github-api.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/github-api.js +160 -0
- package/dist/humain/web-access/vendor/github-api.js.map +1 -0
- package/dist/humain/web-access/vendor/github-extract.d.ts +13 -0
- package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/github-extract.js +635 -0
- package/dist/humain/web-access/vendor/github-extract.js.map +1 -0
- package/dist/humain/web-access/vendor/index.d.ts +4 -0
- package/dist/humain/web-access/vendor/index.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/index.js +3076 -0
- package/dist/humain/web-access/vendor/index.js.map +1 -0
- package/dist/humain/web-access/vendor/jina-search.d.ts +8 -0
- package/dist/humain/web-access/vendor/jina-search.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/jina-search.js +255 -0
- package/dist/humain/web-access/vendor/jina-search.js.map +1 -0
- package/dist/humain/web-access/vendor/kagi.d.ts +15 -0
- package/dist/humain/web-access/vendor/kagi.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/kagi.js +262 -0
- package/dist/humain/web-access/vendor/kagi.js.map +1 -0
- package/dist/humain/web-access/vendor/ollama.d.ts +15 -0
- package/dist/humain/web-access/vendor/ollama.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/ollama.js +216 -0
- package/dist/humain/web-access/vendor/ollama.js.map +1 -0
- package/dist/humain/web-access/vendor/openai-search.d.ts +15 -0
- package/dist/humain/web-access/vendor/openai-search.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/openai-search.js +459 -0
- package/dist/humain/web-access/vendor/openai-search.js.map +1 -0
- package/dist/humain/web-access/vendor/page-query.d.ts +16 -0
- package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/page-query.js +79 -0
- package/dist/humain/web-access/vendor/page-query.js.map +1 -0
- package/dist/humain/web-access/vendor/parallel.d.ts +12 -0
- package/dist/humain/web-access/vendor/parallel.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/parallel.js +343 -0
- package/dist/humain/web-access/vendor/parallel.js.map +1 -0
- package/dist/humain/web-access/vendor/pdf-extract.d.ts +44 -0
- package/dist/humain/web-access/vendor/pdf-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/pdf-extract.js +298 -0
- package/dist/humain/web-access/vendor/pdf-extract.js.map +1 -0
- package/dist/humain/web-access/vendor/perplexity.d.ts +20 -0
- package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/perplexity.js +159 -0
- package/dist/humain/web-access/vendor/perplexity.js.map +1 -0
- package/dist/humain/web-access/vendor/querit.d.ts +10 -0
- package/dist/humain/web-access/vendor/querit.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/querit.js +335 -0
- package/dist/humain/web-access/vendor/querit.js.map +1 -0
- package/dist/humain/web-access/vendor/render-search-error.d.ts +57 -0
- package/dist/humain/web-access/vendor/render-search-error.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/render-search-error.js +130 -0
- package/dist/humain/web-access/vendor/render-search-error.js.map +1 -0
- package/dist/humain/web-access/vendor/rsc-extract.d.ts +12 -0
- package/dist/humain/web-access/vendor/rsc-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/rsc-extract.js +329 -0
- package/dist/humain/web-access/vendor/rsc-extract.js.map +1 -0
- package/dist/humain/web-access/vendor/search1api.d.ts +10 -0
- package/dist/humain/web-access/vendor/search1api.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/search1api.js +251 -0
- package/dist/humain/web-access/vendor/search1api.js.map +1 -0
- package/dist/humain/web-access/vendor/searchinfinity.d.ts +8 -0
- package/dist/humain/web-access/vendor/searchinfinity.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/searchinfinity.js +229 -0
- package/dist/humain/web-access/vendor/searchinfinity.js.map +1 -0
- package/dist/humain/web-access/vendor/searxng.d.ts +4 -0
- package/dist/humain/web-access/vendor/searxng.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/searxng.js +238 -0
- package/dist/humain/web-access/vendor/searxng.js.map +1 -0
- package/dist/humain/web-access/vendor/serpbase.d.ts +4 -0
- package/dist/humain/web-access/vendor/serpbase.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/serpbase.js +211 -0
- package/dist/humain/web-access/vendor/serpbase.js.map +1 -0
- package/dist/humain/web-access/vendor/serpdive.d.ts +8 -0
- package/dist/humain/web-access/vendor/serpdive.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/serpdive.js +267 -0
- package/dist/humain/web-access/vendor/serpdive.js.map +1 -0
- package/dist/humain/web-access/vendor/source-check.d.ts +99 -0
- package/dist/humain/web-access/vendor/source-check.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/source-check.js +205 -0
- package/dist/humain/web-access/vendor/source-check.js.map +1 -0
- package/dist/humain/web-access/vendor/ssrf-protection.d.ts +50 -0
- package/dist/humain/web-access/vendor/ssrf-protection.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/ssrf-protection.js +466 -0
- package/dist/humain/web-access/vendor/ssrf-protection.js.map +1 -0
- package/dist/humain/web-access/vendor/storage.d.ts +55 -0
- package/dist/humain/web-access/vendor/storage.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/storage.js +485 -0
- package/dist/humain/web-access/vendor/storage.js.map +1 -0
- package/dist/humain/web-access/vendor/summary-model-scope.d.ts +25 -0
- package/dist/humain/web-access/vendor/summary-model-scope.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/summary-model-scope.js +98 -0
- package/dist/humain/web-access/vendor/summary-model-scope.js.map +1 -0
- package/dist/humain/web-access/vendor/summary-review.d.ts +26 -0
- package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/summary-review.js +344 -0
- package/dist/humain/web-access/vendor/summary-review.js.map +1 -0
- package/dist/humain/web-access/vendor/tavily.d.ts +8 -0
- package/dist/humain/web-access/vendor/tavily.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/tavily.js +194 -0
- package/dist/humain/web-access/vendor/tavily.js.map +1 -0
- package/dist/humain/web-access/vendor/tinyfish.d.ts +11 -0
- package/dist/humain/web-access/vendor/tinyfish.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/tinyfish.js +331 -0
- package/dist/humain/web-access/vendor/tinyfish.js.map +1 -0
- package/dist/humain/web-access/vendor/utils.d.ts +20 -0
- package/dist/humain/web-access/vendor/utils.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/utils.js +91 -0
- package/dist/humain/web-access/vendor/utils.js.map +1 -0
- package/dist/humain/web-access/vendor/video-extract.d.ts +16 -0
- package/dist/humain/web-access/vendor/video-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/video-extract.js +335 -0
- package/dist/humain/web-access/vendor/video-extract.js.map +1 -0
- package/dist/humain/web-access/vendor/xai-search.d.ts +13 -0
- package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/xai-search.js +331 -0
- package/dist/humain/web-access/vendor/xai-search.js.map +1 -0
- package/dist/humain/web-access/vendor/youtube-extract.d.ts +27 -0
- package/dist/humain/web-access/vendor/youtube-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/youtube-extract.js +282 -0
- package/dist/humain/web-access/vendor/youtube-extract.js.map +1 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +2 -2
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +169 -102
- package/dist/main.js.map +1 -1
- package/dist/modes/agent-exec-mode.d.ts +14 -0
- package/dist/modes/agent-exec-mode.d.ts.map +1 -0
- package/dist/modes/agent-exec-mode.js +92 -0
- package/dist/modes/agent-exec-mode.js.map +1 -0
- package/dist/modes/index.d.ts +4 -2
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js +2 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +5 -2
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +13 -4
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +7 -0
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
- package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
- package/dist/modes/interactive/components/earendil-announcement.js +40 -0
- package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +1 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
- package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
- package/dist/modes/interactive/components/markdown-transform.js +19 -0
- package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
- package/dist/modes/interactive/components/mermaid.d.ts +11 -0
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
- package/dist/modes/interactive/components/mermaid.js +75 -0
- package/dist/modes/interactive/components/mermaid.js.map +1 -0
- package/dist/modes/interactive/components/model-selector.d.ts +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +16 -4
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +26 -0
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +8 -2
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +30 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +3 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +9 -2
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +45 -9
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +581 -211
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +1 -0
- package/dist/modes/interactive/theme/light.json +1 -0
- package/dist/modes/interactive/theme/theme-controller.d.ts +3 -0
- package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-controller.js +10 -1
- package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.json +5 -1
- package/dist/modes/interactive/theme/theme.d.ts +2 -2
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +24 -6
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/json-event.d.ts +28 -0
- package/dist/modes/json-event.d.ts.map +1 -0
- package/dist/modes/json-event.js +12 -0
- package/dist/modes/json-event.js.map +1 -0
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +12 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +12 -5
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +55 -1
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +13 -3
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +15 -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 +11 -9
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/rpc-entry.d.ts.map +1 -1
- package/dist/rpc-entry.js +3 -2
- package/dist/rpc-entry.js.map +1 -1
- package/dist/server/create-harness.d.ts +26 -0
- package/dist/server/create-harness.d.ts.map +1 -0
- package/dist/server/create-harness.js +104 -0
- package/dist/server/create-harness.js.map +1 -0
- package/dist/utils/abort.d.ts +5 -0
- package/dist/utils/abort.d.ts.map +1 -0
- package/dist/utils/abort.js +48 -0
- package/dist/utils/abort.js.map +1 -0
- package/dist/utils/clipboard.d.ts +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +22 -2
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/management-http.d.ts +23 -0
- package/dist/utils/management-http.d.ts.map +1 -0
- package/dist/utils/management-http.js +50 -0
- package/dist/utils/management-http.js.map +1 -0
- package/dist/utils/paths.d.ts +3 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +23 -1
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/tool-result-images.d.ts +19 -0
- package/dist/utils/tool-result-images.d.ts.map +1 -0
- package/dist/utils/tool-result-images.js +45 -0
- package/dist/utils/tool-result-images.js.map +1 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +13 -25
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts +4 -0
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/version-check.js +23 -5
- package/dist/utils/version-check.js.map +1 -1
- package/docs/compaction.md +2 -2
- package/docs/custom-provider.md +7 -5
- package/docs/extensions.md +30 -5
- package/docs/humain-terminal.md +21 -1
- package/docs/json.md +24 -19
- package/docs/keybindings.md +46 -14
- package/docs/models.md +32 -11
- package/docs/providers.md +9 -1
- package/docs/quickstart.md +39 -37
- package/docs/rpc.md +31 -11
- package/docs/sdk.md +21 -2
- package/docs/security.md +21 -21
- package/docs/session-format.md +14 -14
- package/docs/settings.md +4 -1
- package/docs/themes.md +5 -3
- package/docs/usage.md +7 -0
- package/examples/extensions/custom-compaction.ts +3 -18
- package/examples/extensions/custom-provider-anthropic/index.ts +5 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +5 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/handoff.ts +4 -13
- package/examples/extensions/qna.ts +5 -9
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/summarize.ts +9 -20
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/rpc-extension-ui.ts +11 -2
- package/examples/sdk/02-custom-model.ts +2 -3
- package/examples/sdk/09-api-keys-and-oauth.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/npm-shrinkwrap.json +2771 -535
- package/package.json +40 -11
- package/src/humain/mcp-adapter/UPSTREAM.md +15 -0
- package/src/humain/mcp-adapter/upstream.json +7 -0
- package/src/humain/mcp-adapter/vendor/CHANGELOG.md +673 -0
- package/src/humain/mcp-adapter/vendor/LICENSE +21 -0
- package/src/humain/web-access/UPSTREAM.md +17 -0
- package/src/humain/web-access/upstream.json +23 -0
- package/src/humain/web-access/vendor/LICENSE +21 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export class ActivityMonitor {
|
|
2
|
+
entries = [];
|
|
3
|
+
maxEntries = 10;
|
|
4
|
+
listeners = new Set();
|
|
5
|
+
rateLimitInfo = { used: 0, max: 10, oldestTimestamp: null, windowMs: 60000 };
|
|
6
|
+
nextId = 1;
|
|
7
|
+
logStart(partial) {
|
|
8
|
+
const id = `act-${this.nextId++}`;
|
|
9
|
+
const entry = {
|
|
10
|
+
...partial,
|
|
11
|
+
id,
|
|
12
|
+
startTime: Date.now(),
|
|
13
|
+
status: null,
|
|
14
|
+
};
|
|
15
|
+
this.entries.push(entry);
|
|
16
|
+
if (this.entries.length > this.maxEntries) {
|
|
17
|
+
this.entries.shift();
|
|
18
|
+
}
|
|
19
|
+
this.notify();
|
|
20
|
+
return id;
|
|
21
|
+
}
|
|
22
|
+
logComplete(id, status) {
|
|
23
|
+
const entry = this.entries.find((e) => e.id === id);
|
|
24
|
+
if (entry) {
|
|
25
|
+
entry.endTime = Date.now();
|
|
26
|
+
entry.status = status;
|
|
27
|
+
this.notify();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
logError(id, error) {
|
|
31
|
+
const entry = this.entries.find((e) => e.id === id);
|
|
32
|
+
if (entry) {
|
|
33
|
+
entry.endTime = Date.now();
|
|
34
|
+
entry.error = error;
|
|
35
|
+
this.notify();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
getEntries() {
|
|
39
|
+
return this.entries;
|
|
40
|
+
}
|
|
41
|
+
getRateLimitInfo() {
|
|
42
|
+
return this.rateLimitInfo;
|
|
43
|
+
}
|
|
44
|
+
updateRateLimit(info) {
|
|
45
|
+
this.rateLimitInfo = info;
|
|
46
|
+
this.notify();
|
|
47
|
+
}
|
|
48
|
+
onUpdate(callback) {
|
|
49
|
+
this.listeners.add(callback);
|
|
50
|
+
return () => this.listeners.delete(callback);
|
|
51
|
+
}
|
|
52
|
+
clear() {
|
|
53
|
+
this.entries = [];
|
|
54
|
+
this.rateLimitInfo = { used: 0, max: 10, oldestTimestamp: null, windowMs: 60000 };
|
|
55
|
+
this.notify();
|
|
56
|
+
}
|
|
57
|
+
notify() {
|
|
58
|
+
for (const cb of this.listeners) {
|
|
59
|
+
try {
|
|
60
|
+
cb();
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export const activityMonitor = new ActivityMonitor();
|
|
68
|
+
//# sourceMappingURL=activity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"activity.js","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/activity.ts"],"names":[],"mappings":"AAyBA,MAAM,OAAO,eAAe;IACnB,OAAO,GAAoB,EAAE,CAAC;IACrB,UAAU,GAAG,EAAE,CAAC;IACzB,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;IAClC,aAAa,GAAkB,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IAC5F,MAAM,GAAG,CAAC,CAAC;IAEnB,QAAQ,CAAC,OAA2D,EAAU;QAC7E,MAAM,EAAE,GAAG,OAAO,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;QAClC,MAAM,KAAK,GAAkB;YAC5B,GAAG,OAAO;YACV,EAAE;YACF,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;YACrB,MAAM,EAAE,IAAI;SACZ,CAAC;QACF,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzB,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;YAC3C,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACtB,CAAC;QACD,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,OAAO,EAAE,CAAC;IAAA,CACV;IAED,WAAW,CAAC,EAAU,EAAE,MAAc,EAAQ;QAC7C,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I,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;QAClF,IAAI,CAAC,MAAM,EAAE,CAAC;IAAA,CACd;IAEO,MAAM,GAAS;QACtB,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC;gBACJ,EAAE,EAAE,CAAC;YACN,CAAC;YAAC,MAAM,CAAC;YACT,CAAC;QACF,CAAC;IAAA,CACD;CACD;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["// Types\nexport interface ActivityEntry {\n\tid: string;\n\ttype: \"api\" | \"fetch\";\n\tstartTime: number;\n\tendTime?: number;\n\n\t// For API calls\n\tquery?: string;\n\n\t// For URL fetches\n\turl?: string;\n\n\t// Result - status is number (HTTP code) or null (pending/network error)\n\tstatus: number | null;\n\terror?: string;\n}\n\nexport interface RateLimitInfo {\n\tused: number;\n\tmax: number;\n\toldestTimestamp: number | null;\n\twindowMs: number;\n}\n\nexport class ActivityMonitor {\n\tprivate entries: ActivityEntry[] = [];\n\tprivate readonly maxEntries = 10;\n\tprivate listeners = new Set<() => void>();\n\tprivate rateLimitInfo: RateLimitInfo = { used: 0, max: 10, oldestTimestamp: null, windowMs: 60000 };\n\tprivate nextId = 1;\n\n\tlogStart(partial: Omit<ActivityEntry, \"id\" | \"startTime\" | \"status\">): string {\n\t\tconst id = `act-${this.nextId++}`;\n\t\tconst entry: ActivityEntry = {\n\t\t\t...partial,\n\t\t\tid,\n\t\t\tstartTime: Date.now(),\n\t\t\tstatus: null,\n\t\t};\n\t\tthis.entries.push(entry);\n\t\tif (this.entries.length > this.maxEntries) {\n\t\t\tthis.entries.shift();\n\t\t}\n\t\tthis.notify();\n\t\treturn id;\n\t}\n\n\tlogComplete(id: string, status: number): void {\n\t\tconst entry = this.entries.find((e) => e.id === id);\n\t\tif (entry) {\n\t\t\tentry.endTime = Date.now();\n\t\t\tentry.status = status;\n\t\t\tthis.notify();\n\t\t}\n\t}\n\n\tlogError(id: string, error: string): void {\n\t\tconst entry = this.entries.find((e) => e.id === id);\n\t\tif (entry) {\n\t\t\tentry.endTime = Date.now();\n\t\t\tentry.error = error;\n\t\t\tthis.notify();\n\t\t}\n\t}\n\n\tgetEntries(): readonly ActivityEntry[] {\n\t\treturn this.entries;\n\t}\n\n\tgetRateLimitInfo(): RateLimitInfo {\n\t\treturn this.rateLimitInfo;\n\t}\n\n\tupdateRateLimit(info: RateLimitInfo): void {\n\t\tthis.rateLimitInfo = info;\n\t\tthis.notify();\n\t}\n\n\tonUpdate(callback: () => void): () => void {\n\t\tthis.listeners.add(callback);\n\t\treturn () => this.listeners.delete(callback);\n\t}\n\n\tclear(): void {\n\t\tthis.entries = [];\n\t\tthis.rateLimitInfo = { used: 0, max: 10, oldestTimestamp: null, windowMs: 60000 };\n\t\tthis.notify();\n\t}\n\n\tprivate notify(): void {\n\t\tfor (const cb of this.listeners) {\n\t\t\ttry {\n\t\t\t\tcb();\n\t\t\t} catch {\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport const activityMonitor = new ActivityMonitor();\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SearchOptions, SearchResponse } from "./perplexity.ts";
|
|
2
|
+
interface AnySearchSearchOptions extends SearchOptions {
|
|
3
|
+
includeContent?: boolean;
|
|
4
|
+
}
|
|
5
|
+
export declare function isAnySearchAvailable(): boolean;
|
|
6
|
+
export declare function searchWithAnySearch(query: string, options?: AnySearchSearchOptions): Promise<SearchResponse>;
|
|
7
|
+
export {};
|
|
8
|
+
//# sourceMappingURL=anysearch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anysearch.d.ts","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/anysearch.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAmBrE,UAAU,sBAAuB,SAAQ,aAAa;IACrD,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAiGD,wBAAgB,oBAAoB,IAAI,OAAO,CAE9C;AAED,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,cAAc,CAAC,CAkEtH","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { activityMonitor } from \"./activity.ts\";\nimport type { ExtractedContent } from \"./extract.ts\";\nimport type { SearchOptions, SearchResponse } from \"./perplexity.ts\";\nimport { redactCredential, resolveCredential } from \"./credential-source.ts\";\nimport { getWebSearchConfigPath } from \"./utils.ts\";\n\nconst ANYSEARCH_API_URL = \"https://api.anysearch.com/v1/search\";\nconst CONFIG_PATH = getWebSearchConfigPath();\nconst SEARCH_TIMEOUT_MS = 30_000;\n\ninterface WebSearchConfig {\n\tanysearchApiKey?: unknown;\n}\n\ninterface AnySearchResult {\n\ttitle: string;\n\turl: string;\n\tsnippet: string;\n\tcontent: string;\n}\n\ninterface AnySearchSearchOptions extends SearchOptions {\n\tincludeContent?: boolean;\n}\n\ninterface AnySearchResponse {\n\tcode: 0;\n\tdata: {\n\t\tresults: AnySearchResult[];\n\t\tmetadata: Record<string, unknown>;\n\t};\n}\n\nlet cachedConfig: WebSearchConfig | null = null;\n\nfunction loadConfig(): WebSearchConfig {\n\tif (cachedConfig) return cachedConfig;\n\tif (!existsSync(CONFIG_PATH)) {\n\t\tcachedConfig = {};\n\t\treturn cachedConfig;\n\t}\n\n\tconst raw = readFileSync(CONFIG_PATH, \"utf-8\");\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);\n\t}\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);\n\t}\n\tcachedConfig = parsed as WebSearchConfig;\n\treturn cachedConfig;\n}\n\nasync function getApiKey(signal?: AbortSignal): Promise<string | null> {\n\treturn resolveCredential({\n\t\tprovider: \"AnySearch\",\n\t\tconfiguredValue: loadConfig().anysearchApiKey,\n\t\tenvironmentValue: process.env.ANYSEARCH_API_KEY,\n\t\tsignal,\n\t});\n}\n\nfunction normalizeCount(value: number | undefined): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) return 5;\n\treturn Math.max(1, Math.min(Math.floor(value), 20));\n}\n\nfunction errorMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n\nfunction invalidResponse(message: string): Error {\n\treturn new Error(`AnySearch API returned invalid response: ${message}`);\n}\n\nfunction parseResponse(value: unknown): AnySearchResponse {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow invalidResponse(\"expected an object envelope\");\n\t}\n\tconst envelope = value as Record<string, unknown>;\n\tif (envelope.code !== 0) throw invalidResponse(\"expected code 0\");\n\tif (!envelope.data || typeof envelope.data !== \"object\" || Array.isArray(envelope.data)) {\n\t\tthrow invalidResponse(\"expected data object\");\n\t}\n\tconst data = envelope.data as Record<string, unknown>;\n\tif (!Array.isArray(data.results)) throw invalidResponse(\"expected data.results array\");\n\tif (!data.metadata || typeof data.metadata !== \"object\" || Array.isArray(data.metadata)) {\n\t\tthrow invalidResponse(\"expected data.metadata object\");\n\t}\n\n\tconst results: AnySearchResult[] = [];\n\tfor (const [index, value] of data.results.entries()) {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\t\tthrow invalidResponse(`expected data.results[${index}] object`);\n\t\t}\n\t\tconst result = value as Record<string, unknown>;\n\t\tconst { title, url, snippet, content } = result;\n\t\tif (typeof title !== \"string\") throw invalidResponse(`expected data.results[${index}].title string`);\n\t\tif (typeof url !== \"string\") throw invalidResponse(`expected data.results[${index}].url string`);\n\t\tif (typeof snippet !== \"string\") throw invalidResponse(`expected data.results[${index}].snippet string`);\n\t\tif (typeof content !== \"string\") throw invalidResponse(`expected data.results[${index}].content string`);\n\t\tif (!url) throw invalidResponse(`expected data.results[${index}].url to be non-empty`);\n\t\tresults.push({ title, url, snippet, content });\n\t}\n\n\treturn { code: 0, data: { results, metadata: data.metadata as Record<string, unknown> } };\n}\n\nfunction buildAnswer(results: SearchResponse[\"results\"]): string {\n\treturn results\n\t\t.map((result) => result.snippet\n\t\t\t? `${result.snippet}\\nSource: ${result.title} (${result.url})`\n\t\t\t: `Source: ${result.title} (${result.url})`)\n\t\t.join(\"\\n\\n\");\n}\n\nexport function isAnySearchAvailable(): boolean {\n\treturn true;\n}\n\nexport async function searchWithAnySearch(query: string, options: AnySearchSearchOptions = {}): Promise<SearchResponse> {\n\tconst apiKey = await getApiKey(options.signal);\n\tconst numResults = normalizeCount(options.numResults);\n\tconst body = { query, max_results: numResults };\n\tconst activityId = activityMonitor.logStart({ type: \"api\", query });\n\tlet response: Response;\n\n\ttry {\n\t\tresponse = await fetch(ANYSEARCH_API_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t\tsignal: options.signal\n\t\t\t\t? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])\n\t\t\t\t: AbortSignal.timeout(SEARCH_TIMEOUT_MS),\n\t\t});\n\t} catch (err) {\n\t\tconst message = errorMessage(err);\n\t\tconst redactedMessage = redactCredential(message, apiKey);\n\t\tif (redactedMessage.toLowerCase().includes(\"abort\")) activityMonitor.logComplete(activityId, 0);\n\t\telse activityMonitor.logError(activityId, redactedMessage);\n\t\tif (redactedMessage === message) throw err;\n\t\tconst redactedError = new Error(redactedMessage);\n\t\tif (err instanceof Error) redactedError.name = err.name;\n\t\tthrow redactedError;\n\t}\n\n\tif (!response.ok) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tconst errorText = redactCredential(await response.text(), apiKey);\n\t\tthrow new Error(`AnySearch API error ${response.status}: ${errorText.slice(0, 300)}`);\n\t}\n\n\tlet rawData: unknown;\n\ttry {\n\t\trawData = await response.json();\n\t} catch (err) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tthrow new Error(`AnySearch API returned invalid JSON: ${errorMessage(err)}`);\n\t}\n\n\tlet data: AnySearchResponse;\n\ttry {\n\t\tdata = parseResponse(rawData);\n\t} catch (err) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tthrow err;\n\t}\n\n\tactivityMonitor.logComplete(activityId, response.status);\n\tconst results = data.data.results.slice(0, numResults).map((result) => ({\n\t\ttitle: result.title,\n\t\turl: result.url,\n\t\tsnippet: result.snippet,\n\t}));\n\tconst mapped: SearchResponse = { answer: buildAnswer(results), results };\n\tif (options.includeContent) {\n\t\tconst inlineContent: ExtractedContent[] = data.data.results.slice(0, numResults)\n\t\t\t.filter(result => result.content.length > 0)\n\t\t\t.map(result => ({ url: result.url, title: result.title, content: result.content, error: null }));\n\t\tif (inlineContent.length > 0) mapped.inlineContent = inlineContent;\n\t}\n\treturn mapped;\n}\n"]}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.js";
|
|
3
|
+
import { redactCredential, resolveCredential } from "./credential-source.js";
|
|
4
|
+
import { getWebSearchConfigPath } from "./utils.js";
|
|
5
|
+
const ANYSEARCH_API_URL = "https://api.anysearch.com/v1/search";
|
|
6
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
7
|
+
const SEARCH_TIMEOUT_MS = 30_000;
|
|
8
|
+
let cachedConfig = null;
|
|
9
|
+
function loadConfig() {
|
|
10
|
+
if (cachedConfig)
|
|
11
|
+
return cachedConfig;
|
|
12
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
13
|
+
cachedConfig = {};
|
|
14
|
+
return cachedConfig;
|
|
15
|
+
}
|
|
16
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
17
|
+
let parsed;
|
|
18
|
+
try {
|
|
19
|
+
parsed = JSON.parse(raw);
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
23
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
24
|
+
}
|
|
25
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
26
|
+
throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
|
|
27
|
+
}
|
|
28
|
+
cachedConfig = parsed;
|
|
29
|
+
return cachedConfig;
|
|
30
|
+
}
|
|
31
|
+
async function getApiKey(signal) {
|
|
32
|
+
return resolveCredential({
|
|
33
|
+
provider: "AnySearch",
|
|
34
|
+
configuredValue: loadConfig().anysearchApiKey,
|
|
35
|
+
environmentValue: process.env.ANYSEARCH_API_KEY,
|
|
36
|
+
signal,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function normalizeCount(value) {
|
|
40
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
41
|
+
return 5;
|
|
42
|
+
return Math.max(1, Math.min(Math.floor(value), 20));
|
|
43
|
+
}
|
|
44
|
+
function errorMessage(err) {
|
|
45
|
+
return err instanceof Error ? err.message : String(err);
|
|
46
|
+
}
|
|
47
|
+
function invalidResponse(message) {
|
|
48
|
+
return new Error(`AnySearch API returned invalid response: ${message}`);
|
|
49
|
+
}
|
|
50
|
+
function parseResponse(value) {
|
|
51
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
52
|
+
throw invalidResponse("expected an object envelope");
|
|
53
|
+
}
|
|
54
|
+
const envelope = value;
|
|
55
|
+
if (envelope.code !== 0)
|
|
56
|
+
throw invalidResponse("expected code 0");
|
|
57
|
+
if (!envelope.data || typeof envelope.data !== "object" || Array.isArray(envelope.data)) {
|
|
58
|
+
throw invalidResponse("expected data object");
|
|
59
|
+
}
|
|
60
|
+
const data = envelope.data;
|
|
61
|
+
if (!Array.isArray(data.results))
|
|
62
|
+
throw invalidResponse("expected data.results array");
|
|
63
|
+
if (!data.metadata || typeof data.metadata !== "object" || Array.isArray(data.metadata)) {
|
|
64
|
+
throw invalidResponse("expected data.metadata object");
|
|
65
|
+
}
|
|
66
|
+
const results = [];
|
|
67
|
+
for (const [index, value] of data.results.entries()) {
|
|
68
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
69
|
+
throw invalidResponse(`expected data.results[${index}] object`);
|
|
70
|
+
}
|
|
71
|
+
const result = value;
|
|
72
|
+
const { title, url, snippet, content } = result;
|
|
73
|
+
if (typeof title !== "string")
|
|
74
|
+
throw invalidResponse(`expected data.results[${index}].title string`);
|
|
75
|
+
if (typeof url !== "string")
|
|
76
|
+
throw invalidResponse(`expected data.results[${index}].url string`);
|
|
77
|
+
if (typeof snippet !== "string")
|
|
78
|
+
throw invalidResponse(`expected data.results[${index}].snippet string`);
|
|
79
|
+
if (typeof content !== "string")
|
|
80
|
+
throw invalidResponse(`expected data.results[${index}].content string`);
|
|
81
|
+
if (!url)
|
|
82
|
+
throw invalidResponse(`expected data.results[${index}].url to be non-empty`);
|
|
83
|
+
results.push({ title, url, snippet, content });
|
|
84
|
+
}
|
|
85
|
+
return { code: 0, data: { results, metadata: data.metadata } };
|
|
86
|
+
}
|
|
87
|
+
function buildAnswer(results) {
|
|
88
|
+
return results
|
|
89
|
+
.map((result) => result.snippet
|
|
90
|
+
? `${result.snippet}\nSource: ${result.title} (${result.url})`
|
|
91
|
+
: `Source: ${result.title} (${result.url})`)
|
|
92
|
+
.join("\n\n");
|
|
93
|
+
}
|
|
94
|
+
export function isAnySearchAvailable() {
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
export async function searchWithAnySearch(query, options = {}) {
|
|
98
|
+
const apiKey = await getApiKey(options.signal);
|
|
99
|
+
const numResults = normalizeCount(options.numResults);
|
|
100
|
+
const body = { query, max_results: numResults };
|
|
101
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
102
|
+
let response;
|
|
103
|
+
try {
|
|
104
|
+
response = await fetch(ANYSEARCH_API_URL, {
|
|
105
|
+
method: "POST",
|
|
106
|
+
headers: {
|
|
107
|
+
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
|
108
|
+
"Content-Type": "application/json",
|
|
109
|
+
},
|
|
110
|
+
body: JSON.stringify(body),
|
|
111
|
+
signal: options.signal
|
|
112
|
+
? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])
|
|
113
|
+
: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
const message = errorMessage(err);
|
|
118
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
119
|
+
if (redactedMessage.toLowerCase().includes("abort"))
|
|
120
|
+
activityMonitor.logComplete(activityId, 0);
|
|
121
|
+
else
|
|
122
|
+
activityMonitor.logError(activityId, redactedMessage);
|
|
123
|
+
if (redactedMessage === message)
|
|
124
|
+
throw err;
|
|
125
|
+
const redactedError = new Error(redactedMessage);
|
|
126
|
+
if (err instanceof Error)
|
|
127
|
+
redactedError.name = err.name;
|
|
128
|
+
throw redactedError;
|
|
129
|
+
}
|
|
130
|
+
if (!response.ok) {
|
|
131
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
132
|
+
const errorText = redactCredential(await response.text(), apiKey);
|
|
133
|
+
throw new Error(`AnySearch API error ${response.status}: ${errorText.slice(0, 300)}`);
|
|
134
|
+
}
|
|
135
|
+
let rawData;
|
|
136
|
+
try {
|
|
137
|
+
rawData = await response.json();
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
141
|
+
throw new Error(`AnySearch API returned invalid JSON: ${errorMessage(err)}`);
|
|
142
|
+
}
|
|
143
|
+
let data;
|
|
144
|
+
try {
|
|
145
|
+
data = parseResponse(rawData);
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
149
|
+
throw err;
|
|
150
|
+
}
|
|
151
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
152
|
+
const results = data.data.results.slice(0, numResults).map((result) => ({
|
|
153
|
+
title: result.title,
|
|
154
|
+
url: result.url,
|
|
155
|
+
snippet: result.snippet,
|
|
156
|
+
}));
|
|
157
|
+
const mapped = { answer: buildAnswer(results), results };
|
|
158
|
+
if (options.includeContent) {
|
|
159
|
+
const inlineContent = data.data.results.slice(0, numResults)
|
|
160
|
+
.filter(result => result.content.length > 0)
|
|
161
|
+
.map(result => ({ url: result.url, title: result.title, content: result.content, error: null }));
|
|
162
|
+
if (inlineContent.length > 0)
|
|
163
|
+
mapped.inlineContent = inlineContent;
|
|
164
|
+
}
|
|
165
|
+
return mapped;
|
|
166
|
+
}
|
|
167
|
+
//# sourceMappingURL=anysearch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anysearch.js","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/anysearch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,iBAAiB,GAAG,qCAAqC,CAAC;AAChE,MAAM,WAAW,GAAG,sBAAsB,EAAE,CAAC;AAC7C,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAyBjC,IAAI,YAAY,GAA2B,IAAI,CAAC;AAEhD,SAAS,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OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAClG,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC;YAAE,MAAM,CAAC,aAAa,GAAG,aAAa,CAAC;IACpE,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { activityMonitor } from \"./activity.ts\";\nimport type { ExtractedContent } from \"./extract.ts\";\nimport type { SearchOptions, SearchResponse } from \"./perplexity.ts\";\nimport { redactCredential, resolveCredential } from \"./credential-source.ts\";\nimport { getWebSearchConfigPath } from \"./utils.ts\";\n\nconst ANYSEARCH_API_URL = \"https://api.anysearch.com/v1/search\";\nconst CONFIG_PATH = getWebSearchConfigPath();\nconst SEARCH_TIMEOUT_MS = 30_000;\n\ninterface WebSearchConfig {\n\tanysearchApiKey?: unknown;\n}\n\ninterface AnySearchResult {\n\ttitle: string;\n\turl: string;\n\tsnippet: string;\n\tcontent: string;\n}\n\ninterface AnySearchSearchOptions extends SearchOptions {\n\tincludeContent?: boolean;\n}\n\ninterface AnySearchResponse {\n\tcode: 0;\n\tdata: {\n\t\tresults: AnySearchResult[];\n\t\tmetadata: Record<string, unknown>;\n\t};\n}\n\nlet cachedConfig: WebSearchConfig | null = null;\n\nfunction loadConfig(): WebSearchConfig {\n\tif (cachedConfig) return cachedConfig;\n\tif (!existsSync(CONFIG_PATH)) {\n\t\tcachedConfig = {};\n\t\treturn cachedConfig;\n\t}\n\n\tconst raw = readFileSync(CONFIG_PATH, \"utf-8\");\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);\n\t}\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);\n\t}\n\tcachedConfig = parsed as WebSearchConfig;\n\treturn cachedConfig;\n}\n\nasync function getApiKey(signal?: AbortSignal): Promise<string | null> {\n\treturn resolveCredential({\n\t\tprovider: \"AnySearch\",\n\t\tconfiguredValue: loadConfig().anysearchApiKey,\n\t\tenvironmentValue: process.env.ANYSEARCH_API_KEY,\n\t\tsignal,\n\t});\n}\n\nfunction normalizeCount(value: number | undefined): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) return 5;\n\treturn Math.max(1, Math.min(Math.floor(value), 20));\n}\n\nfunction errorMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n\nfunction invalidResponse(message: string): Error {\n\treturn new Error(`AnySearch API returned invalid response: ${message}`);\n}\n\nfunction parseResponse(value: unknown): AnySearchResponse {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow invalidResponse(\"expected an object envelope\");\n\t}\n\tconst envelope = value as Record<string, unknown>;\n\tif (envelope.code !== 0) throw invalidResponse(\"expected code 0\");\n\tif (!envelope.data || typeof envelope.data !== \"object\" || Array.isArray(envelope.data)) {\n\t\tthrow invalidResponse(\"expected data object\");\n\t}\n\tconst data = envelope.data as Record<string, unknown>;\n\tif (!Array.isArray(data.results)) throw invalidResponse(\"expected data.results array\");\n\tif (!data.metadata || typeof data.metadata !== \"object\" || Array.isArray(data.metadata)) {\n\t\tthrow invalidResponse(\"expected data.metadata object\");\n\t}\n\n\tconst results: AnySearchResult[] = [];\n\tfor (const [index, value] of data.results.entries()) {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\t\tthrow invalidResponse(`expected data.results[${index}] object`);\n\t\t}\n\t\tconst result = value as Record<string, unknown>;\n\t\tconst { title, url, snippet, content } = result;\n\t\tif (typeof title !== \"string\") throw invalidResponse(`expected data.results[${index}].title string`);\n\t\tif (typeof url !== \"string\") throw invalidResponse(`expected data.results[${index}].url string`);\n\t\tif (typeof snippet !== \"string\") throw invalidResponse(`expected data.results[${index}].snippet string`);\n\t\tif (typeof content !== \"string\") throw invalidResponse(`expected data.results[${index}].content string`);\n\t\tif (!url) throw invalidResponse(`expected data.results[${index}].url to be non-empty`);\n\t\tresults.push({ title, url, snippet, content });\n\t}\n\n\treturn { code: 0, data: { results, metadata: data.metadata as Record<string, unknown> } };\n}\n\nfunction buildAnswer(results: SearchResponse[\"results\"]): string {\n\treturn results\n\t\t.map((result) => result.snippet\n\t\t\t? `${result.snippet}\\nSource: ${result.title} (${result.url})`\n\t\t\t: `Source: ${result.title} (${result.url})`)\n\t\t.join(\"\\n\\n\");\n}\n\nexport function isAnySearchAvailable(): boolean {\n\treturn true;\n}\n\nexport async function searchWithAnySearch(query: string, options: AnySearchSearchOptions = {}): Promise<SearchResponse> {\n\tconst apiKey = await getApiKey(options.signal);\n\tconst numResults = normalizeCount(options.numResults);\n\tconst body = { query, max_results: numResults };\n\tconst activityId = activityMonitor.logStart({ type: \"api\", query });\n\tlet response: Response;\n\n\ttry {\n\t\tresponse = await fetch(ANYSEARCH_API_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t\tsignal: options.signal\n\t\t\t\t? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])\n\t\t\t\t: AbortSignal.timeout(SEARCH_TIMEOUT_MS),\n\t\t});\n\t} catch (err) {\n\t\tconst message = errorMessage(err);\n\t\tconst redactedMessage = redactCredential(message, apiKey);\n\t\tif (redactedMessage.toLowerCase().includes(\"abort\")) activityMonitor.logComplete(activityId, 0);\n\t\telse activityMonitor.logError(activityId, redactedMessage);\n\t\tif (redactedMessage === message) throw err;\n\t\tconst redactedError = new Error(redactedMessage);\n\t\tif (err instanceof Error) redactedError.name = err.name;\n\t\tthrow redactedError;\n\t}\n\n\tif (!response.ok) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tconst errorText = redactCredential(await response.text(), apiKey);\n\t\tthrow new Error(`AnySearch API error ${response.status}: ${errorText.slice(0, 300)}`);\n\t}\n\n\tlet rawData: unknown;\n\ttry {\n\t\trawData = await response.json();\n\t} catch (err) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tthrow new Error(`AnySearch API returned invalid JSON: ${errorMessage(err)}`);\n\t}\n\n\tlet data: AnySearchResponse;\n\ttry {\n\t\tdata = parseResponse(rawData);\n\t} catch (err) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tthrow err;\n\t}\n\n\tactivityMonitor.logComplete(activityId, response.status);\n\tconst results = data.data.results.slice(0, numResults).map((result) => ({\n\t\ttitle: result.title,\n\t\turl: result.url,\n\t\tsnippet: result.snippet,\n\t}));\n\tconst mapped: SearchResponse = { answer: buildAnswer(results), results };\n\tif (options.includeContent) {\n\t\tconst inlineContent: ExtractedContent[] = data.data.results.slice(0, numResults)\n\t\t\t.filter(result => result.content.length > 0)\n\t\t\t.map(result => ({ url: result.url, title: result.title, content: result.content, error: null }));\n\t\tif (inlineContent.length > 0) mapped.inlineContent = inlineContent;\n\t}\n\treturn mapped;\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type AuthFetchRequest = true | string;
|
|
2
|
+
export type AuthFetchCache = "session" | "off";
|
|
3
|
+
export interface AuthFetchProfile {
|
|
4
|
+
name: string;
|
|
5
|
+
hosts: string[];
|
|
6
|
+
chromeProfile?: string;
|
|
7
|
+
redirects: "same-origin";
|
|
8
|
+
cache: AuthFetchCache;
|
|
9
|
+
}
|
|
10
|
+
export declare function resolveAuthFetchProfile(request: AuthFetchRequest): AuthFetchProfile;
|
|
11
|
+
export declare function assertAuthFetchUrl(profile: AuthFetchProfile, rawUrl: string): URL;
|
|
12
|
+
export declare function authFetchRedirectGuard(profile: AuthFetchProfile, from: URL, to: URL): void;
|
|
13
|
+
//# sourceMappingURL=auth-fetch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-fetch.d.ts","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/auth-fetch.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,gBAAgB,GAAG,IAAI,GAAG,MAAM,CAAC;AAC7C,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,KAAK,CAAC;AAE/C,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,aAAa,CAAC;IACzB,KAAK,EAAE,cAAc,CAAC;CACtB;AAMD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,gBAAgB,GAAG,gBAAgB,CAenF;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,GAAG,GAAG,CAcjF;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,GAAG,IAAI,CAI1F","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { getWebSearchConfigPath } from \"./utils.ts\";\n\nconst WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();\nconst AUTH_PROFILE_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n\nexport type AuthFetchRequest = true | string;\nexport type AuthFetchCache = \"session\" | \"off\";\n\nexport interface AuthFetchProfile {\n\tname: string;\n\thosts: string[];\n\tchromeProfile?: string;\n\tredirects: \"same-origin\";\n\tcache: AuthFetchCache;\n}\n\ninterface AuthFetchConfigRoot {\n\tauthFetch?: unknown;\n}\n\nexport function resolveAuthFetchProfile(request: AuthFetchRequest): AuthFetchProfile {\n\tconst profiles = loadAuthFetchProfiles();\n\tif (profiles.length === 0) {\n\t\tthrow new Error(`auth requires at least one authFetch profile in ${WEB_SEARCH_CONFIG_PATH}`);\n\t}\n\tif (request === true) {\n\t\tif (profiles.length !== 1) {\n\t\t\tthrow new Error(\"auth: true requires exactly one authFetch profile; use a profile name instead\");\n\t\t}\n\t\treturn profiles[0];\n\t}\n\tconst name = request.trim();\n\tconst profile = profiles.find(candidate => candidate.name === name);\n\tif (!profile) throw new Error(`Unknown authFetch profile: ${name}`);\n\treturn profile;\n}\n\nexport function assertAuthFetchUrl(profile: AuthFetchProfile, rawUrl: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(rawUrl);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Authenticated fetch requires an HTTPS URL: ${message}`);\n\t}\n\tif (url.protocol !== \"https:\") throw new Error(\"Authenticated fetch requires an HTTPS URL\");\n\tconst hostname = normalizeHostname(url.hostname);\n\tif (!profile.hosts.some(host => hostMatches(hostname, host))) {\n\t\tthrow new Error(`URL host ${hostname} is not allowed by authFetch profile ${profile.name}`);\n\t}\n\treturn url;\n}\n\nexport function authFetchRedirectGuard(profile: AuthFetchProfile, from: URL, to: URL): void {\n\tif (profile.redirects === \"same-origin\" && to.origin !== from.origin) {\n\t\tthrow new Error(`Authenticated fetch refused cross-origin redirect: ${from.origin} -> ${to.origin}`);\n\t}\n}\n\nfunction loadAuthFetchProfiles(): AuthFetchProfile[] {\n\tif (!existsSync(WEB_SEARCH_CONFIG_PATH)) return [];\n\tconst raw = readFileSync(WEB_SEARCH_CONFIG_PATH, \"utf-8\");\n\tlet parsed: AuthFetchConfigRoot;\n\ttry {\n\t\tconst value: unknown = JSON.parse(raw);\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"expected a JSON object\");\n\t\tparsed = value as AuthFetchConfigRoot;\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);\n\t}\n\tif (parsed.authFetch === undefined || parsed.authFetch === null) return [];\n\tif (typeof parsed.authFetch !== \"object\" || Array.isArray(parsed.authFetch)) {\n\t\tthrow new Error(`authFetch in ${WEB_SEARCH_CONFIG_PATH} must be an object`);\n\t}\n\treturn Object.entries(parsed.authFetch as Record<string, unknown>).map(([name, value]) => parseProfile(name, value));\n}\n\nfunction parseProfile(name: string, value: unknown): AuthFetchProfile {\n\tif (!AUTH_PROFILE_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`authFetch profile name ${JSON.stringify(name)} must start with a letter and contain only letters, numbers, underscores, or hyphens`);\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn { name, hosts: parseHosts(value, `authFetch.${name}`), redirects: \"same-origin\", cache: \"session\" };\n\t}\n\tif (!value || typeof value !== \"object\") {\n\t\tthrow new Error(`authFetch.${name} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hosts or an object`);\n\t}\n\tconst config = value as Record<string, unknown>;\n\tif (!Array.isArray(config.hosts)) {\n\t\tthrow new Error(`authFetch.${name}.hosts in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);\n\t}\n\tconst redirects = config.redirects ?? \"same-origin\";\n\tif (redirects !== \"same-origin\") {\n\t\tthrow new Error(`authFetch.${name}.redirects in ${WEB_SEARCH_CONFIG_PATH} must be \"same-origin\"`);\n\t}\n\tconst cache = config.cache ?? \"session\";\n\tif (cache !== \"session\" && cache !== \"off\") {\n\t\tthrow new Error(`authFetch.${name}.cache in ${WEB_SEARCH_CONFIG_PATH} must be \"session\" or \"off\"`);\n\t}\n\tconst chromeProfile = parseChromeProfile(config.chromeProfile, `authFetch.${name}.chromeProfile`);\n\treturn {\n\t\tname,\n\t\thosts: parseHosts(config.hosts, `authFetch.${name}.hosts`),\n\t\t...(chromeProfile ? { chromeProfile } : {}),\n\t\tredirects,\n\t\tcache,\n\t};\n}\n\nfunction parseHosts(value: unknown[], label: string): string[] {\n\tif (value.length === 0) throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);\n\tconst hosts = value.map((entry) => {\n\t\tif (typeof entry !== \"string\") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames`);\n\t\treturn parseHost(entry, label);\n\t});\n\treturn [...new Set(hosts)];\n}\n\nfunction parseHost(value: string, label: string): string {\n\tconst host = normalizeHostname(value.trim());\n\tif (!host || host.startsWith(\".\") || host.endsWith(\".\") || /\\s|[\\\\/?:#@*]/.test(host)) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);\n\t}\n\tif (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)) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);\n\t}\n\treturn host;\n}\n\nfunction parseChromeProfile(value: unknown, label: string): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a string`);\n\tconst normalized = value.trim();\n\tif (!normalized || normalized === \".\" || normalized === \"..\" || normalized.includes(\"/\") || normalized.includes(\"\\\\\")) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a profile directory name, not a path`);\n\t}\n\treturn normalized;\n}\n\nfunction normalizeHostname(hostname: string): string {\n\treturn hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\").replace(/\\.$/, \"\");\n}\n\nfunction hostMatches(hostname: string, allowedHost: string): boolean {\n\treturn hostname === allowedHost || hostname.endsWith(`.${allowedHost}`);\n}\n"]}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { getWebSearchConfigPath } from "./utils.js";
|
|
3
|
+
const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
|
|
4
|
+
const AUTH_PROFILE_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
5
|
+
export function resolveAuthFetchProfile(request) {
|
|
6
|
+
const profiles = loadAuthFetchProfiles();
|
|
7
|
+
if (profiles.length === 0) {
|
|
8
|
+
throw new Error(`auth requires at least one authFetch profile in ${WEB_SEARCH_CONFIG_PATH}`);
|
|
9
|
+
}
|
|
10
|
+
if (request === true) {
|
|
11
|
+
if (profiles.length !== 1) {
|
|
12
|
+
throw new Error("auth: true requires exactly one authFetch profile; use a profile name instead");
|
|
13
|
+
}
|
|
14
|
+
return profiles[0];
|
|
15
|
+
}
|
|
16
|
+
const name = request.trim();
|
|
17
|
+
const profile = profiles.find(candidate => candidate.name === name);
|
|
18
|
+
if (!profile)
|
|
19
|
+
throw new Error(`Unknown authFetch profile: ${name}`);
|
|
20
|
+
return profile;
|
|
21
|
+
}
|
|
22
|
+
export function assertAuthFetchUrl(profile, rawUrl) {
|
|
23
|
+
let url;
|
|
24
|
+
try {
|
|
25
|
+
url = new URL(rawUrl);
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
29
|
+
throw new Error(`Authenticated fetch requires an HTTPS URL: ${message}`);
|
|
30
|
+
}
|
|
31
|
+
if (url.protocol !== "https:")
|
|
32
|
+
throw new Error("Authenticated fetch requires an HTTPS URL");
|
|
33
|
+
const hostname = normalizeHostname(url.hostname);
|
|
34
|
+
if (!profile.hosts.some(host => hostMatches(hostname, host))) {
|
|
35
|
+
throw new Error(`URL host ${hostname} is not allowed by authFetch profile ${profile.name}`);
|
|
36
|
+
}
|
|
37
|
+
return url;
|
|
38
|
+
}
|
|
39
|
+
export function authFetchRedirectGuard(profile, from, to) {
|
|
40
|
+
if (profile.redirects === "same-origin" && to.origin !== from.origin) {
|
|
41
|
+
throw new Error(`Authenticated fetch refused cross-origin redirect: ${from.origin} -> ${to.origin}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function loadAuthFetchProfiles() {
|
|
45
|
+
if (!existsSync(WEB_SEARCH_CONFIG_PATH))
|
|
46
|
+
return [];
|
|
47
|
+
const raw = readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8");
|
|
48
|
+
let parsed;
|
|
49
|
+
try {
|
|
50
|
+
const value = JSON.parse(raw);
|
|
51
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
52
|
+
throw new Error("expected a JSON object");
|
|
53
|
+
parsed = value;
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
57
|
+
throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
|
|
58
|
+
}
|
|
59
|
+
if (parsed.authFetch === undefined || parsed.authFetch === null)
|
|
60
|
+
return [];
|
|
61
|
+
if (typeof parsed.authFetch !== "object" || Array.isArray(parsed.authFetch)) {
|
|
62
|
+
throw new Error(`authFetch in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
|
|
63
|
+
}
|
|
64
|
+
return Object.entries(parsed.authFetch).map(([name, value]) => parseProfile(name, value));
|
|
65
|
+
}
|
|
66
|
+
function parseProfile(name, value) {
|
|
67
|
+
if (!AUTH_PROFILE_NAME_PATTERN.test(name)) {
|
|
68
|
+
throw new Error(`authFetch profile name ${JSON.stringify(name)} must start with a letter and contain only letters, numbers, underscores, or hyphens`);
|
|
69
|
+
}
|
|
70
|
+
if (Array.isArray(value)) {
|
|
71
|
+
return { name, hosts: parseHosts(value, `authFetch.${name}`), redirects: "same-origin", cache: "session" };
|
|
72
|
+
}
|
|
73
|
+
if (!value || typeof value !== "object") {
|
|
74
|
+
throw new Error(`authFetch.${name} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hosts or an object`);
|
|
75
|
+
}
|
|
76
|
+
const config = value;
|
|
77
|
+
if (!Array.isArray(config.hosts)) {
|
|
78
|
+
throw new Error(`authFetch.${name}.hosts in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);
|
|
79
|
+
}
|
|
80
|
+
const redirects = config.redirects ?? "same-origin";
|
|
81
|
+
if (redirects !== "same-origin") {
|
|
82
|
+
throw new Error(`authFetch.${name}.redirects in ${WEB_SEARCH_CONFIG_PATH} must be "same-origin"`);
|
|
83
|
+
}
|
|
84
|
+
const cache = config.cache ?? "session";
|
|
85
|
+
if (cache !== "session" && cache !== "off") {
|
|
86
|
+
throw new Error(`authFetch.${name}.cache in ${WEB_SEARCH_CONFIG_PATH} must be "session" or "off"`);
|
|
87
|
+
}
|
|
88
|
+
const chromeProfile = parseChromeProfile(config.chromeProfile, `authFetch.${name}.chromeProfile`);
|
|
89
|
+
return {
|
|
90
|
+
name,
|
|
91
|
+
hosts: parseHosts(config.hosts, `authFetch.${name}.hosts`),
|
|
92
|
+
...(chromeProfile ? { chromeProfile } : {}),
|
|
93
|
+
redirects,
|
|
94
|
+
cache,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function parseHosts(value, label) {
|
|
98
|
+
if (value.length === 0)
|
|
99
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);
|
|
100
|
+
const hosts = value.map((entry) => {
|
|
101
|
+
if (typeof entry !== "string")
|
|
102
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames`);
|
|
103
|
+
return parseHost(entry, label);
|
|
104
|
+
});
|
|
105
|
+
return [...new Set(hosts)];
|
|
106
|
+
}
|
|
107
|
+
function parseHost(value, label) {
|
|
108
|
+
const host = normalizeHostname(value.trim());
|
|
109
|
+
if (!host || host.startsWith(".") || host.endsWith(".") || /\s|[\\/?:#@*]/.test(host)) {
|
|
110
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);
|
|
111
|
+
}
|
|
112
|
+
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)) {
|
|
113
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);
|
|
114
|
+
}
|
|
115
|
+
return host;
|
|
116
|
+
}
|
|
117
|
+
function parseChromeProfile(value, label) {
|
|
118
|
+
if (value === undefined || value === null)
|
|
119
|
+
return undefined;
|
|
120
|
+
if (typeof value !== "string")
|
|
121
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a string`);
|
|
122
|
+
const normalized = value.trim();
|
|
123
|
+
if (!normalized || normalized === "." || normalized === ".." || normalized.includes("/") || normalized.includes("\\")) {
|
|
124
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a profile directory name, not a path`);
|
|
125
|
+
}
|
|
126
|
+
return normalized;
|
|
127
|
+
}
|
|
128
|
+
function normalizeHostname(hostname) {
|
|
129
|
+
return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
130
|
+
}
|
|
131
|
+
function hostMatches(hostname, allowedHost) {
|
|
132
|
+
return hostname === allowedHost || hostname.endsWith(`.${allowedHost}`);
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=auth-fetch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-fetch.js","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/auth-fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,sBAAsB,GAAG,sBAAsB,EAAE,CAAC;AACxD,MAAM,yBAAyB,GAAG,+BAA+B,CAAC;AAiBlE,MAAM,UAAU,uBAAuB,CAAC,OAAyB,EAAoB;IACpF,MAAM,QAAQ,GAAG,qB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,IAAI,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACvH,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,sBAAsB,+CAA+C,CAAC,CAAC;IACvG,CAAC;IACD,OAAO,UAAU,CAAC;AAAA,CAClB;AAED,SAAS,iBAAiB,CAAC,QAAgB,EAAU;IACpD,OAAO,QAAQ,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAAA,CACzE;AAED,SAAS,WAAW,CAAC,QAAgB,EAAE,WAAmB,EAAW;IACpE,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,WAAW,EAAE,CAAC,CAAC;AAAA,CACxE","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { getWebSearchConfigPath } from \"./utils.ts\";\n\nconst WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();\nconst AUTH_PROFILE_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n\nexport type AuthFetchRequest = true | string;\nexport type AuthFetchCache = \"session\" | \"off\";\n\nexport interface AuthFetchProfile {\n\tname: string;\n\thosts: string[];\n\tchromeProfile?: string;\n\tredirects: \"same-origin\";\n\tcache: AuthFetchCache;\n}\n\ninterface AuthFetchConfigRoot {\n\tauthFetch?: unknown;\n}\n\nexport function resolveAuthFetchProfile(request: AuthFetchRequest): AuthFetchProfile {\n\tconst profiles = loadAuthFetchProfiles();\n\tif (profiles.length === 0) {\n\t\tthrow new Error(`auth requires at least one authFetch profile in ${WEB_SEARCH_CONFIG_PATH}`);\n\t}\n\tif (request === true) {\n\t\tif (profiles.length !== 1) {\n\t\t\tthrow new Error(\"auth: true requires exactly one authFetch profile; use a profile name instead\");\n\t\t}\n\t\treturn profiles[0];\n\t}\n\tconst name = request.trim();\n\tconst profile = profiles.find(candidate => candidate.name === name);\n\tif (!profile) throw new Error(`Unknown authFetch profile: ${name}`);\n\treturn profile;\n}\n\nexport function assertAuthFetchUrl(profile: AuthFetchProfile, rawUrl: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(rawUrl);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Authenticated fetch requires an HTTPS URL: ${message}`);\n\t}\n\tif (url.protocol !== \"https:\") throw new Error(\"Authenticated fetch requires an HTTPS URL\");\n\tconst hostname = normalizeHostname(url.hostname);\n\tif (!profile.hosts.some(host => hostMatches(hostname, host))) {\n\t\tthrow new Error(`URL host ${hostname} is not allowed by authFetch profile ${profile.name}`);\n\t}\n\treturn url;\n}\n\nexport function authFetchRedirectGuard(profile: AuthFetchProfile, from: URL, to: URL): void {\n\tif (profile.redirects === \"same-origin\" && to.origin !== from.origin) {\n\t\tthrow new Error(`Authenticated fetch refused cross-origin redirect: ${from.origin} -> ${to.origin}`);\n\t}\n}\n\nfunction loadAuthFetchProfiles(): AuthFetchProfile[] {\n\tif (!existsSync(WEB_SEARCH_CONFIG_PATH)) return [];\n\tconst raw = readFileSync(WEB_SEARCH_CONFIG_PATH, \"utf-8\");\n\tlet parsed: AuthFetchConfigRoot;\n\ttry {\n\t\tconst value: unknown = JSON.parse(raw);\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"expected a JSON object\");\n\t\tparsed = value as AuthFetchConfigRoot;\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);\n\t}\n\tif (parsed.authFetch === undefined || parsed.authFetch === null) return [];\n\tif (typeof parsed.authFetch !== \"object\" || Array.isArray(parsed.authFetch)) {\n\t\tthrow new Error(`authFetch in ${WEB_SEARCH_CONFIG_PATH} must be an object`);\n\t}\n\treturn Object.entries(parsed.authFetch as Record<string, unknown>).map(([name, value]) => parseProfile(name, value));\n}\n\nfunction parseProfile(name: string, value: unknown): AuthFetchProfile {\n\tif (!AUTH_PROFILE_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`authFetch profile name ${JSON.stringify(name)} must start with a letter and contain only letters, numbers, underscores, or hyphens`);\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn { name, hosts: parseHosts(value, `authFetch.${name}`), redirects: \"same-origin\", cache: \"session\" };\n\t}\n\tif (!value || typeof value !== \"object\") {\n\t\tthrow new Error(`authFetch.${name} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hosts or an object`);\n\t}\n\tconst config = value as Record<string, unknown>;\n\tif (!Array.isArray(config.hosts)) {\n\t\tthrow new Error(`authFetch.${name}.hosts in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);\n\t}\n\tconst redirects = config.redirects ?? \"same-origin\";\n\tif (redirects !== \"same-origin\") {\n\t\tthrow new Error(`authFetch.${name}.redirects in ${WEB_SEARCH_CONFIG_PATH} must be \"same-origin\"`);\n\t}\n\tconst cache = config.cache ?? \"session\";\n\tif (cache !== \"session\" && cache !== \"off\") {\n\t\tthrow new Error(`authFetch.${name}.cache in ${WEB_SEARCH_CONFIG_PATH} must be \"session\" or \"off\"`);\n\t}\n\tconst chromeProfile = parseChromeProfile(config.chromeProfile, `authFetch.${name}.chromeProfile`);\n\treturn {\n\t\tname,\n\t\thosts: parseHosts(config.hosts, `authFetch.${name}.hosts`),\n\t\t...(chromeProfile ? { chromeProfile } : {}),\n\t\tredirects,\n\t\tcache,\n\t};\n}\n\nfunction parseHosts(value: unknown[], label: string): string[] {\n\tif (value.length === 0) throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);\n\tconst hosts = value.map((entry) => {\n\t\tif (typeof entry !== \"string\") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames`);\n\t\treturn parseHost(entry, label);\n\t});\n\treturn [...new Set(hosts)];\n}\n\nfunction parseHost(value: string, label: string): string {\n\tconst host = normalizeHostname(value.trim());\n\tif (!host || host.startsWith(\".\") || host.endsWith(\".\") || /\\s|[\\\\/?:#@*]/.test(host)) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);\n\t}\n\tif (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)) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);\n\t}\n\treturn host;\n}\n\nfunction parseChromeProfile(value: unknown, label: string): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a string`);\n\tconst normalized = value.trim();\n\tif (!normalized || normalized === \".\" || normalized === \"..\" || normalized.includes(\"/\") || normalized.includes(\"\\\\\")) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a profile directory name, not a path`);\n\t}\n\treturn normalized;\n}\n\nfunction normalizeHostname(hostname: string): string {\n\treturn hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\").replace(/\\.$/, \"\");\n}\n\nfunction hostMatches(hostname: string, allowedHost: string): boolean {\n\treturn hostname === allowedHost || hostname.endsWith(`.${allowedHost}`);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bocha.d.ts","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/bocha.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAoKrE,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C;AAED,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,aAAkB,GAAG,OAAO,CAAC,cAAc,CAAC,CAkDzG","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { activityMonitor } from \"./activity.ts\";\nimport type { SearchOptions, SearchResponse } from \"./perplexity.ts\";\nimport { hasCredentialSource, redactCredential, resolveCredential } from \"./credential-source.ts\";\nimport { getWebSearchConfigPath } from \"./utils.ts\";\n\nconst BOCHA_SEARCH_URL = \"https://api.bochaai.com/v1/web-search\";\nconst CONFIG_PATH = getWebSearchConfigPath();\nconst SEARCH_TIMEOUT_MS = 60_000;\n\ninterface WebSearchConfig {\n\tbochaApiKey?: unknown;\n}\n\nlet cachedConfig: WebSearchConfig | null = null;\n\nfunction loadConfig(): WebSearchConfig {\n\tif (cachedConfig) return cachedConfig;\n\tif (!existsSync(CONFIG_PATH)) {\n\t\tcachedConfig = {};\n\t\treturn cachedConfig;\n\t}\n\tconst raw = readFileSync(CONFIG_PATH, \"utf-8\");\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);\n\t}\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);\n\t}\n\tcachedConfig = parsed as WebSearchConfig;\n\treturn cachedConfig;\n}\n\nasync function getApiKey(signal?: AbortSignal): Promise<string | null> {\n\treturn resolveCredential({\n\t\tprovider: \"Bocha\",\n\t\tconfiguredValue: loadConfig().bochaApiKey,\n\t\tenvironmentValue: process.env.BOCHA_API_KEY,\n\t\tsignal,\n\t});\n}\n\nasync function requireApiKey(signal?: AbortSignal): Promise<string> {\n\tconst apiKey = await getApiKey(signal);\n\tif (!apiKey) {\n\t\tthrow new Error(\n\t\t\t\"Bocha API key not found. Either:\\n\" +\n\t\t\t` 1. Create ${CONFIG_PATH} with { \"bochaApiKey\": \"your-key\" }\\n` +\n\t\t\t\" 2. Set BOCHA_API_KEY environment variable\\n\" +\n\t\t\t\"Create a key at https://open.bochaai.com/\",\n\t\t);\n\t}\n\treturn apiKey;\n}\n\nfunction normalizeCount(value: number | undefined): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) return 8;\n\treturn Math.max(1, Math.min(Math.floor(value), 20));\n}\n\nfunction mapFreshness(value: SearchOptions[\"recencyFilter\"]): string {\n\tswitch (value) {\n\t\tcase \"day\": return \"oneDay\";\n\t\tcase \"week\": return \"oneWeek\";\n\t\tcase \"month\": return \"oneMonth\";\n\t\tcase \"year\": return \"oneYear\";\n\t\tdefault: return \"noLimit\";\n\t}\n}\n\ninterface DomainFilters {\n\tinclude: string[];\n\texclude: string[];\n}\n\nfunction normalizeDomain(value: string): string | null {\n\tlet input = value.trim().toLowerCase();\n\tif (!input) return null;\n\tif (input.startsWith(\"-\")) input = input.slice(1).trim();\n\tif (!input) return null;\n\ttry {\n\t\tconst parsed = input.includes(\"://\") ? new URL(input) : new URL(`https://${input}`);\n\t\tinput = parsed.hostname;\n\t} catch {\n\t\tinput = input.split(\"/\")[0]?.split(\":\")[0] ?? \"\";\n\t}\n\tinput = input.replace(/^\\.+|\\.+$/g, \"\");\n\treturn /^[a-z0-9][a-z0-9.-]*\\.[a-z]{2,}$/i.test(input) ? input : null;\n}\n\nfunction parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {\n\tconst filters: DomainFilters = { include: [], exclude: [] };\n\tfor (const raw of domainFilter ?? []) {\n\t\tconst domain = normalizeDomain(raw);\n\t\tif (!domain) continue;\n\t\tconst target = raw.trim().startsWith(\"-\") ? filters.exclude : filters.include;\n\t\tif (!target.includes(domain)) target.push(domain);\n\t}\n\treturn filters;\n}\n\nfunction passesDomainFilters(url: string, filters: DomainFilters): boolean {\n\tif (filters.include.length === 0 && filters.exclude.length === 0) return true;\n\tlet hostname: string;\n\ttry {\n\t\thostname = new URL(url).hostname.toLowerCase();\n\t} catch {\n\t\treturn false;\n\t}\n\tconst matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);\n\tif (filters.exclude.some(matches)) return false;\n\treturn filters.include.length === 0 || filters.include.some(matches);\n}\n\nfunction errorMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n\nfunction invalidResponse(message: string): Error {\n\treturn new Error(`Bocha API returned invalid response: ${message}`);\n}\n\nfunction firstString(...values: unknown[]): string | null {\n\tfor (const value of values) {\n\t\tif (typeof value === \"string\" && value.trim()) return value.trim();\n\t}\n\treturn null;\n}\n\nfunction parseSearchResponse(value: unknown): { results: SearchResponse[\"results\"] } {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw invalidResponse(\"expected an object envelope\");\n\tconst envelope = value as Record<string, unknown>;\n\tif (envelope.code !== undefined && Number(envelope.code) !== 200) {\n\t\tthrow invalidResponse(`code ${String(envelope.code)}: ${firstString(envelope.msg) ?? \"unknown error\"}`);\n\t}\n\tconst data = envelope.data;\n\tconst pages = (typeof data === \"object\" && data !== null && !Array.isArray(data))\n\t\t? (data as Record<string, unknown>).webPages\n\t\t: undefined;\n\tconst items = (typeof pages === \"object\" && pages !== null && !Array.isArray(pages))\n\t\t? (pages as Record<string, unknown>).value\n\t\t: undefined;\n\tif (!Array.isArray(items)) throw invalidResponse(\"missing data.webPages.value array\");\n\tconst results: SearchResponse[\"results\"] = [];\n\tfor (const item of items) {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n\t\tconst entry = item as Record<string, unknown>;\n\t\tconst url = firstString(entry.url, entry.link, entry.href);\n\t\tif (!url) continue;\n\t\tconst title = firstString(entry.title, entry.name) ?? url;\n\t\tconst snippet = firstString(entry.summary, entry.snippet, entry.description, entry.content) ?? \"\";\n\t\tresults.push({ title, url, snippet });\n\t}\n\treturn { results };\n}\n\nfunction buildAnswer(results: SearchResponse[\"results\"]): string {\n\treturn results.map((result) => result.snippet\n\t\t? `${result.snippet}\\nSource: ${result.title} (${result.url})`\n\t\t: `Source: ${result.title} (${result.url})`).join(\"\\n\\n\");\n}\n\nexport function isBochaAvailable(): boolean {\n\treturn hasCredentialSource({ provider: \"Bocha\", configuredValue: loadConfig().bochaApiKey, environmentValue: process.env.BOCHA_API_KEY });\n}\n\nexport async function searchWithBocha(query: string, options: SearchOptions = {}): Promise<SearchResponse> {\n\tconst apiKey = await requireApiKey(options.signal);\n\tconst numResults = normalizeCount(options.numResults);\n\tconst filters = parseDomainFilter(options.domainFilter);\n\tconst activityId = activityMonitor.logStart({ type: \"api\", query });\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(BOCHA_SEARCH_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\", Accept: \"application/json\" },\n\t\t\tbody: JSON.stringify({ query, count: numResults, freshness: mapFreshness(options.recencyFilter), summary: true }),\n\t\t\tsignal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS),\n\t\t});\n\t} catch (err) {\n\t\tconst message = errorMessage(err);\n\t\tconst redactedMessage = redactCredential(message, apiKey);\n\t\tif (redactedMessage.toLowerCase().includes(\"abort\")) activityMonitor.logComplete(activityId, 0);\n\t\telse activityMonitor.logError(activityId, redactedMessage);\n\t\tif (redactedMessage === message) throw err;\n\t\tconst redactedError = new Error(redactedMessage);\n\t\tif (err instanceof Error) redactedError.name = err.name;\n\t\tthrow redactedError;\n\t}\n\tif (!response.ok) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tconst errorText = redactCredential(await response.text(), apiKey);\n\t\tthrow new Error(`Bocha API error ${response.status}: ${errorText.slice(0, 300)}`);\n\t}\n\tlet rawData: unknown;\n\ttry {\n\t\trawData = await response.json();\n\t} catch (err) {\n\t\tactivityMonitor.logComplete(activityId, response.status);\n\t\tthrow new Error(`Bocha API returned invalid JSON: ${errorMessage(err)}`);\n\t}\n\tlet parsed: { results: SearchResponse[\"results\"] };\n\ttry {\n\t\tparsed = parseSearchResponse(rawData);\n\t} catch (err) {\n\t\tconst message = errorMessage(err);\n\t\tconst redactedMessage = redactCredential(message, apiKey);\n\t\tactivityMonitor.logError(activityId, redactedMessage);\n\t\tif (redactedMessage === message) throw err;\n\t\tconst redactedError = new Error(redactedMessage);\n\t\tif (err instanceof Error) redactedError.name = err.name;\n\t\tthrow redactedError;\n\t}\n\tactivityMonitor.logComplete(activityId, response.status);\n\tconst results = parsed.results.filter((result) => passesDomainFilters(result.url, filters)).slice(0, numResults);\n\treturn { answer: buildAnswer(results), results };\n}\n"]}
|