nova-personal-agent-server 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/bin/novapersonal-server.mjs +4 -0
- package/package.json +61 -4
- package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
- package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
- package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
- package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
- package/resources/native/codex-sandbox-probe +0 -0
- package/resources/native/project-native/nova_project_native.node +0 -0
- package/resources/native-resources-v1.json +1 -0
- package/runtime/dist/eval/demos.js +156 -0
- package/runtime/dist/eval/fixture-host.js +385 -0
- package/runtime/dist/eval/fixtures.js +319 -0
- package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
- package/runtime/dist/eval/scorecard.js +285 -0
- package/runtime/dist/eval/sim.js +43 -0
- package/runtime/dist/src/cascaded-text-provider.js +31 -0
- package/runtime/dist/src/cli.js +96 -0
- package/runtime/dist/src/composition/assembly.js +352 -0
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
- package/runtime/dist/src/composition/production-composition.js +389 -0
- package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
- package/runtime/dist/src/config/capability-registry.js +315 -0
- package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
- package/runtime/dist/src/config/coding-backends.js +8 -0
- package/runtime/dist/src/config/coding-profiles.js +98 -0
- package/runtime/dist/src/config/config.js +857 -0
- package/runtime/dist/src/config/diagnostics.js +139 -0
- package/runtime/dist/src/config/environment-contract.js +202 -0
- package/runtime/dist/src/config/self-hosted.js +23 -0
- package/runtime/dist/src/connectors/composio/client.js +195 -0
- package/runtime/dist/src/connectors/composio/google.js +208 -0
- package/runtime/dist/src/connectors/composio/index.js +334 -0
- package/runtime/dist/src/connectors/feishu/cli.js +220 -0
- package/runtime/dist/src/connectors/feishu/index.js +980 -0
- package/runtime/dist/src/connectors/macos/calendar.js +35 -0
- package/runtime/dist/src/connectors/macos/mail.js +32 -0
- package/runtime/dist/src/connectors/macos/reader.js +62 -0
- package/runtime/dist/src/conversation-voice-provider.js +41 -0
- package/runtime/dist/src/core/approval-port.js +9 -0
- package/runtime/dist/src/core/approval.js +1328 -0
- package/runtime/dist/src/core/calls.js +35 -0
- package/runtime/dist/src/core/camera-session.js +32 -0
- package/runtime/dist/src/core/causal-runtime.js +650 -0
- package/runtime/dist/src/core/clock.js +139 -0
- package/runtime/dist/src/core/context-view.js +156 -0
- package/runtime/dist/src/core/effects.js +62 -0
- package/runtime/dist/src/core/events.js +217 -0
- package/runtime/dist/src/core/executor-diagnostic.js +9 -0
- package/runtime/dist/src/core/ids.js +32 -0
- package/runtime/dist/src/core/media-store.js +104 -0
- package/runtime/dist/src/core/memory.js +296 -0
- package/runtime/dist/src/core/pending-decision.js +64 -0
- package/runtime/dist/src/core/ports.js +125 -0
- package/runtime/dist/src/core/runtime.js +1459 -0
- package/runtime/dist/src/core/schedule-tools.js +15 -0
- package/runtime/dist/src/core/sims.js +186 -0
- package/runtime/dist/src/core/slots.js +97 -0
- package/runtime/dist/src/core/source-processing-instructions.js +3 -0
- package/runtime/dist/src/core/source-processing-tools.js +12 -0
- package/runtime/dist/src/core/suggestions.js +143 -0
- package/runtime/dist/src/core/task-tools.js +22 -0
- package/runtime/dist/src/core/tool-schema.js +212 -0
- package/runtime/dist/src/core/trace.js +34 -0
- package/runtime/dist/src/core/work-tools.js +94 -0
- package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
- package/runtime/dist/src/desktop/desktop-camera.js +281 -0
- package/runtime/dist/src/desktop/desktop-control.js +140 -0
- package/runtime/dist/src/desktop/desktop-progress.js +162 -0
- package/runtime/dist/src/desktop/desktop-session.js +2106 -0
- package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
- package/runtime/dist/src/desktop/desktop-wire.js +605 -0
- package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
- package/runtime/dist/src/desktop/startup-error.js +18 -0
- package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
- package/runtime/dist/src/desktop-entry.js +106 -0
- package/runtime/dist/src/desktop.js +1092 -0
- package/runtime/dist/src/executors/acp/backends.js +105 -0
- package/runtime/dist/src/executors/acp/mcp.js +81 -0
- package/runtime/dist/src/executors/acp/preflight.js +14 -0
- package/runtime/dist/src/executors/acp/process-owner.js +112 -0
- package/runtime/dist/src/executors/acp/transport.js +760 -0
- package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
- package/runtime/dist/src/executors/agent-controller.js +244 -0
- package/runtime/dist/src/executors/autoglm.js +376 -0
- package/runtime/dist/src/executors/browser-device.js +102 -0
- package/runtime/dist/src/executors/browser.js +61 -0
- package/runtime/dist/src/executors/camera.js +101 -0
- package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
- package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
- package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
- package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
- package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
- package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
- package/runtime/dist/src/executors/codex/common.js +655 -0
- package/runtime/dist/src/executors/codex/contract.js +581 -0
- package/runtime/dist/src/executors/codex/controller.js +141 -0
- package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
- package/runtime/dist/src/executors/codex/factory.js +463 -0
- package/runtime/dist/src/executors/codex/host-config.js +238 -0
- package/runtime/dist/src/executors/codex/host.js +17 -0
- package/runtime/dist/src/executors/codex/index.js +19 -0
- package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
- package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
- package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
- package/runtime/dist/src/executors/codex/process-owner.js +398 -0
- package/runtime/dist/src/executors/codex/production-host.js +887 -0
- package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
- package/runtime/dist/src/executors/codex/protocol.js +581 -0
- package/runtime/dist/src/executors/codex/safe-json.js +87 -0
- package/runtime/dist/src/executors/codex/session-title.js +61 -0
- package/runtime/dist/src/executors/codex/shared-home.js +29 -0
- package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
- package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
- package/runtime/dist/src/executors/codex/version.js +38 -0
- package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
- package/runtime/dist/src/executors/coding/intake-model.js +103 -0
- package/runtime/dist/src/executors/coding/intake.js +824 -0
- package/runtime/dist/src/executors/coding/json-completion.js +14 -0
- package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
- package/runtime/dist/src/executors/coding/work-order.js +50 -0
- package/runtime/dist/src/executors/coding-executor.js +23 -0
- package/runtime/dist/src/executors/computer-backend.js +188 -0
- package/runtime/dist/src/executors/computer-device.js +187 -0
- package/runtime/dist/src/executors/computer-worker.js +125 -0
- package/runtime/dist/src/executors/computer.js +100 -0
- package/runtime/dist/src/executors/device-lock.js +127 -0
- package/runtime/dist/src/executors/frame-source.js +29 -0
- package/runtime/dist/src/executors/gui-evidence.js +30 -0
- package/runtime/dist/src/executors/gui-execution.js +237 -0
- package/runtime/dist/src/executors/gui-runner.js +88 -0
- package/runtime/dist/src/executors/host-executor-capability.js +12 -0
- package/runtime/dist/src/executors/index.js +13 -0
- package/runtime/dist/src/executors/mcp-client.js +198 -0
- package/runtime/dist/src/executors/mcp.js +210 -0
- package/runtime/dist/src/executors/mobile-android.js +180 -0
- package/runtime/dist/src/executors/mobile-ios.js +303 -0
- package/runtime/dist/src/executors/mobile.js +78 -0
- package/runtime/dist/src/executors/search-mcp.js +146 -0
- package/runtime/dist/src/executors/search.js +524 -0
- package/runtime/dist/src/executors/task-resources.js +38 -0
- package/runtime/dist/src/executors/vision/assess.js +296 -0
- package/runtime/dist/src/executors/vision/controller-core.js +373 -0
- package/runtime/dist/src/executors/vision/controller.js +164 -0
- package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
- package/runtime/dist/src/executors/vision.js +5 -0
- package/runtime/dist/src/executors/watcher.js +718 -0
- package/runtime/dist/src/http/bounded-response.js +37 -0
- package/runtime/dist/src/index.js +56 -0
- package/runtime/dist/src/knowledge/assembly.js +60 -0
- package/runtime/dist/src/knowledge/documents.js +520 -0
- package/runtime/dist/src/knowledge/embeddings.js +201 -0
- package/runtime/dist/src/knowledge/mcp.js +218 -0
- package/runtime/dist/src/knowledge/parse-worker.js +122 -0
- package/runtime/dist/src/knowledge/references.js +51 -0
- package/runtime/dist/src/knowledge/service.js +526 -0
- package/runtime/dist/src/knowledge/store-client.js +185 -0
- package/runtime/dist/src/knowledge/store-worker.js +843 -0
- package/runtime/dist/src/knowledge/types.js +2 -0
- package/runtime/dist/src/mcp/http-server.js +177 -0
- package/runtime/dist/src/mem0/resource.js +35 -0
- package/runtime/dist/src/mem0/store-worker.js +330 -0
- package/runtime/dist/src/memory/blackboard-session.js +205 -0
- package/runtime/dist/src/memory/blackboard-store.js +194 -0
- package/runtime/dist/src/memory/blackboard-worker.js +369 -0
- package/runtime/dist/src/memory/entry.js +39 -0
- package/runtime/dist/src/memory/factory.js +20 -0
- package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
- package/runtime/dist/src/memory/personal-memory.js +10 -0
- package/runtime/dist/src/memory/prerecall.js +20 -0
- package/runtime/dist/src/memory/provenance.js +17 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
- package/runtime/dist/src/memory/retrieval.js +235 -0
- package/runtime/dist/src/memory/sensitivity.js +261 -0
- package/runtime/dist/src/memory-ledger/models.js +98 -0
- package/runtime/dist/src/memory-ledger/store-client.js +210 -0
- package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
- package/runtime/dist/src/memory-ledger/store.js +597 -0
- package/runtime/dist/src/memory-substrate/candidates.js +16 -0
- package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
- package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
- package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
- package/runtime/dist/src/memory-substrate/migration.js +87 -0
- package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
- package/runtime/dist/src/memory-substrate/purge.js +398 -0
- package/runtime/dist/src/memory-substrate/resolution.js +32 -0
- package/runtime/dist/src/memory-substrate/resource.js +867 -0
- package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
- package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
- package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
- package/runtime/dist/src/memory-substrate/source-state.js +93 -0
- package/runtime/dist/src/memory-substrate/store.js +534 -0
- package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
- package/runtime/dist/src/memory-substrate/workspace.js +21 -0
- package/runtime/dist/src/model/jev-client.js +25 -0
- package/runtime/dist/src/model/model-adapters.js +64 -0
- package/runtime/dist/src/model/model-gateway.js +399 -0
- package/runtime/dist/src/model/model-lane.js +34 -0
- package/runtime/dist/src/model/model-purpose.js +5 -0
- package/runtime/dist/src/model/personal-writer.js +361 -0
- package/runtime/dist/src/model/proactivity.js +72 -0
- package/runtime/dist/src/model/prompting.js +279 -0
- package/runtime/dist/src/model/task-verifier.js +217 -0
- package/runtime/dist/src/model/vision-capability.js +10 -0
- package/runtime/dist/src/news/feeds.js +114 -0
- package/runtime/dist/src/news/jev-ranking.js +25 -0
- package/runtime/dist/src/news/ranking.js +26 -0
- package/runtime/dist/src/news/service.js +262 -0
- package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
- package/runtime/dist/src/notifications/adapters/nova.js +15 -0
- package/runtime/dist/src/notifications/content.js +15 -0
- package/runtime/dist/src/notifications/contracts.js +9 -0
- package/runtime/dist/src/notifications/feed.js +8 -0
- package/runtime/dist/src/notifications/service.js +412 -0
- package/runtime/dist/src/notifications/store.js +4 -0
- package/runtime/dist/src/personal-agent/app-context.js +113 -0
- package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
- package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
- package/runtime/dist/src/personal-agent/contracts.js +32 -0
- package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
- package/runtime/dist/src/personal-agent/conversations.js +187 -0
- package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2403 -0
- package/runtime/dist/src/personal-agent/intake-task.js +37 -0
- package/runtime/dist/src/personal-agent/life.js +260 -0
- package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
- package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
- package/runtime/dist/src/personal-agent/project-digests.js +242 -0
- package/runtime/dist/src/personal-agent/sampling.js +20 -0
- package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
- package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
- package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
- package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
- package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
- package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
- package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
- package/runtime/dist/src/personal-agent/source-priority.js +142 -0
- package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
- package/runtime/dist/src/personal-agent/source-walk.js +25 -0
- package/runtime/dist/src/personal-agent/sources.js +1484 -0
- package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
- package/runtime/dist/src/personal-agent/store.js +146 -0
- package/runtime/dist/src/personal-agent/task-loop.js +163 -0
- package/runtime/dist/src/personal-agent/tasks.js +920 -0
- package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
- package/runtime/dist/src/personal-agent/understanding.js +160 -0
- package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
- package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
- package/runtime/dist/src/projects/host-paths.js +133 -0
- package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
- package/runtime/dist/src/projects/project-confirmation.js +486 -0
- package/runtime/dist/src/projects/project-native-resource.js +284 -0
- package/runtime/dist/src/projects/project-node-files.js +169 -0
- package/runtime/dist/src/projects/project-root-file.js +16 -0
- package/runtime/dist/src/projects/project-state.js +504 -0
- package/runtime/dist/src/projects/project-store-files.js +1271 -0
- package/runtime/dist/src/projects/project-store.js +1345 -0
- package/runtime/dist/src/realtime/aoq.js +141 -0
- package/runtime/dist/src/realtime/bridge.js +652 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
- package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
- package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
- package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
- package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
- package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
- package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
- package/runtime/dist/src/realtime/dictation.js +28 -0
- package/runtime/dist/src/realtime/evidence.js +276 -0
- package/runtime/dist/src/realtime/floor.js +43 -0
- package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
- package/runtime/dist/src/realtime/gemini.js +517 -0
- package/runtime/dist/src/realtime/history.js +122 -0
- package/runtime/dist/src/realtime/host-delivery.js +1711 -0
- package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
- package/runtime/dist/src/realtime/memory-board.js +105 -0
- package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
- package/runtime/dist/src/realtime/playback.js +242 -0
- package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
- package/runtime/dist/src/realtime/prompt-language.js +17 -0
- package/runtime/dist/src/realtime/protocol.js +428 -0
- package/runtime/dist/src/realtime/provider-projection.js +526 -0
- package/runtime/dist/src/realtime/provider-session.js +491 -0
- package/runtime/dist/src/realtime/qwen-transport.js +144 -0
- package/runtime/dist/src/realtime/qwen.js +1377 -0
- package/runtime/dist/src/realtime/recall.js +341 -0
- package/runtime/dist/src/realtime/service-ports.js +8 -0
- package/runtime/dist/src/realtime/service-state.js +259 -0
- package/runtime/dist/src/realtime/service.js +1726 -0
- package/runtime/dist/src/realtime/session-state.js +684 -0
- package/runtime/dist/src/realtime/session.js +1976 -0
- package/runtime/dist/src/realtime/speech-prep.js +63 -0
- package/runtime/dist/src/realtime/streaming-speech.js +120 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
- package/runtime/dist/src/realtime/telemetry.js +144 -0
- package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
- package/runtime/dist/src/realtime/transport.js +8 -0
- package/runtime/dist/src/realtime/usage.js +55 -0
- package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
- package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
- package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
- package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
- package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
- package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
- package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
- package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
- package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
- package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
- package/runtime/dist/src/server/aoq-chat-server.js +497 -0
- package/runtime/dist/src/server/client-pairing.js +192 -0
- package/runtime/dist/src/server/client-protocol.js +87 -0
- package/runtime/dist/src/server/client-server.js +312 -0
- package/runtime/dist/src/server/server-config.js +72 -0
- package/runtime/dist/src/server-entry.js +135 -0
- package/runtime/dist/src/storage/bounded-json.js +63 -0
- package/runtime/dist/src/storage/native-file-lock.js +8 -0
- package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
- package/runtime/dist/src/storage/private-database.js +120 -0
- package/runtime/dist/src/text/canonical-json.js +60 -0
- package/runtime/dist/src/text/python-number.js +18 -0
- package/runtime/dist/src/text/python-text.js +92 -0
- package/runtime/dist/src/text/unicode-casefold.js +29 -0
- package/runtime/dist/src/text/unicode-normalize.js +138 -0
- package/runtime/dist/src/text/unicode-tables.js +210 -0
- package/runtime/dist/src/understanding/candidates.js +77 -0
- package/runtime/dist/src/understanding/fixture.js +7 -0
- package/runtime/dist/src/understanding/jev.js +20 -0
- package/runtime/dist/src/understanding/pipeline.js +38 -0
- package/runtime/dist/src/voicemem/store-client.js +476 -0
- package/runtime/dist/src/voicemem/store-worker.js +380 -0
- package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
- package/runtime/scripts/pair-device.mjs +109 -0
- package/src/command.mjs +48 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/** MCP is a bounded search transport; SearchAdapter remains the owner of evidence and trust. */
|
|
2
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
3
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
4
|
+
import { ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
+
import { boundedMcpFetch } from './mcp-client.js';
|
|
6
|
+
import { validateMcpEndpoint } from '../config/capability-registry.js';
|
|
7
|
+
import { TavilyTransportFailure } from './search.js';
|
|
8
|
+
export class McpSearchTransport {
|
|
9
|
+
config;
|
|
10
|
+
provider = 'mcp';
|
|
11
|
+
#active = new Set();
|
|
12
|
+
#closed = false;
|
|
13
|
+
constructor(config) {
|
|
14
|
+
this.config = config;
|
|
15
|
+
validateMcpEndpoint(config.url, config.headers);
|
|
16
|
+
}
|
|
17
|
+
async search(query, options) {
|
|
18
|
+
if (this.#closed)
|
|
19
|
+
throw new TavilyTransportFailure('transport_closed');
|
|
20
|
+
const controller = new AbortController();
|
|
21
|
+
let settled;
|
|
22
|
+
const active = { controller, done: new Promise(resolve => { settled = resolve; }) };
|
|
23
|
+
this.#active.add(active);
|
|
24
|
+
const timer = setTimeout(() => controller.abort(), this.config.timeoutMs);
|
|
25
|
+
let cleanupSignal;
|
|
26
|
+
const client = new Client({ name: 'nova-search', version: '1' });
|
|
27
|
+
const transport = new StreamableHTTPClientTransport(new URL(this.config.url), {
|
|
28
|
+
requestInit: { headers: this.config.headers },
|
|
29
|
+
reconnectionOptions: { maxRetries: 0, maxReconnectionDelay: 0, initialReconnectionDelay: 0, reconnectionDelayGrowFactor: 1 },
|
|
30
|
+
fetch: (url, init) => boundedMcpFetch(url, init, {
|
|
31
|
+
signal: cleanupSignal ?? controller.signal,
|
|
32
|
+
maxBytes: this.config.maxResultBytes,
|
|
33
|
+
failure: code => new TavilyTransportFailure(code),
|
|
34
|
+
}),
|
|
35
|
+
});
|
|
36
|
+
try {
|
|
37
|
+
const request = { signal: controller.signal, timeout: this.config.timeoutMs };
|
|
38
|
+
// SDK 1.30 Transport predates exactOptionalPropertyTypes; its concrete transport is structurally compatible at runtime.
|
|
39
|
+
await client.connect(transport, request);
|
|
40
|
+
let cursor;
|
|
41
|
+
let tool;
|
|
42
|
+
// Discovery pagination is bounded as well as each HTTP response.
|
|
43
|
+
for (let page = 0; page < 8; page += 1) {
|
|
44
|
+
// Metadata only: the SDK convenience listTools() compiles even unselected output schemas.
|
|
45
|
+
const listed = await client.request({ method: 'tools/list', params: cursor === undefined ? {} : { cursor } }, ListToolsResultSchema, request);
|
|
46
|
+
tool = listed.tools.find(item => item.name === this.config.tool);
|
|
47
|
+
if (tool !== undefined || listed.nextCursor === undefined)
|
|
48
|
+
break;
|
|
49
|
+
cursor = listed.nextCursor;
|
|
50
|
+
}
|
|
51
|
+
if (tool === undefined)
|
|
52
|
+
throw new TavilyTransportFailure('search_tool_missing');
|
|
53
|
+
const properties = tool.inputSchema.properties ?? {};
|
|
54
|
+
const queryField = ['query', 'q', 'search_query'].find(field => field in properties) ?? 'query';
|
|
55
|
+
const limitField = ['limit', 'count', 'top_k', 'max_results'].find(field => field in properties);
|
|
56
|
+
const result = await client.callTool({ name: this.config.tool, arguments: {
|
|
57
|
+
[queryField]: query, ...(limitField === undefined ? {} : { [limitField]: options.maxResults }),
|
|
58
|
+
} }, undefined, request);
|
|
59
|
+
if (Buffer.byteLength(JSON.stringify(result)) > this.config.maxResultBytes)
|
|
60
|
+
throw new TavilyTransportFailure('response_too_large');
|
|
61
|
+
return normalizeMcpSearchResult(result);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (controller.signal.aborted)
|
|
65
|
+
throw new TavilyTransportFailure('timeout');
|
|
66
|
+
if (error instanceof TavilyTransportFailure)
|
|
67
|
+
throw error;
|
|
68
|
+
throw new TavilyTransportFailure('mcp_search_failed');
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
// A timed-out call still owns its remote session. Give DELETE a separate bounded cleanup deadline.
|
|
72
|
+
cleanupSignal = AbortSignal.timeout(250);
|
|
73
|
+
try {
|
|
74
|
+
if (transport.sessionId !== undefined)
|
|
75
|
+
await transport.terminateSession();
|
|
76
|
+
}
|
|
77
|
+
catch { /* redacted */ }
|
|
78
|
+
controller.abort();
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
await client.close().catch(() => undefined);
|
|
81
|
+
this.#active.delete(active);
|
|
82
|
+
settled();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
close() {
|
|
86
|
+
this.#closed = true;
|
|
87
|
+
for (const { controller } of this.#active)
|
|
88
|
+
controller.abort();
|
|
89
|
+
return Promise.all([...this.#active].map(active => active.done)).then(() => undefined);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function record(value) {
|
|
93
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
|
|
94
|
+
}
|
|
95
|
+
function results(value, depth = 0) {
|
|
96
|
+
if (Array.isArray(value))
|
|
97
|
+
return value;
|
|
98
|
+
const object = record(value);
|
|
99
|
+
if (object === undefined || depth > 8)
|
|
100
|
+
return [];
|
|
101
|
+
for (const key of ['results', 'search_results', 'searchResults', 'items', 'pages']) {
|
|
102
|
+
if (Array.isArray(object[key]))
|
|
103
|
+
return object[key];
|
|
104
|
+
}
|
|
105
|
+
for (const key of ['result', 'data', 'web']) {
|
|
106
|
+
const nested = results(object[key], depth + 1);
|
|
107
|
+
if (nested.length > 0)
|
|
108
|
+
return nested;
|
|
109
|
+
}
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
const text = (value) => typeof value === 'string' ? value.trim() : '';
|
|
113
|
+
export function normalizeMcpSearchResult(result) {
|
|
114
|
+
if (result.isError)
|
|
115
|
+
throw new TavilyTransportFailure('search_tool_failed');
|
|
116
|
+
const content = result.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
|
|
117
|
+
let structured = result.structuredContent;
|
|
118
|
+
if (structured === undefined) {
|
|
119
|
+
try {
|
|
120
|
+
structured = JSON.parse(content);
|
|
121
|
+
}
|
|
122
|
+
catch { /* plain text links below */ }
|
|
123
|
+
}
|
|
124
|
+
const projected = results(structured).flatMap(value => {
|
|
125
|
+
const item = record(value);
|
|
126
|
+
if (item === undefined)
|
|
127
|
+
return [];
|
|
128
|
+
const url = text(item.url) || text(item.link) || text(item.href);
|
|
129
|
+
return url ? [{ url, title: text(item.title) || text(item.name) || url,
|
|
130
|
+
content: text(item.snippet) || text(item.description) || text(item.content) || text(item.text) || url }] : [];
|
|
131
|
+
});
|
|
132
|
+
if (projected.length > 0)
|
|
133
|
+
return { results: projected };
|
|
134
|
+
const links = new Map();
|
|
135
|
+
const add = (url, title) => {
|
|
136
|
+
const cleaned = url.replace(/[.,;:!?]+$/u, '');
|
|
137
|
+
if (!links.has(cleaned))
|
|
138
|
+
links.set(cleaned, { url: cleaned, title: title || cleaned, content: content.slice(0, 2000) || cleaned });
|
|
139
|
+
};
|
|
140
|
+
for (const match of content.matchAll(/\[([^\]]{1,300})\]\((https?:\/\/[^)\s]+)\)/giu))
|
|
141
|
+
add(match[2], match[1]);
|
|
142
|
+
for (const match of content.matchAll(/https?:\/\/[^\s<>()\]]+/giu))
|
|
143
|
+
add(match[0], '');
|
|
144
|
+
return { results: [...links.values()] };
|
|
145
|
+
}
|
|
146
|
+
//# sourceMappingURL=search-mcp.js.map
|
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded Tavily Search adapter.
|
|
3
|
+
*
|
|
4
|
+
* Ported from `src/nova_personal_agent/executors/search.py`. Search is an optional readonly executor:
|
|
5
|
+
* the transport owns one bounded HTTP request, the adapter owns the executor contract and evidence
|
|
6
|
+
* normalization, and neither writes Memory or speaks to the user.
|
|
7
|
+
*
|
|
8
|
+
* The reason this file is careful out of proportion to its size is that everything it returns is
|
|
9
|
+
* `untrusted_external` and reaches the model as evidence. A URL that survives canonicalization is a URL
|
|
10
|
+
* the agent may later be asked to trust; an evidence ref is an identifier the model cites. So the URL
|
|
11
|
+
* rules refuse anything ambiguous rather than normalizing it, and the refs are content digests that
|
|
12
|
+
* have to be byte-identical across both runtimes or the same search produces two different citations.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from 'node:crypto';
|
|
15
|
+
import { EnvHttpProxyAgent, fetch as undiciFetch } from 'undici';
|
|
16
|
+
import { compareCodePoints } from '../text/canonical-json.js';
|
|
17
|
+
import { handoffPolicySchema } from '../core/memory.js';
|
|
18
|
+
import { executorManifestSchema, opSpecSchema } from '../core/ports.js';
|
|
19
|
+
import { pythonFloat } from '../model/prompting.js';
|
|
20
|
+
import { codePointLengthLikePython, isPythonSpace, isWellFormed, stripLikePython, } from '../text/python-text.js';
|
|
21
|
+
import { isOtherCategory } from '../text/unicode-tables.js';
|
|
22
|
+
const PROVIDER = 'tavily';
|
|
23
|
+
const ENDPOINT = 'https://api.tavily.com/search';
|
|
24
|
+
const HTTP_TIMEOUT_S = 8;
|
|
25
|
+
/** A response larger than this is refused unread rather than buffered. */
|
|
26
|
+
const MAX_RESPONSE_BYTES = 256 * 1_024;
|
|
27
|
+
const MAX_QUERY_CHARS = 512;
|
|
28
|
+
const MAX_RESULTS = 5;
|
|
29
|
+
const MAX_TITLE_CHARS = 300;
|
|
30
|
+
const MAX_SNIPPET_CHARS = 2_000;
|
|
31
|
+
const MAX_URL_CHARS = 2_048;
|
|
32
|
+
export const SEARCH = opSpecSchema.parse({
|
|
33
|
+
name: 'search',
|
|
34
|
+
description: '搜索公开网页,返回带来源的标题、摘要和证据引用',
|
|
35
|
+
params: {
|
|
36
|
+
type: 'object',
|
|
37
|
+
properties: {
|
|
38
|
+
query: {
|
|
39
|
+
type: 'string', minLength: 1, maxLength: MAX_QUERY_CHARS, description: '要搜索的简短查询',
|
|
40
|
+
},
|
|
41
|
+
k: {
|
|
42
|
+
type: 'integer', minimum: 1, maximum: MAX_RESULTS, description: '返回结果数量,1 到 5',
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
required: ['query', 'k'],
|
|
46
|
+
additionalProperties: false,
|
|
47
|
+
},
|
|
48
|
+
readonly: true,
|
|
49
|
+
deadline_budget: 10,
|
|
50
|
+
verifies: ['search'],
|
|
51
|
+
sync_result: true,
|
|
52
|
+
});
|
|
53
|
+
export const SEARCH_POLICY = handoffPolicySchema.parse({
|
|
54
|
+
channel: 'search',
|
|
55
|
+
priority: 40,
|
|
56
|
+
wake: 'surrogate',
|
|
57
|
+
typical_latency: 3,
|
|
58
|
+
compress_watermark: 20,
|
|
59
|
+
});
|
|
60
|
+
export const SEARCH_MANIFEST = executorManifestSchema.parse({
|
|
61
|
+
name: 'search',
|
|
62
|
+
display_name: 'Search',
|
|
63
|
+
ops: [SEARCH],
|
|
64
|
+
policy: SEARCH_POLICY,
|
|
65
|
+
});
|
|
66
|
+
/** A credential-free transport observation, normalized by the adapter. */
|
|
67
|
+
export class TavilyTransportFailure extends Error {
|
|
68
|
+
code;
|
|
69
|
+
constructor(code) {
|
|
70
|
+
super(code);
|
|
71
|
+
this.name = 'TavilyTransportFailure';
|
|
72
|
+
this.code = code;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function proxyAwareFetch() {
|
|
76
|
+
const dispatcher = new EnvHttpProxyAgent();
|
|
77
|
+
return (input, init) => undiciFetch(input, { ...init, dispatcher });
|
|
78
|
+
}
|
|
79
|
+
/** One direct, bounded Tavily `/search` request with no retries. */
|
|
80
|
+
export class TavilyTransport {
|
|
81
|
+
#apiKey;
|
|
82
|
+
#fetch;
|
|
83
|
+
constructor(apiKey, options = {}) {
|
|
84
|
+
this.#apiKey = apiKey ?? '';
|
|
85
|
+
this.#fetch = options.fetch ?? proxyAwareFetch();
|
|
86
|
+
}
|
|
87
|
+
async search(query, options) {
|
|
88
|
+
// Reported as an authentication failure rather than attempted: a request with no key would leak
|
|
89
|
+
// the query to the provider for nothing.
|
|
90
|
+
if (this.#apiKey === '')
|
|
91
|
+
throw new TavilyTransportFailure('authentication');
|
|
92
|
+
const controller = new AbortController();
|
|
93
|
+
const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_S * 1_000);
|
|
94
|
+
let response;
|
|
95
|
+
try {
|
|
96
|
+
response = await this.#fetch(ENDPOINT, {
|
|
97
|
+
method: 'POST',
|
|
98
|
+
headers: {
|
|
99
|
+
Authorization: `Bearer ${this.#apiKey}`,
|
|
100
|
+
'Content-Type': 'application/json',
|
|
101
|
+
},
|
|
102
|
+
body: JSON.stringify({
|
|
103
|
+
query,
|
|
104
|
+
search_depth: 'basic',
|
|
105
|
+
max_results: options.maxResults,
|
|
106
|
+
include_answer: false,
|
|
107
|
+
include_raw_content: false,
|
|
108
|
+
include_images: false,
|
|
109
|
+
}),
|
|
110
|
+
// Never followed: a redirect from a search API is either a misconfiguration or a
|
|
111
|
+
// redirect-to-attacker, and neither is worth chasing with a bearer token attached.
|
|
112
|
+
redirect: 'manual',
|
|
113
|
+
signal: controller.signal,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
catch (cause) {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
if (cause instanceof TavilyTransportFailure)
|
|
119
|
+
throw cause;
|
|
120
|
+
if (isAbortError(cause))
|
|
121
|
+
throw new TavilyTransportFailure('timeout');
|
|
122
|
+
throw new TavilyTransportFailure('transport');
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
checkStatus(response.status);
|
|
126
|
+
const body = await readBounded(response, MAX_RESPONSE_BYTES);
|
|
127
|
+
let value;
|
|
128
|
+
try {
|
|
129
|
+
value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body));
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
throw new TavilyTransportFailure('malformed_response');
|
|
133
|
+
}
|
|
134
|
+
if (!isPlainObject(value))
|
|
135
|
+
throw new TavilyTransportFailure('malformed_response');
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
catch (cause) {
|
|
139
|
+
if (cause instanceof TavilyTransportFailure)
|
|
140
|
+
throw cause;
|
|
141
|
+
if (isAbortError(cause))
|
|
142
|
+
throw new TavilyTransportFailure('timeout');
|
|
143
|
+
throw new TavilyTransportFailure('transport');
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Map a status to a credential-free code.
|
|
152
|
+
*
|
|
153
|
+
* The distinction that matters is between codes the adapter turns into `failed` -- meaning do not
|
|
154
|
+
* retry, something is wrong with the request or the key -- and the rest, which become `unknown`.
|
|
155
|
+
*/
|
|
156
|
+
function checkStatus(status) {
|
|
157
|
+
if (status >= 300 && status < 400)
|
|
158
|
+
throw new TavilyTransportFailure('redirect');
|
|
159
|
+
if (status === 401 || status === 403)
|
|
160
|
+
throw new TavilyTransportFailure('authentication');
|
|
161
|
+
if (status === 429)
|
|
162
|
+
throw new TavilyTransportFailure('rate_limited');
|
|
163
|
+
if (status >= 500)
|
|
164
|
+
throw new TavilyTransportFailure('upstream');
|
|
165
|
+
if (status >= 400)
|
|
166
|
+
throw new TavilyTransportFailure('provider_rejected');
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Read a response body, refusing one that grows past the bound.
|
|
170
|
+
*
|
|
171
|
+
* Checked per chunk rather than from `Content-Length`, which a provider need not send and an attacker
|
|
172
|
+
* would not send honestly.
|
|
173
|
+
*/
|
|
174
|
+
async function readBounded(response, limit) {
|
|
175
|
+
const body = response.body;
|
|
176
|
+
if (body === null)
|
|
177
|
+
return new Uint8Array();
|
|
178
|
+
const reader = body.getReader();
|
|
179
|
+
const chunks = [];
|
|
180
|
+
let total = 0;
|
|
181
|
+
try {
|
|
182
|
+
for (;;) {
|
|
183
|
+
const chunk = await reader.read();
|
|
184
|
+
if (chunk.done === true)
|
|
185
|
+
break;
|
|
186
|
+
const value = chunk.value;
|
|
187
|
+
if (value === undefined)
|
|
188
|
+
continue;
|
|
189
|
+
total += value.length;
|
|
190
|
+
if (total > limit)
|
|
191
|
+
throw new TavilyTransportFailure('response_too_large');
|
|
192
|
+
chunks.push(value);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
// Released whether or not the read completed, so an abandoned response does not hold the socket.
|
|
197
|
+
reader.releaseLock();
|
|
198
|
+
}
|
|
199
|
+
const out = new Uint8Array(total);
|
|
200
|
+
let offset = 0;
|
|
201
|
+
for (const chunk of chunks) {
|
|
202
|
+
out.set(chunk, offset);
|
|
203
|
+
offset += chunk.length;
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
export class SearchAdapter {
|
|
208
|
+
manifest = SEARCH_MANIFEST;
|
|
209
|
+
#transport;
|
|
210
|
+
#provider;
|
|
211
|
+
constructor(transport) {
|
|
212
|
+
this.#transport = transport;
|
|
213
|
+
this.#provider = transport.provider ?? PROVIDER;
|
|
214
|
+
}
|
|
215
|
+
async dispatch(op, request, ctx) {
|
|
216
|
+
const fail = (outcome, code, extra = {}) => failure(outcome, code, extra, this.#provider);
|
|
217
|
+
if (op !== 'search')
|
|
218
|
+
return fail('failed', 'unknown_op');
|
|
219
|
+
const normalized = normalizeRequest(request);
|
|
220
|
+
if (normalized === null)
|
|
221
|
+
return fail('failed', 'invalid_params');
|
|
222
|
+
const { query, maxResults } = normalized;
|
|
223
|
+
// Derived from the query and the delegate, so the same question in two different delegations gets
|
|
224
|
+
// two refs -- the evidence belongs to a particular asking, not to a string.
|
|
225
|
+
const queryRef = evidenceRef('query', [
|
|
226
|
+
['provider', digestString(this.#provider)],
|
|
227
|
+
['query', digestString(query)],
|
|
228
|
+
['delegate_id', digestString(ctx.delegate.delegate_id)],
|
|
229
|
+
]);
|
|
230
|
+
let response;
|
|
231
|
+
try {
|
|
232
|
+
response = await this.#transport.search(query, { maxResults });
|
|
233
|
+
}
|
|
234
|
+
catch (cause) {
|
|
235
|
+
if (cause instanceof TavilyTransportFailure) {
|
|
236
|
+
// `failed` means do not retry: the key is wrong or the request was rejected on its merits.
|
|
237
|
+
// Everything else -- a timeout, a rate limit, an upstream fault -- is `unknown`, which leaves
|
|
238
|
+
// the door open for the model to try again.
|
|
239
|
+
const outcome = cause.code === 'authentication' || cause.code === 'provider_rejected'
|
|
240
|
+
? 'failed'
|
|
241
|
+
: 'unknown';
|
|
242
|
+
return fail(outcome, cause.code, { query, queryRef, fetchedAt: ctx.clock.now() });
|
|
243
|
+
}
|
|
244
|
+
return fail('unknown', 'adapter_exception', {
|
|
245
|
+
query,
|
|
246
|
+
queryRef,
|
|
247
|
+
fetchedAt: ctx.clock.now(),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
const fetchedAt = ctx.clock.now();
|
|
251
|
+
const results = normalizeResults(response.results, { queryRef, fetchedAt, maxResults, provider: this.#provider });
|
|
252
|
+
if (results.length === 0) {
|
|
253
|
+
// A response with nothing usable in it is not a success. Reporting `ok` with no evidence would
|
|
254
|
+
// tell the model the search worked and give it nothing to cite.
|
|
255
|
+
return fail('unknown', 'empty_evidence', { query, queryRef, fetchedAt });
|
|
256
|
+
}
|
|
257
|
+
const providerRequestId = response.request_id;
|
|
258
|
+
return {
|
|
259
|
+
outcome: 'ok',
|
|
260
|
+
trust: 'untrusted_external',
|
|
261
|
+
content: {
|
|
262
|
+
provider: this.#provider,
|
|
263
|
+
query,
|
|
264
|
+
query_ref: queryRef,
|
|
265
|
+
fetched_at: fetchedAt,
|
|
266
|
+
provider_request_id: typeof providerRequestId === 'string' ? providerRequestId : null,
|
|
267
|
+
results,
|
|
268
|
+
},
|
|
269
|
+
refs: [queryRef, ...results.map(result => result.evidence_ref)],
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function failure(outcome, code, extra = {}, provider = PROVIDER) {
|
|
274
|
+
const content = { error: code, provider };
|
|
275
|
+
if (extra.query !== undefined)
|
|
276
|
+
content.query = extra.query;
|
|
277
|
+
if (extra.queryRef !== undefined)
|
|
278
|
+
content.query_ref = extra.queryRef;
|
|
279
|
+
if (extra.fetchedAt !== undefined)
|
|
280
|
+
content.fetched_at = extra.fetchedAt;
|
|
281
|
+
return {
|
|
282
|
+
outcome,
|
|
283
|
+
trust: 'untrusted_external',
|
|
284
|
+
content,
|
|
285
|
+
refs: extra.queryRef === undefined ? [] : [extra.queryRef],
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Accept a request, or refuse it whole.
|
|
290
|
+
*
|
|
291
|
+
* The key set has to match *exactly*: an extra field means the caller and this adapter disagree about
|
|
292
|
+
* the contract, and guessing which fields to honour is how a stale caller gets silently different
|
|
293
|
+
* behaviour.
|
|
294
|
+
*/
|
|
295
|
+
function normalizeRequest(request) {
|
|
296
|
+
const keys = Object.keys(request);
|
|
297
|
+
if (keys.length !== 2 || !keys.includes('query') || !keys.includes('k'))
|
|
298
|
+
return null;
|
|
299
|
+
const rawQuery = request.query;
|
|
300
|
+
const rawMax = request.k;
|
|
301
|
+
if (typeof rawQuery !== 'string')
|
|
302
|
+
return null;
|
|
303
|
+
const query = stripLikePython(rawQuery);
|
|
304
|
+
if (query === '' || [...query].length > MAX_QUERY_CHARS)
|
|
305
|
+
return null;
|
|
306
|
+
// Integer, not float, and not a boolean -- `true` is not one result.
|
|
307
|
+
if (typeof rawMax !== 'number' || !Number.isInteger(rawMax))
|
|
308
|
+
return null;
|
|
309
|
+
if (rawMax < 1 || rawMax > MAX_RESULTS)
|
|
310
|
+
return null;
|
|
311
|
+
return { query, maxResults: rawMax };
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Turn provider results into evidence, dropping anything unusable.
|
|
315
|
+
*
|
|
316
|
+
* Provider positions are preserved, so a skipped malformed entry leaves a gap in the ranks. That is
|
|
317
|
+
* deliberate: the rank is the provider's ordering, and renumbering would claim a result was ranked
|
|
318
|
+
* higher than the provider put it.
|
|
319
|
+
*/
|
|
320
|
+
function normalizeResults(value, options) {
|
|
321
|
+
if (!Array.isArray(value))
|
|
322
|
+
return [];
|
|
323
|
+
const results = [];
|
|
324
|
+
for (const [index, raw] of value.entries()) {
|
|
325
|
+
if (results.length >= options.maxResults)
|
|
326
|
+
break;
|
|
327
|
+
const rank = index + 1;
|
|
328
|
+
if (!isPlainObject(raw))
|
|
329
|
+
continue;
|
|
330
|
+
const title = boundedText(raw.title, MAX_TITLE_CHARS);
|
|
331
|
+
const snippet = boundedText(raw.content, MAX_SNIPPET_CHARS);
|
|
332
|
+
const canonicalUrl = canonicalizeUrl(raw.url);
|
|
333
|
+
// All three or none: a result the model cannot attribute to a source is not evidence.
|
|
334
|
+
if (title === '' || snippet === '' || canonicalUrl === '')
|
|
335
|
+
continue;
|
|
336
|
+
// A lone surrogate cannot be encoded as UTF-8 at all. The oracle raises out of `_digest` and takes
|
|
337
|
+
// the whole dispatch with it; refusing the one result instead is strictly better -- the rest of the
|
|
338
|
+
// response is still usable evidence, and a crash gives the model nothing. Recorded as a divergence.
|
|
339
|
+
if (!isWellFormed(title) || !isWellFormed(snippet) || !isWellFormed(canonicalUrl))
|
|
340
|
+
continue;
|
|
341
|
+
const contentDigest = digest([
|
|
342
|
+
['canonical_url', digestString(canonicalUrl)],
|
|
343
|
+
['snippet', digestString(snippet)],
|
|
344
|
+
['title', digestString(title)],
|
|
345
|
+
]);
|
|
346
|
+
results.push({
|
|
347
|
+
rank,
|
|
348
|
+
title,
|
|
349
|
+
source_label: sourceLabel(canonicalUrl),
|
|
350
|
+
snippet,
|
|
351
|
+
canonical_url: canonicalUrl,
|
|
352
|
+
content_digest: contentDigest,
|
|
353
|
+
evidence_ref: evidenceRef('evidence', [
|
|
354
|
+
['canonical_url', digestString(canonicalUrl)],
|
|
355
|
+
['content_digest', digestString(contentDigest)],
|
|
356
|
+
// A Python `float`, so it always carries a decimal point -- even at a whole second.
|
|
357
|
+
['fetched_at', digestFloat(options.fetchedAt)],
|
|
358
|
+
['provider', digestString(options.provider)],
|
|
359
|
+
['query_ref', digestString(options.queryRef)],
|
|
360
|
+
['rank', digestInt(rank)],
|
|
361
|
+
]),
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return results;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Trim and bound one piece of provider text.
|
|
368
|
+
*
|
|
369
|
+
* `stripLikePython` rather than `trim()`: a title of a single U+001C is blank to the oracle and
|
|
370
|
+
* non-blank to `trim`, so the same provider response would drop the result in one runtime and emit a
|
|
371
|
+
* control-character title in the other. U+FEFF is the same problem in reverse.
|
|
372
|
+
*/
|
|
373
|
+
function boundedText(value, limit) {
|
|
374
|
+
if (typeof value !== 'string')
|
|
375
|
+
return '';
|
|
376
|
+
return [...stripLikePython(value)].slice(0, limit).join('');
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Canonicalize a result URL, or refuse it.
|
|
380
|
+
*
|
|
381
|
+
* This is the security boundary of the module. Everything here refuses rather than repairs, because a
|
|
382
|
+
* URL that arrives ambiguous and leaves unambiguous is a URL whose meaning this code chose -- and the
|
|
383
|
+
* agent may later be asked to act on it.
|
|
384
|
+
*
|
|
385
|
+
* Userinfo is refused outright: `https://evil.com@good.com/` reads as `good.com` to a person and
|
|
386
|
+
* resolves to `good.com` with credentials for `evil.com`, and no rendering of it is honest. Whitespace
|
|
387
|
+
* and control characters are refused for the same reason -- they let a URL display as one thing and
|
|
388
|
+
* resolve as another. Backslash, `<` and `>` are refused because browsers and parsers disagree about
|
|
389
|
+
* them.
|
|
390
|
+
*/
|
|
391
|
+
function canonicalizeUrl(value) {
|
|
392
|
+
if (typeof value !== 'string'
|
|
393
|
+
|| value === ''
|
|
394
|
+
|| codePointLengthLikePython(value) > MAX_URL_CHARS)
|
|
395
|
+
return '';
|
|
396
|
+
for (const character of value) {
|
|
397
|
+
if (isPythonSpace(character))
|
|
398
|
+
return '';
|
|
399
|
+
const codePoint = character.codePointAt(0);
|
|
400
|
+
if (codePoint !== undefined && isOtherCategory(codePoint))
|
|
401
|
+
return '';
|
|
402
|
+
}
|
|
403
|
+
if (value.includes('\\') || value.includes('<') || value.includes('>'))
|
|
404
|
+
return '';
|
|
405
|
+
// Read from the *source*, before any parser has a chance to repair it. WHATWG parsing is deliberately
|
|
406
|
+
// forgiving in three ways the oracle is not, and each forgiveness is a URL whose meaning this code
|
|
407
|
+
// would be choosing.
|
|
408
|
+
const schemeEnd = value.indexOf('://');
|
|
409
|
+
if (schemeEnd === -1)
|
|
410
|
+
return '';
|
|
411
|
+
const authorityStart = schemeEnd + 3;
|
|
412
|
+
const authorityEnd = findAuthorityEnd(value, authorityStart);
|
|
413
|
+
const authority = value.slice(authorityStart, authorityEnd);
|
|
414
|
+
// `https:///a` parses as host `a` under WHATWG and as no host at all in the oracle. An empty
|
|
415
|
+
// authority is a URL with no host, whatever a lenient parser makes of the slashes.
|
|
416
|
+
if (authority === '')
|
|
417
|
+
return '';
|
|
418
|
+
// `https://@good.com/` carries an *empty* userinfo, which WHATWG discards and the oracle refuses. The
|
|
419
|
+
// presence of the delimiter is the signal, not what precedes it.
|
|
420
|
+
if (authority.includes('@'))
|
|
421
|
+
return '';
|
|
422
|
+
let parsed;
|
|
423
|
+
try {
|
|
424
|
+
parsed = new URL(value);
|
|
425
|
+
}
|
|
426
|
+
catch {
|
|
427
|
+
return '';
|
|
428
|
+
}
|
|
429
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
430
|
+
return '';
|
|
431
|
+
if (parsed.hostname === '')
|
|
432
|
+
return '';
|
|
433
|
+
if (parsed.username !== '' || parsed.password !== '')
|
|
434
|
+
return '';
|
|
435
|
+
// Dropped, not kept: a fragment is client-side only, so two results differing by one are the same
|
|
436
|
+
// evidence and must digest the same.
|
|
437
|
+
parsed.hash = '';
|
|
438
|
+
let canonical = parsed.toString();
|
|
439
|
+
// WHATWG always writes a path, so `https://example.com` comes back as `https://example.com/` -- and
|
|
440
|
+
// `https://example.com?` as `https://example.com/?`. The oracle preserves the absence in both. These
|
|
441
|
+
// are the same resource either way, and a citation has to spell it one way.
|
|
442
|
+
if (value.slice(authorityEnd, authorityEnd + 1) !== '/') {
|
|
443
|
+
const slash = canonical.indexOf('/', value.indexOf('://') + 3);
|
|
444
|
+
if (slash !== -1 && (canonical[slash + 1] === undefined || '?#'.includes(canonical[slash + 1]))) {
|
|
445
|
+
canonical = canonical.slice(0, slash) + canonical.slice(slash + 1);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return codePointLengthLikePython(canonical) <= MAX_URL_CHARS ? canonical : '';
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* What a person sees as the source. `www.` is noise in a spoken label.
|
|
452
|
+
*
|
|
453
|
+
* The brackets around an IPv6 host are URL syntax rather than part of the address, and the oracle's
|
|
454
|
+
* `hostname` reports it without them.
|
|
455
|
+
*/
|
|
456
|
+
function sourceLabel(url) {
|
|
457
|
+
let hostname;
|
|
458
|
+
try {
|
|
459
|
+
hostname = new URL(url).hostname;
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
return '';
|
|
463
|
+
}
|
|
464
|
+
if (hostname.startsWith('[') && hostname.endsWith(']'))
|
|
465
|
+
hostname = hostname.slice(1, -1);
|
|
466
|
+
return hostname.startsWith('www.') ? hostname.slice(4) : hostname;
|
|
467
|
+
}
|
|
468
|
+
/** Where the authority ends: at the first `/`, `?`, or `#` after it, or at the end of the string. */
|
|
469
|
+
function findAuthorityEnd(value, start) {
|
|
470
|
+
for (let index = start; index < value.length; index += 1) {
|
|
471
|
+
const character = value[index];
|
|
472
|
+
if (character === '/' || character === '?' || character === '#')
|
|
473
|
+
return index;
|
|
474
|
+
}
|
|
475
|
+
return value.length;
|
|
476
|
+
}
|
|
477
|
+
export const digestString = (value) => ({ kind: 'string', value });
|
|
478
|
+
export const digestInt = (value) => ({ kind: 'int', value });
|
|
479
|
+
export const digestFloat = (value) => ({ kind: 'float', value });
|
|
480
|
+
/**
|
|
481
|
+
* A digest of an evidence value, byte-identical to the oracle's.
|
|
482
|
+
*
|
|
483
|
+
* The fields are passed as ordered pairs and sorted here, matching `sort_keys=True`. The model cites
|
|
484
|
+
* the resulting refs and Memory stores them, so a one-byte difference means the same search produces
|
|
485
|
+
* two different citations in the two runtimes.
|
|
486
|
+
*/
|
|
487
|
+
function digest(fields) {
|
|
488
|
+
return createHash('sha256').update(renderDigestBody(fields), 'utf8').digest('hex');
|
|
489
|
+
}
|
|
490
|
+
function evidenceRef(kind, fields) {
|
|
491
|
+
return `web.search://${kind}/${digest(fields)}`;
|
|
492
|
+
}
|
|
493
|
+
function renderDigestBody(fields) {
|
|
494
|
+
const rendered = [...fields]
|
|
495
|
+
.sort((left, right) => compareCodePoints(left[0], right[0]))
|
|
496
|
+
.map(([key, value]) => `${JSON.stringify(key)}:${renderDigestValue(value)}`);
|
|
497
|
+
return `{${rendered.join(',')}}`;
|
|
498
|
+
}
|
|
499
|
+
function renderDigestValue(value) {
|
|
500
|
+
if (value.kind === 'string')
|
|
501
|
+
return JSON.stringify(value.value);
|
|
502
|
+
if (value.kind === 'int') {
|
|
503
|
+
if (!Number.isInteger(value.value)) {
|
|
504
|
+
throw new TypeError(`digest int must be an integer: ${value.value}`);
|
|
505
|
+
}
|
|
506
|
+
return `${value.value}`;
|
|
507
|
+
}
|
|
508
|
+
return pythonFloat(value.value);
|
|
509
|
+
}
|
|
510
|
+
function isPlainObject(value) {
|
|
511
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
512
|
+
}
|
|
513
|
+
function isAbortError(cause) {
|
|
514
|
+
return cause instanceof Error && (cause.name === 'AbortError' || cause.name === 'TimeoutError');
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Test seams.
|
|
518
|
+
*
|
|
519
|
+
* The pinned surfaces are internal by design -- a caller has no reason to canonicalize a URL or build a
|
|
520
|
+
* digest itself -- but they are exactly what the golden compares, and a test that reimplemented them
|
|
521
|
+
* would only prove it agrees with itself.
|
|
522
|
+
*/
|
|
523
|
+
export { canonicalizeUrl as canonicalizeUrlForTest, digest as digestForTest, evidenceRef as evidenceRefForTest, normalizeRequest as normalizeRequestForTest, sourceLabel as sourceLabelForTest, };
|
|
524
|
+
//# sourceMappingURL=search.js.map
|