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,208 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { canonicalJson } from '../../text/canonical-json.js';
|
|
4
|
+
import { ComposioFailure, createComposioBudget } from './client.js';
|
|
5
|
+
const hash = (s) => createHash('sha256').update(s).digest('hex');
|
|
6
|
+
const rec = z.record(z.string(), z.unknown());
|
|
7
|
+
const text = (v, max = 100000) => { if (v === undefined || v === null)
|
|
8
|
+
return ''; if (typeof v !== 'string' || v.length > max)
|
|
9
|
+
throw new ComposioFailure('invalid_contract'); return v; };
|
|
10
|
+
const array = (v) => { if (!Array.isArray(v) || v.length > 200)
|
|
11
|
+
throw new ComposioFailure('invalid_contract'); return v; };
|
|
12
|
+
const object = (v) => { const r = rec.safeParse(v); if (!r.success)
|
|
13
|
+
throw new ComposioFailure('invalid_contract'); return r.data; };
|
|
14
|
+
function empty(kind, remoteId, status, calendar = '') {
|
|
15
|
+
return { key: hash(kind + ':' + calendar + ':' + remoteId), semanticHash: hash(status), metadata: { remote_id: remoteId, ...(calendar ? { calendar_id: calendar } : {}) }, text: '', locator: kind === 'mail' ? 'https://mail.google.com/mail/u/0/#inbox/' + encodeURIComponent(remoteId) : 'https://calendar.google.com/', observedAt: new Date().toISOString(), retentionUntil: null, kind, status };
|
|
16
|
+
}
|
|
17
|
+
export function normalizeGmailMessage(value, labels, window) {
|
|
18
|
+
const m = object(value), remoteId = text(m.messageId, 128);
|
|
19
|
+
if (!remoteId)
|
|
20
|
+
throw new ComposioFailure('invalid_contract');
|
|
21
|
+
const timestamp = Date.parse(text(m.messageTimestamp, 100)), actualLabels = array(m.labelIds).map(x => text(x, 256));
|
|
22
|
+
if (!Number.isFinite(timestamp))
|
|
23
|
+
throw new ComposioFailure('invalid_contract');
|
|
24
|
+
const item = empty('mail', remoteId, 'current');
|
|
25
|
+
item.metadata = { ...item.metadata, labels: actualLabels, thread_id: text(m.threadId, 256), sender: text(m.sender, 4000), recipients: text(m.to, 10000) };
|
|
26
|
+
if (timestamp < window.start || timestamp >= window.end || !labels.every(x => actualLabels.includes(x)))
|
|
27
|
+
return { ...item, status: 'coverage_removed' };
|
|
28
|
+
item.text = [text(m.subject, 10000), text(m.sender, 4000), text(m.to, 10000), text(m.messageText, 2 * 1024 * 1024)].join('\n');
|
|
29
|
+
item.observedAt = new Date(timestamp).toISOString();
|
|
30
|
+
item.retentionUntil = new Date(timestamp + 30 * 86400000).toISOString();
|
|
31
|
+
item.semanticHash = hash(canonicalJson({ text: item.text, at: item.observedAt }));
|
|
32
|
+
return excerpt(item);
|
|
33
|
+
}
|
|
34
|
+
export function normalizeCalendarEvent(calendar, value, calendarZone = 'UTC') {
|
|
35
|
+
const e = object(value), remoteId = text(e.id, 4096);
|
|
36
|
+
if (!remoteId)
|
|
37
|
+
throw new ComposioFailure('invalid_contract');
|
|
38
|
+
if (e.status === 'cancelled')
|
|
39
|
+
return empty('calendar', remoteId, 'provider_deleted', calendar);
|
|
40
|
+
const start = object(e.start), end = object(e.end);
|
|
41
|
+
for (const d of [start, end])
|
|
42
|
+
if (!(typeof d.date === 'string' && /^\d{4}-\d{2}-\d{2}$/u.test(d.date)) && !(typeof d.dateTime === 'string' && Number.isFinite(Date.parse(d.dateTime))))
|
|
43
|
+
throw new ComposioFailure('invalid_contract');
|
|
44
|
+
const metadata = z.record(z.string(), z.json()).parse({ calendar_id: calendar, remote_id: remoteId, start, end, recurringEventId: e.recurringEventId ?? null, originalStartTime: e.originalStartTime ?? null });
|
|
45
|
+
const item = empty('calendar', remoteId, 'current', calendar);
|
|
46
|
+
item.metadata = metadata;
|
|
47
|
+
item.text = [text(e.summary, 10000), text(e.description, 2 * 1024 * 1024), text(e.location, 4000), canonicalJson({ start, end })].join('\n');
|
|
48
|
+
item.semanticHash = hash(canonicalJson({ text: item.text, recurrence: e.recurrence ?? null, status: e.status ?? 'confirmed' }));
|
|
49
|
+
if (typeof e.updated === 'string' && Number.isFinite(Date.parse(e.updated)))
|
|
50
|
+
item.observedAt = new Date(e.updated).toISOString();
|
|
51
|
+
const endAt = typeof end.dateTime === 'string' ? Date.parse(end.dateTime) : midnight(text(end.date), typeof end.timeZone === 'string' ? end.timeZone : calendarZone);
|
|
52
|
+
item.retentionUntil = new Date(endAt + 30 * 86400000).toISOString();
|
|
53
|
+
return excerpt(item);
|
|
54
|
+
}
|
|
55
|
+
function midnight(date, timeZone) {
|
|
56
|
+
z.iso.date().parse(date);
|
|
57
|
+
const target = Date.parse(date + 'T00:00:00Z'), format = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' });
|
|
58
|
+
let result = target;
|
|
59
|
+
for (let n = 0; n < 3; n++) {
|
|
60
|
+
const p = Object.fromEntries(format.formatToParts(result).map(x => [x.type, x.value]));
|
|
61
|
+
const shown = Date.parse(`${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}:${p.second}Z`);
|
|
62
|
+
result += target - shown;
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
function excerpt(item) {
|
|
67
|
+
if (item.text.length > 99000) {
|
|
68
|
+
item.text = item.text.slice(0, 99000) + '\n[正文已截断,请打开原始来源查看完整内容]';
|
|
69
|
+
item.metadata.truncated = true;
|
|
70
|
+
}
|
|
71
|
+
return item;
|
|
72
|
+
}
|
|
73
|
+
const cursorSchema = z.object({ phase: z.enum(['snapshot', 'history']), start: z.number(), end: z.number(), calendar: z.number().int().nonnegative(), baseline: z.string().nullable(), token: z.string().max(16384).nullable(), nextToken: z.string().max(16384).nullable(), nextBaseline: z.string().nullable(), loaded: z.boolean(), pending: z.array(z.object({ id: z.string().min(1).max(256), deleted: z.boolean() })).max(200), seenTokens: z.array(z.string().max(16384)).max(200) }).strict();
|
|
74
|
+
function token(value) { if (value === null || value === undefined || value === '')
|
|
75
|
+
return null; if (typeof value !== 'string' || value.length > 16384)
|
|
76
|
+
throw new ComposioFailure('invalid_contract'); return value; }
|
|
77
|
+
export class GoogleProvider {
|
|
78
|
+
client;
|
|
79
|
+
constructor(client) {
|
|
80
|
+
this.client = client;
|
|
81
|
+
}
|
|
82
|
+
async page(verified, continuation, budget = createComposioBudget(), checkpoint = null) {
|
|
83
|
+
const scope = verified.scope, now = Date.now();
|
|
84
|
+
const fresh = { phase: checkpoint && scope.kind === 'gmail' ? 'history' : 'snapshot', start: now - scope.pastDays * 86400000, end: scope.kind === 'gmail' ? now : now + scope.futureDays * 86400000, calendar: 0, baseline: checkpoint?.historyId ?? null, token: null, nextToken: null, nextBaseline: null, loaded: false, pending: [], seenTokens: [] };
|
|
85
|
+
const parsed = cursorSchema.safeParse(continuation ?? fresh);
|
|
86
|
+
if (!parsed.success)
|
|
87
|
+
throw new ComposioFailure('invalid_cursor');
|
|
88
|
+
const c = parsed.data;
|
|
89
|
+
const read = (request) => this.client.read(verified, request, budget);
|
|
90
|
+
if (scope.kind === 'calendar') {
|
|
91
|
+
const calendar = scope.calendars[c.calendar];
|
|
92
|
+
if (!calendar)
|
|
93
|
+
throw new ComposioFailure('scope_denied');
|
|
94
|
+
const d = await read({ kind: 'calendar.list', calendarId: calendar, timeMin: new Date(c.start).toISOString(), timeMax: new Date(c.end).toISOString(), ...(c.token ? { pageToken: c.token } : {}) });
|
|
95
|
+
const objects = array(d.items).map(e => normalizeCalendarEvent(calendar, e, typeof d.timeZone === 'string' ? d.timeZone : 'UTC')), next = token(d.nextPageToken);
|
|
96
|
+
this.#advance(c, next);
|
|
97
|
+
if (!next) {
|
|
98
|
+
c.calendar++;
|
|
99
|
+
c.seenTokens = [];
|
|
100
|
+
}
|
|
101
|
+
const complete = c.calendar >= scope.calendars.length;
|
|
102
|
+
return { objects, continuation: complete ? null : c, checkpoint: null, complete, snapshot: true };
|
|
103
|
+
}
|
|
104
|
+
if (!c.baseline) {
|
|
105
|
+
const p = await read({ kind: 'gmail.profile' });
|
|
106
|
+
c.baseline = text(p.historyId, 100);
|
|
107
|
+
if (!/^\d+$/u.test(c.baseline))
|
|
108
|
+
throw new ComposioFailure('invalid_contract');
|
|
109
|
+
}
|
|
110
|
+
if (!c.loaded) {
|
|
111
|
+
if (c.phase === 'snapshot') {
|
|
112
|
+
const d = await read({ kind: 'gmail.list', after: Math.floor(c.start / 1000), before: Math.floor(c.end / 1000), ...(c.token ? { pageToken: c.token } : {}) });
|
|
113
|
+
c.pending = array(d.messages).map(x => ({ id: text(object(x).messageId, 128), deleted: false }));
|
|
114
|
+
c.nextToken = token(d.nextPageToken);
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
const d = await read({ kind: 'gmail.history', historyId: c.baseline, ...(c.token ? { pageToken: c.token } : {}) });
|
|
118
|
+
const pending = new Map();
|
|
119
|
+
for (const raw of array(d.history ?? [])) {
|
|
120
|
+
const h = object(raw);
|
|
121
|
+
for (const field of ['messages', 'messagesAdded', 'messagesDeleted', 'labelsAdded', 'labelsRemoved'])
|
|
122
|
+
for (const rawMessage of array(h[field] ?? [])) {
|
|
123
|
+
const entry = object(rawMessage), message = field === 'messages' ? entry : object(entry.message), id = text(message.id, 128);
|
|
124
|
+
if (!id)
|
|
125
|
+
throw new ComposioFailure('invalid_contract');
|
|
126
|
+
pending.set(id, field === 'messagesDeleted' || pending.get(id) === true);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (pending.size > 200)
|
|
130
|
+
throw new ComposioFailure('history_too_large');
|
|
131
|
+
c.pending = [...pending].map(([id, deleted]) => ({ id, deleted }));
|
|
132
|
+
c.nextToken = token(d.nextPageToken);
|
|
133
|
+
c.nextBaseline = text(d.historyId, 100);
|
|
134
|
+
if (!/^\d+$/u.test(c.nextBaseline))
|
|
135
|
+
throw new ComposioFailure('invalid_contract');
|
|
136
|
+
}
|
|
137
|
+
c.loaded = true;
|
|
138
|
+
}
|
|
139
|
+
const objects = [];
|
|
140
|
+
const readWindow = c.phase === 'history' ? { start: now - scope.pastDays * 86400000, end: now } : { start: c.start, end: c.end };
|
|
141
|
+
// At most eight metadata/body pairs, leaving requests for route verification and the page itself.
|
|
142
|
+
for (let n = 0; c.pending.length && n < 8 && budget.requests < 18 && Date.now() < budget.deadline - 15000;) {
|
|
143
|
+
const batch = c.pending.slice(0, Math.min(4, 8 - n, Math.floor((18 - budget.requests) / (c.phase === 'history' ? 2 : 1))));
|
|
144
|
+
if (!batch.length)
|
|
145
|
+
break;
|
|
146
|
+
n += batch.length;
|
|
147
|
+
const settled = await Promise.allSettled(batch.map(async (item) => {
|
|
148
|
+
const results = [];
|
|
149
|
+
if (item.deleted)
|
|
150
|
+
results.push(empty('mail', item.id, 'provider_deleted'));
|
|
151
|
+
else
|
|
152
|
+
try {
|
|
153
|
+
if (c.phase === 'history') {
|
|
154
|
+
const metadata = await read({ kind: 'gmail.message', messageId: item.id, format: 'metadata' });
|
|
155
|
+
const admitted = normalizeGmailMessage(metadata, scope.labels, readWindow);
|
|
156
|
+
if (admitted.status !== 'current') {
|
|
157
|
+
results.push(admitted);
|
|
158
|
+
return results;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const full = await read({ kind: 'gmail.message', messageId: item.id, format: 'full' });
|
|
162
|
+
if (full.messageId !== item.id)
|
|
163
|
+
throw new ComposioFailure('object_mismatch');
|
|
164
|
+
const normalized = normalizeGmailMessage(full, scope.labels, readWindow);
|
|
165
|
+
normalized.locator = 'https://mail.google.com/mail/?authuser=' + encodeURIComponent(verified.identity) + '#inbox/' + encodeURIComponent(item.id);
|
|
166
|
+
results.push(normalized);
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (error instanceof ComposioFailure && error.code === 'not_found')
|
|
170
|
+
results.push(empty('mail', item.id, 'provider_deleted'));
|
|
171
|
+
else
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
return results;
|
|
175
|
+
}));
|
|
176
|
+
// Only a wholly successful batch consumes IDs; a partial failure is safe to replay.
|
|
177
|
+
const failure = settled.find(result => result.status === 'rejected');
|
|
178
|
+
if (failure?.status === 'rejected')
|
|
179
|
+
throw failure.reason;
|
|
180
|
+
for (const result of settled)
|
|
181
|
+
if (result.status === 'fulfilled')
|
|
182
|
+
objects.push(...result.value);
|
|
183
|
+
c.pending.splice(0, batch.length);
|
|
184
|
+
}
|
|
185
|
+
let complete = false;
|
|
186
|
+
if (!c.pending.length) {
|
|
187
|
+
this.#advance(c, c.nextToken);
|
|
188
|
+
c.loaded = false;
|
|
189
|
+
if (!c.token) {
|
|
190
|
+
if (c.phase === 'snapshot') {
|
|
191
|
+
c.phase = 'history';
|
|
192
|
+
c.seenTokens = [];
|
|
193
|
+
}
|
|
194
|
+
else
|
|
195
|
+
complete = true;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return { objects, continuation: complete ? null : c, checkpoint: complete ? { historyId: c.nextBaseline ?? c.baseline } : null, complete, snapshot: checkpoint === null };
|
|
199
|
+
}
|
|
200
|
+
#advance(cursor, next) {
|
|
201
|
+
if (next && (cursor.seenTokens.includes(next) || cursor.seenTokens.length >= 200))
|
|
202
|
+
throw new ComposioFailure('pagination_loop');
|
|
203
|
+
if (next)
|
|
204
|
+
cursor.seenTokens.push(next);
|
|
205
|
+
cursor.token = next;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
//# sourceMappingURL=google.js.map
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { macMailScopeSchema } from '../macos/mail.js';
|
|
2
|
+
import { hostname, userInfo } from 'node:os';
|
|
3
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { ComposioClient, ComposioFailure, createComposioBudget, toolkitSchema, googleScopeSchema, bindingSchema } from './client.js';
|
|
6
|
+
import { GoogleProvider } from './google.js';
|
|
7
|
+
import { connectionSchema, sourceObjectSchema, connectorSourceId, processingGrantSchema } from '../../memory-substrate/source-state.js';
|
|
8
|
+
import { EvidenceRecordSchema } from '../../memory-substrate/store.js';
|
|
9
|
+
import { canonicalJson } from '../../text/canonical-json.js';
|
|
10
|
+
const hash = (s) => createHash('sha256').update(s).digest('hex');
|
|
11
|
+
const configSchema = z.object({ provider: z.enum(['composio', 'macos_calendar', 'macos_mail']), toolkit: z.union([toolkitSchema, z.enum(['macos_calendar', 'macos_mail'])]), userId: z.string(), authConfigId: z.string(), accountId: z.string(), identity: z.string().nullable(), selection: z.union([googleScopeSchema, macMailScopeSchema]).nullable() }).strict();
|
|
12
|
+
const stateSchema = z.object({ providerCursor: z.json().nullable(), anchor: z.number(), snapshot: z.boolean(), reconciling: z.boolean(), after: z.string().nullable(), nextCheckpoint: z.json().nullable() }).strict();
|
|
13
|
+
const checkpointSchema = z.object({ historyId: z.string().optional(), fullAt: z.number(), limited: z.boolean().optional() });
|
|
14
|
+
const inventorySchema = z.object({ connections: z.array(connectionSchema), next: z.string().nullable() });
|
|
15
|
+
/** One host owns this manager; the existing personal host lock owns its SQLite namespace. */
|
|
16
|
+
export class ComposioConnector {
|
|
17
|
+
options;
|
|
18
|
+
#timer;
|
|
19
|
+
#closed = true;
|
|
20
|
+
#active = new Map();
|
|
21
|
+
#commands = Promise.resolve();
|
|
22
|
+
#rows = [];
|
|
23
|
+
#provider;
|
|
24
|
+
constructor(options) {
|
|
25
|
+
this.options = options;
|
|
26
|
+
this.#provider = options.provider ?? (options.client instanceof ComposioClient ? new GoogleProvider(options.client) : null);
|
|
27
|
+
}
|
|
28
|
+
snapshot() { return { available: !!this.options.client, memory_available: !!this.options.memory(), local_available: !!this.options.local, mail_available: !!this.options.mail, connections: structuredClone(this.#rows) }; }
|
|
29
|
+
#memory() { const m = this.options.memory(); if (!m)
|
|
30
|
+
throw new ComposioFailure('memory_unavailable'); return m; }
|
|
31
|
+
async #get(id) {
|
|
32
|
+
const m = this.#memory();
|
|
33
|
+
if (!id.startsWith(m.prefix + 'connector:'))
|
|
34
|
+
throw new ComposioFailure('connection_unverified');
|
|
35
|
+
const c = connectionSchema.parse(await m.options.client.memory('source_connection', { action: 'get', id }));
|
|
36
|
+
configSchema.parse(c.scope);
|
|
37
|
+
return c;
|
|
38
|
+
}
|
|
39
|
+
async #list() {
|
|
40
|
+
const m = this.#memory(), result = [];
|
|
41
|
+
let after = null;
|
|
42
|
+
do {
|
|
43
|
+
const p = inventorySchema.parse(await m.options.client.memory('source_connection', { action: 'list', prefix: m.prefix + 'connector:', after, limit: 100 }));
|
|
44
|
+
result.push(...p.connections.filter(c => configSchema.safeParse(c.scope).success));
|
|
45
|
+
after = p.next;
|
|
46
|
+
} while (after && result.length < 100);
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
async #refresh() {
|
|
50
|
+
const rows = [];
|
|
51
|
+
for (const c of await this.#list()) {
|
|
52
|
+
const conf = configSchema.parse(c.scope), grant = await this.#grant(c), expected = this.#memory().processingGrant(true, grant.revision, c.fence.scope_revision);
|
|
53
|
+
rows.push({ id: c.fence.connection_id, toolkit: conf.toolkit, identity: conf.identity, state: conf.identity ? c.state : 'authorizing', scope: conf.selection, mode: conf.toolkit === 'gmail' ? 'history' : 'window_snapshot', processing_allowed: !!grant.extraction_provider && grant.extraction_provider === expected.extraction_provider && grant.embedding_provider === expected.embedding_provider, has_pending: !!c.continuation || c.deleting.length > 0, error: c.sync_status?.error ?? null, last_attempt: c.sync_status?.attempt_at ?? null, last_complete: c.sync_status?.complete_at ?? null, scan_limited: c.checkpoint !== null && checkpointSchema.parse(c.checkpoint).limited === true, checkpoint_present: !!c.checkpoint });
|
|
54
|
+
}
|
|
55
|
+
this.#rows = rows;
|
|
56
|
+
this.options.onChange();
|
|
57
|
+
}
|
|
58
|
+
async open() { this.#closed = false; if (this.options.memory()) {
|
|
59
|
+
for (const c of await this.#list())
|
|
60
|
+
if (c.deleting.length)
|
|
61
|
+
await this.#deleteStep(c.fence.connection_id);
|
|
62
|
+
await this.#refresh();
|
|
63
|
+
} this.#schedule(1000); }
|
|
64
|
+
async close() { this.#closed = true; clearTimeout(this.#timer); for (const a of this.#active.values())
|
|
65
|
+
a.abort.abort(); await Promise.allSettled([...this.#active.values()].map(x => x.promise)); await this.#commands; }
|
|
66
|
+
#schedule(delay) { if (this.#closed || this.options.automatic === false)
|
|
67
|
+
return; clearTimeout(this.#timer); this.#timer = setTimeout(() => { void this.#tick(); }, delay); this.#timer.unref(); }
|
|
68
|
+
async #tick() {
|
|
69
|
+
try {
|
|
70
|
+
const connections = await this.#list();
|
|
71
|
+
let next = 0;
|
|
72
|
+
await Promise.all(Array.from({ length: Math.min(4, connections.length) }, async () => {
|
|
73
|
+
while (next < connections.length && !this.#closed) {
|
|
74
|
+
const c = connections[next++];
|
|
75
|
+
try {
|
|
76
|
+
if (c.deleting.length) {
|
|
77
|
+
await this.#deleteStep(c.fence.connection_id);
|
|
78
|
+
await this.#refresh();
|
|
79
|
+
}
|
|
80
|
+
else if (c.state === 'connected' && (c.sync_status?.retry_at ?? 0) <= Date.now())
|
|
81
|
+
await this.#run(c.fence.connection_id);
|
|
82
|
+
}
|
|
83
|
+
catch { /* One unavailable connection must not block the others. */ }
|
|
84
|
+
}
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
catch { /* unavailable memory retries at the next tick */ }
|
|
88
|
+
this.#schedule(this.#rows.some(r => r.has_pending) ? 1000 : 60000);
|
|
89
|
+
}
|
|
90
|
+
async #deleteStep(id) { await this.#memory().options.client.memory('source_connection', { action: 'delete_step', id, limit: 200 }); }
|
|
91
|
+
command(method, params = {}) {
|
|
92
|
+
const result = this.#commands.then(() => this.#command(method, params));
|
|
93
|
+
this.#commands = result.catch(() => undefined);
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
syncOnce(id) { if (this.#closed)
|
|
97
|
+
return Promise.reject(new ComposioFailure('connector_closed')); return this.#run(id); }
|
|
98
|
+
async #command(method, params) {
|
|
99
|
+
if (this.#closed)
|
|
100
|
+
throw new ComposioFailure('connector_closed');
|
|
101
|
+
if (method === 'connector.status') {
|
|
102
|
+
await this.#refresh();
|
|
103
|
+
return this.snapshot();
|
|
104
|
+
}
|
|
105
|
+
const m = this.#memory(), client = this.options.client;
|
|
106
|
+
if (['connector.mail_status', 'connector.mail_access', 'connector.mail_connect'].includes(method)) {
|
|
107
|
+
z.object({}).strict().parse(params);
|
|
108
|
+
const mail = this.options.mail;
|
|
109
|
+
if (!mail)
|
|
110
|
+
throw new ComposioFailure('native_unavailable');
|
|
111
|
+
if (method !== 'connector.mail_connect')
|
|
112
|
+
return mail.request({ command: method === 'connector.mail_access' ? 'request_access' : 'status' });
|
|
113
|
+
if ((await mail.request({ command: 'status' })).status !== 'granted')
|
|
114
|
+
throw new ComposioFailure('permission_denied');
|
|
115
|
+
const identity = hash(hostname() + ':' + userInfo().uid), id = m.prefix + 'connector:macos-mail:' + identity.slice(0, 16);
|
|
116
|
+
if (await m.options.client.memory('source_connection', { action: 'get', id }) === null) {
|
|
117
|
+
const c = connectionSchema.parse(await m.options.client.memory('source_connection', { action: 'create', id, namespace: id }));
|
|
118
|
+
await m.options.client.memory('source_connection', { action: 'scope', id, expected_scope_revision: c.fence.scope_revision, scope: { provider: 'macos_mail', toolkit: 'macos_mail', userId: identity, authConfigId: 'local', accountId: 'local', identity: 'Apple Mail', selection: null } });
|
|
119
|
+
}
|
|
120
|
+
await this.#refresh();
|
|
121
|
+
return { id };
|
|
122
|
+
}
|
|
123
|
+
if (method === 'connector.local_status' || method === 'connector.local_access') {
|
|
124
|
+
z.object({}).strict().parse(params);
|
|
125
|
+
if (!this.options.local)
|
|
126
|
+
throw new ComposioFailure('native_unavailable');
|
|
127
|
+
return this.options.local.request({ command: method === 'connector.local_status' ? 'status' : 'request_access' });
|
|
128
|
+
}
|
|
129
|
+
if (method === 'connector.local_connect') {
|
|
130
|
+
z.object({}).strict().parse(params);
|
|
131
|
+
if (!this.options.local || (await this.options.local.request({ command: 'status' })).status !== 'granted')
|
|
132
|
+
throw new ComposioFailure('permission_denied');
|
|
133
|
+
const identity = hash(hostname() + ':' + userInfo().uid), id = m.prefix + 'connector:macos-calendar:' + identity.slice(0, 16);
|
|
134
|
+
let c = await m.options.client.memory('source_connection', { action: 'get', id });
|
|
135
|
+
if (c === null) {
|
|
136
|
+
c = await m.options.client.memory('source_connection', { action: 'create', id, namespace: id });
|
|
137
|
+
await m.options.client.memory('source_connection', { action: 'scope', id, expected_scope_revision: connectionSchema.parse(c).fence.scope_revision, scope: { provider: 'macos_calendar', toolkit: 'macos_calendar', userId: identity, authConfigId: 'local', accountId: 'local', identity: '本机日历', selection: null } });
|
|
138
|
+
}
|
|
139
|
+
await this.#refresh();
|
|
140
|
+
return { id };
|
|
141
|
+
}
|
|
142
|
+
if (method === 'connector.link') {
|
|
143
|
+
if (!client)
|
|
144
|
+
throw new ComposioFailure('key_required');
|
|
145
|
+
const { toolkit } = z.object({ toolkit: toolkitSchema }).strict().parse(params);
|
|
146
|
+
if ((await this.#list()).length >= 20)
|
|
147
|
+
throw new ComposioFailure('connection_limit');
|
|
148
|
+
const budget = createComposioBudget(), userId = 'nova-' + randomUUID(), authConfigId = await client.createAuthConfig(toolkit, budget), link = await client.link(authConfigId, userId, budget), id = m.prefix + 'connector:' + randomUUID();
|
|
149
|
+
const c = connectionSchema.parse(await m.options.client.memory('source_connection', { action: 'create', id, namespace: id }));
|
|
150
|
+
await m.options.client.memory('source_connection', { action: 'scope', id, expected_scope_revision: c.fence.scope_revision, scope: { provider: 'composio', toolkit, userId, authConfigId, accountId: link.accountId, identity: null, selection: null } });
|
|
151
|
+
await this.#refresh();
|
|
152
|
+
return { id, url: link.url, expiresAt: link.expiresAt };
|
|
153
|
+
}
|
|
154
|
+
const p = z.object({ id: z.string().min(1).max(256) }).passthrough().parse(params), c = await this.#get(p.id), config = configSchema.parse(c.scope);
|
|
155
|
+
if (method === 'connector.scopes') {
|
|
156
|
+
const q = z.object({ id: z.string(), pageToken: z.string().max(16384).optional() }).strict().parse(params);
|
|
157
|
+
if (config.provider === 'macos_mail') {
|
|
158
|
+
if (!this.options.mail)
|
|
159
|
+
throw new ComposioFailure('native_unavailable');
|
|
160
|
+
const r = await this.options.mail.request({ command: 'list_mailboxes' });
|
|
161
|
+
if (r.complete !== true)
|
|
162
|
+
throw new ComposioFailure('snapshot_incomplete');
|
|
163
|
+
return { items: r.items, next: null };
|
|
164
|
+
}
|
|
165
|
+
if (config.provider === 'macos_calendar') {
|
|
166
|
+
if (!this.options.local)
|
|
167
|
+
throw new ComposioFailure('native_unavailable');
|
|
168
|
+
const r = await this.options.local.request({ command: 'list_calendars' });
|
|
169
|
+
return { items: r.items, next: null };
|
|
170
|
+
}
|
|
171
|
+
if (!config.identity || !client?.scopes)
|
|
172
|
+
throw new ComposioFailure('connection_unverified');
|
|
173
|
+
return client.scopes(bindingSchema.parse({ toolkit: config.toolkit, userId: config.userId, accountId: config.accountId, authConfigId: config.authConfigId, identity: config.identity }), q.pageToken);
|
|
174
|
+
}
|
|
175
|
+
if (method === 'connector.complete') {
|
|
176
|
+
z.object({ id: z.string() }).strict().parse(params);
|
|
177
|
+
if (!client || config.toolkit === 'macos_calendar' || config.toolkit === 'macos_mail')
|
|
178
|
+
throw new ComposioFailure('key_required');
|
|
179
|
+
const identity = await client.inspect(config.toolkit, config.userId, config.accountId, config.authConfigId, createComposioBudget());
|
|
180
|
+
await m.options.client.memory('source_connection', { action: 'scope', id: p.id, expected_scope_revision: c.fence.scope_revision, scope: { ...config, identity: identity.identity } });
|
|
181
|
+
}
|
|
182
|
+
else if (method === 'connector.configure') {
|
|
183
|
+
const q = z.object({ id: z.string(), scope: z.union([googleScopeSchema, macMailScopeSchema]), processingConsent: z.boolean() }).strict().parse(params);
|
|
184
|
+
if (!config.identity || (config.toolkit === 'gmail') !== (q.scope.kind === 'gmail') || (config.toolkit === 'macos_mail') !== (q.scope.kind === 'macos_mail'))
|
|
185
|
+
throw new ComposioFailure('scope_denied');
|
|
186
|
+
this.#active.get(p.id)?.abort.abort();
|
|
187
|
+
const next = connectionSchema.parse(await m.options.client.memory('source_connection', { action: 'scope', id: p.id, expected_scope_revision: c.fence.scope_revision, scope: { ...config, selection: q.scope } }));
|
|
188
|
+
await this.#setGrant(next, q.processingConsent);
|
|
189
|
+
await m.options.client.memory('source_connection', { action: 'fence', id: p.id, expected_epoch: next.fence.epoch, state: 'connected' });
|
|
190
|
+
}
|
|
191
|
+
else if (method === 'connector.consent') {
|
|
192
|
+
const q = z.object({ id: z.string(), processingConsent: z.boolean() }).strict().parse(params);
|
|
193
|
+
this.#active.get(p.id)?.abort.abort();
|
|
194
|
+
const paused = connectionSchema.parse(await m.options.client.memory('source_connection', { action: 'fence', id: p.id, expected_epoch: c.fence.epoch, state: 'paused' }));
|
|
195
|
+
await this.#setGrant(paused, q.processingConsent);
|
|
196
|
+
await m.options.client.memory('source_connection', { action: 'fence', id: p.id, expected_epoch: paused.fence.epoch, state: c.state });
|
|
197
|
+
}
|
|
198
|
+
else if (method === 'connector.sync') {
|
|
199
|
+
z.object({ id: z.string() }).strict().parse(params);
|
|
200
|
+
void this.#run(p.id).catch(() => { });
|
|
201
|
+
}
|
|
202
|
+
else if (['connector.pause', 'connector.resume', 'connector.disconnect', 'connector.delete'].includes(method)) {
|
|
203
|
+
z.object({ id: z.string() }).strict().parse(params);
|
|
204
|
+
this.#active.get(p.id)?.abort.abort();
|
|
205
|
+
if (method === 'connector.resume' && (c.deleting.length > 0 || !config.selection || !config.identity))
|
|
206
|
+
throw new ComposioFailure('scope_denied');
|
|
207
|
+
if (method === 'connector.delete') {
|
|
208
|
+
if (!c.deleting.length)
|
|
209
|
+
await m.options.client.memory('source_connection', { action: 'delete_begin', id: p.id, expected_epoch: c.fence.epoch });
|
|
210
|
+
while ((await m.options.client.memory('source_connection', { action: 'delete_step', id: p.id, limit: 200 })).remaining) { /* bounded worker transactions, old generation only */ }
|
|
211
|
+
}
|
|
212
|
+
else
|
|
213
|
+
await m.options.client.memory('source_connection', { action: 'fence', id: p.id, expected_epoch: c.fence.epoch, state: method === 'connector.resume' ? 'connected' : method === 'connector.disconnect' ? 'disconnected' : 'paused' });
|
|
214
|
+
}
|
|
215
|
+
else
|
|
216
|
+
throw new ComposioFailure('unsupported_command');
|
|
217
|
+
await this.#refresh();
|
|
218
|
+
this.#schedule(1000);
|
|
219
|
+
return this.snapshot();
|
|
220
|
+
}
|
|
221
|
+
async #grant(c) {
|
|
222
|
+
const m = this.#memory(), raw = await m.options.client.memory('source_grant', { source_id: c.fence.connection_id, action: 'get' });
|
|
223
|
+
return raw === null ? m.processingGrant(false, 0, c.fence.scope_revision) : processingGrantSchema.parse(raw);
|
|
224
|
+
}
|
|
225
|
+
async #setGrant(c, allowed) {
|
|
226
|
+
const m = this.#memory(), old = await this.#grant(c), grant = m.processingGrant(allowed, old.revision + 1, c.fence.scope_revision);
|
|
227
|
+
await m.setProcessingConsent(c.fence.connection_id, grant);
|
|
228
|
+
let after = null;
|
|
229
|
+
do {
|
|
230
|
+
const page = await this.#objects(c, after);
|
|
231
|
+
for (const o of page.objects)
|
|
232
|
+
await m.setProcessingConsent(o.source_id, grant);
|
|
233
|
+
after = page.next;
|
|
234
|
+
} while (after);
|
|
235
|
+
}
|
|
236
|
+
async #objects(c, after) { return z.object({ objects: z.array(sourceObjectSchema), next: z.string().nullable() }).parse(await this.#memory().options.client.memory('source_pending', { id: c.fence.connection_id, ...(after ? { after } : {}), limit: 200 })); }
|
|
237
|
+
async #run(id) {
|
|
238
|
+
while (!this.#active.has(id) && this.#active.size >= 4 && !this.#closed)
|
|
239
|
+
await Promise.race([...this.#active.values()].map(active => active.promise)).catch(() => { });
|
|
240
|
+
if (this.#closed)
|
|
241
|
+
return;
|
|
242
|
+
const active = this.#active.get(id);
|
|
243
|
+
if (active)
|
|
244
|
+
return active.promise;
|
|
245
|
+
const abort = new AbortController(), promise = this.#sync(id, abort.signal).catch(async (error) => {
|
|
246
|
+
if (abort.signal.aborted)
|
|
247
|
+
return;
|
|
248
|
+
let c = await this.#get(id);
|
|
249
|
+
if (error instanceof ComposioFailure && ['permission_denied', 'authorization_required', 'identity_mismatch', 'connection_unverified'].includes(error.code) && c.state === 'connected')
|
|
250
|
+
c = connectionSchema.parse(await this.#memory().options.client.memory('source_connection', { action: 'fence', id, expected_epoch: c.fence.epoch, state: 'paused' }));
|
|
251
|
+
const failures = (c.sync_status?.failures ?? 0) + 1, seconds = Math.max(Math.min(60 * 2 ** Math.min(failures - 1, 4), 900), error instanceof ComposioFailure ? error.retryAfter ?? 0 : 0);
|
|
252
|
+
await this.#memory().options.client.memory('source_connection', { action: 'sync_status', id, expected_epoch: c.fence.epoch, status: { attempt_at: c.sync_status?.attempt_at ?? Date.now(), complete_at: c.sync_status?.complete_at ?? null, error: error instanceof ComposioFailure ? error.code : 'sync_failed', failures, retry_at: Date.now() + seconds * 1000 + Math.floor(Math.random() * 1000) } });
|
|
253
|
+
}).finally(async () => { this.#active.delete(id); if (!this.#closed)
|
|
254
|
+
await this.#refresh(); });
|
|
255
|
+
this.#active.set(id, { abort, promise });
|
|
256
|
+
return promise;
|
|
257
|
+
}
|
|
258
|
+
async #sync(id, signal) {
|
|
259
|
+
const m = this.#memory(), client = this.options.client, provider = this.#provider, c = await this.#get(id), config = configSchema.parse(c.scope);
|
|
260
|
+
if (!config.identity || !config.selection || c.state !== 'connected')
|
|
261
|
+
return;
|
|
262
|
+
if (config.provider === 'composio' && (!client || !provider))
|
|
263
|
+
throw new ComposioFailure('key_required');
|
|
264
|
+
if ((c.continuation !== null && Date.now() - stateSchema.parse(c.continuation).anchor >= 86400000) || (c.continuation === null && c.checkpoint !== null && Date.now() - checkpointSchema.parse(c.checkpoint).fullAt >= 86400000)) {
|
|
265
|
+
await m.options.client.memory('source_connection', { action: 'reset_sync', id, expected_epoch: c.fence.epoch });
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
await m.options.client.memory('source_connection', { action: 'sync_status', id, expected_epoch: c.fence.epoch, status: { attempt_at: Date.now(), complete_at: c.sync_status?.complete_at ?? null, error: null, failures: c.sync_status?.failures ?? 0, retry_at: 0 } });
|
|
269
|
+
const old = c.continuation === null ? null : stateSchema.parse(c.continuation), state = old ?? { providerCursor: null, anchor: Date.now(), snapshot: !c.checkpoint || config.toolkit !== 'gmail', reconciling: false, after: null, nextCheckpoint: null };
|
|
270
|
+
const batch = c.batch > c.completed_batch ? c.batch : c.completed_batch + 1, changes = [];
|
|
271
|
+
let complete = false;
|
|
272
|
+
if (state.reconciling) {
|
|
273
|
+
const rows = await this.#objects(c, state.after);
|
|
274
|
+
for (const o of rows.objects)
|
|
275
|
+
if (o.status === 'current' && o.metadata.scan_batch !== batch)
|
|
276
|
+
changes.push({ object_key: o.object_key, source_id: o.source_id, semantic_hash: hash('coverage_removed'), metadata: o.metadata, evidence: [], status: 'coverage_removed' });
|
|
277
|
+
state.after = rows.next;
|
|
278
|
+
complete = rows.next === null;
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
const checkpoint = state.snapshot ? null : checkpointSchema.parse(c.checkpoint);
|
|
282
|
+
let page;
|
|
283
|
+
if (config.provider === 'macos_mail') {
|
|
284
|
+
if (!this.options.mail)
|
|
285
|
+
throw new ComposioFailure('native_unavailable');
|
|
286
|
+
page = await this.options.mail.page(macMailScopeSchema.parse(config.selection), state.providerCursor, state.anchor, signal).catch(async (error) => { if (error instanceof ComposioFailure && error.code === 'snapshot_expired' && !signal.aborted)
|
|
287
|
+
await m.options.client.memory('source_connection', { action: 'reset_sync', id, expected_epoch: c.fence.epoch }); throw error; });
|
|
288
|
+
}
|
|
289
|
+
else if (config.provider === 'macos_calendar') {
|
|
290
|
+
if (!this.options.local)
|
|
291
|
+
throw new ComposioFailure('native_unavailable');
|
|
292
|
+
page = await this.options.local.page(googleScopeSchema.parse(config.selection), signal);
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
if (!client || !provider)
|
|
296
|
+
throw new ComposioFailure('key_required');
|
|
297
|
+
const budget = createComposioBudget(signal, state.anchor), binding = bindingSchema.parse({ toolkit: config.toolkit, userId: config.userId, accountId: config.accountId, authConfigId: config.authConfigId, identity: config.identity }), verified = await client.verify(binding, googleScopeSchema.parse(config.selection), budget);
|
|
298
|
+
page = await provider.page(verified, state.providerCursor, budget, checkpoint?.historyId ? { historyId: checkpoint.historyId } : null).catch(async (error) => { if (error instanceof ComposioFailure && ['cursor_expired', 'snapshot_expired', 'history_too_large'].includes(error.code) && !signal.aborted)
|
|
299
|
+
await m.options.client.memory('source_connection', { action: 'reset_sync', id, expected_epoch: c.fence.epoch }); throw error; });
|
|
300
|
+
}
|
|
301
|
+
if (!page.complete && !page.objects.length && canonicalJson(page.continuation) === canonicalJson(state.providerCursor))
|
|
302
|
+
throw new ComposioFailure('no_progress');
|
|
303
|
+
const grant = await this.#grant(c);
|
|
304
|
+
for (const o of page.objects) {
|
|
305
|
+
const change = this.#change(c, o, batch);
|
|
306
|
+
await m.setProcessingConsent(change.source_id, grant);
|
|
307
|
+
changes.push(change);
|
|
308
|
+
}
|
|
309
|
+
state.providerCursor = page.continuation;
|
|
310
|
+
state.nextCheckpoint = { ...page.checkpoint, fullAt: state.snapshot ? state.anchor : checkpoint?.fullAt ?? state.anchor, ...(config.provider === 'macos_mail' ? { limited: page.scanLimited === true } : {}) };
|
|
311
|
+
if (page.complete) {
|
|
312
|
+
if (state.snapshot && !(config.provider === 'macos_mail' && !page.snapshot)) {
|
|
313
|
+
state.reconciling = true;
|
|
314
|
+
state.after = null;
|
|
315
|
+
}
|
|
316
|
+
else
|
|
317
|
+
complete = true;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
signal.throwIfAborted();
|
|
321
|
+
await m.applySourcePage({ fence: c.fence, batch_id: String(batch), page_id: hash(canonicalJson(c.continuation)), changes, pending_ids: state.providerCursor && typeof state.providerCursor === 'object' && !Array.isArray(state.providerCursor) && Array.isArray(state.providerCursor.pending) ? state.providerCursor.pending.map(item => hash('mail::' + z.object({ id: z.string() }).parse(item).id)) : [], continuation: complete ? null : state, checkpoint: complete ? state.nextCheckpoint : c.checkpoint, complete });
|
|
322
|
+
await m.options.client.memory('source_connection', { action: 'sync_status', id, expected_epoch: c.fence.epoch, status: { attempt_at: Date.now(), complete_at: complete ? Date.now() : c.sync_status?.complete_at ?? null, error: null, failures: 0, retry_at: complete ? Date.now() + 60000 : 0 } });
|
|
323
|
+
}
|
|
324
|
+
#change(c, o, batch) {
|
|
325
|
+
const m = this.#memory(), source_id = connectorSourceId(c.namespace, c.fence.generation, o.key);
|
|
326
|
+
const config = configSchema.parse(c.scope), sender = typeof o.metadata.sender === 'string' ? o.metadata.sender.trim().toLowerCase() : '';
|
|
327
|
+
const address = /^(?:[^<>]*<)?([^<>\s]+@[^<>\s]+)>?$/.exec(sender)?.[1];
|
|
328
|
+
const recipients = typeof o.metadata.recipients === 'string' ? [...o.metadata.recipients.matchAll(/[A-Za-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[A-Za-z0-9.-]+/gu)].map(match => match[0].toLowerCase()).slice(0, 50) : [];
|
|
329
|
+
const ownMail = o.kind === 'mail' && Array.isArray(o.metadata.labels) && o.metadata.labels.includes('SENT') && config.provider === 'composio' && !!config.identity && address === config.identity.toLowerCase();
|
|
330
|
+
const evidence = o.status === 'current' ? [EvidenceRecordSchema.parse({ id: m.prefix + 'e:' + hash(source_id + ':' + o.semanticHash), source_id, source_kind: o.kind, ...(ownMail ? { source_metadata: { sender_id: address, account_id: config.identity.toLowerCase(), provider: 'gmail', ...(typeof o.metadata.thread_id === 'string' && o.metadata.thread_id ? { chat_id: o.metadata.thread_id } : {}), recipient_ids: recipients, ...(sender.includes('<') ? { sender_name: sender.slice(0, sender.indexOf('<')).trim().slice(0, 120) } : {}) } } : {}), locator: o.locator, raw_text: o.text, hash: hash(o.text), observed_at: o.observedAt, recorded_at: new Date().toISOString(), retention_until: o.retentionUntil, trust: 'untrusted_external' })] : [];
|
|
331
|
+
return { object_key: o.key, source_id, semantic_hash: o.semanticHash, metadata: { ...o.metadata, scan_batch: batch }, evidence, status: o.status };
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
//# sourceMappingURL=index.js.map
|