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,980 @@
|
|
|
1
|
+
import { processingGrantSchema } from '../../memory-substrate/source-state.js';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
import { createFeishuRunner, FeishuAppNotConfigured, object, parseFeishuJson } from './cli.js';
|
|
6
|
+
export const FEISHU_SCOPES = ['offline_access', 'im:chat:read', 'im:message:readonly', 'im:message.reactions:read'];
|
|
7
|
+
const fresh = () => ({ paused: true, connected: false, bot: false, selected: [], cursors: {}, deliveries: {}, actions: [], generation: 0, sources: [] });
|
|
8
|
+
const str = (value) => typeof value === 'string' ? value : '';
|
|
9
|
+
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
10
|
+
function jsonObject(text) {
|
|
11
|
+
try {
|
|
12
|
+
return object(JSON.parse(text));
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
throw new Error('Invalid Feishu JSON payload');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function pageItems(data, alternative) {
|
|
19
|
+
const items = Object.hasOwn(data, 'items') ? data.items : data[alternative];
|
|
20
|
+
if (typeof data.has_more !== 'boolean' || (items !== null && !Array.isArray(items)))
|
|
21
|
+
throw new Error('Invalid Feishu page');
|
|
22
|
+
return items ?? [];
|
|
23
|
+
}
|
|
24
|
+
function messageText(row) {
|
|
25
|
+
const kind = row.msg_type ?? row.message_type;
|
|
26
|
+
if (kind !== 'text' && kind !== 'post')
|
|
27
|
+
return null;
|
|
28
|
+
// CLI 1.0.69 returns rendered top-level content; raw API records have body.content JSON.
|
|
29
|
+
if (typeof row.content === 'string')
|
|
30
|
+
return row.content;
|
|
31
|
+
const raw = row.content ?? object(row.body).content;
|
|
32
|
+
const content = typeof raw === 'string' ? jsonObject(raw) : object(raw);
|
|
33
|
+
if (kind === 'text')
|
|
34
|
+
return str(content.text);
|
|
35
|
+
const post = Array.isArray(content.content) ? content : object(content.zh_cn ?? content.en_us ?? Object.values(content)[0]);
|
|
36
|
+
if (!Array.isArray(post.content))
|
|
37
|
+
throw new Error('Invalid Feishu post');
|
|
38
|
+
return [str(post.title), ...post.content.map((line) => {
|
|
39
|
+
if (!Array.isArray(line))
|
|
40
|
+
throw new Error('Invalid Feishu post line');
|
|
41
|
+
return line.map((segment) => str(object(segment).text)).join('');
|
|
42
|
+
})].filter(Boolean).join('\n');
|
|
43
|
+
}
|
|
44
|
+
/** Only provider top-level mentions identify the addressed user; quotations and rendered names do not. */
|
|
45
|
+
export function structuredMention(row, openId) {
|
|
46
|
+
if (!Array.isArray(row.mentions)) {
|
|
47
|
+
if ((row.msg_type ?? row.message_type) !== 'post')
|
|
48
|
+
return 'unknown';
|
|
49
|
+
try {
|
|
50
|
+
const raw = object(row.body).content;
|
|
51
|
+
const content = typeof raw === 'string' ? object(JSON.parse(raw)) : object(raw);
|
|
52
|
+
const post = Array.isArray(content.content) ? content : object(content.zh_cn ?? content.en_us ?? Object.values(content)[0]);
|
|
53
|
+
if (!Array.isArray(post.content))
|
|
54
|
+
return 'unknown';
|
|
55
|
+
const nodes = post.content.flat().filter(node => node && typeof node === 'object');
|
|
56
|
+
const targets = nodes.filter(node => node.tag === 'at').map(node => node.user_id);
|
|
57
|
+
if (targets.includes(openId))
|
|
58
|
+
return 'direct';
|
|
59
|
+
if (targets.includes('all'))
|
|
60
|
+
return 'all';
|
|
61
|
+
return targets.length ? 'none' : 'unknown';
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return 'unknown';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const mentions = row.mentions.filter(item => item && typeof item === 'object');
|
|
68
|
+
if (mentions.some(item => (item.id_type === undefined || item.id_type === 'open_id') && item.id === openId))
|
|
69
|
+
return 'direct';
|
|
70
|
+
if (mentions.some(item => item.id === 'all'))
|
|
71
|
+
return 'all';
|
|
72
|
+
return 'none';
|
|
73
|
+
}
|
|
74
|
+
function readSaved(value) {
|
|
75
|
+
const data = object(value);
|
|
76
|
+
for (const key of ['paused', 'connected', 'bot'])
|
|
77
|
+
if (typeof data[key] !== 'boolean')
|
|
78
|
+
throw new Error('Invalid Feishu state');
|
|
79
|
+
for (const key of ['selected', 'actions', 'sources'])
|
|
80
|
+
if (!Array.isArray(data[key]) || !data[key].every((item) => typeof item === 'string'))
|
|
81
|
+
throw new Error('Invalid Feishu state');
|
|
82
|
+
if (!Number.isSafeInteger(data.generation) || Number(data.generation) < 0)
|
|
83
|
+
throw new Error('Invalid Feishu generation');
|
|
84
|
+
for (const key of ['account', 'openId', 'name', 'lastSync'])
|
|
85
|
+
if (data[key] !== undefined && typeof data[key] !== 'string')
|
|
86
|
+
throw new Error('Invalid Feishu identity');
|
|
87
|
+
for (const cursor of [...Object.values(object(data.cursors)), ...Object.values(object(data.backfills ?? {}))]) {
|
|
88
|
+
const row = object(cursor);
|
|
89
|
+
if (!str(row.start) || !Number.isFinite(Date.parse(str(row.start))) || (row.end !== undefined && !Number.isFinite(Date.parse(str(row.end)))) || (row.page !== undefined && typeof row.page !== 'string') || (row.order !== undefined && row.order !== 'asc' && row.order !== 'desc'))
|
|
90
|
+
throw new Error('Invalid Feishu cursor');
|
|
91
|
+
}
|
|
92
|
+
for (const delivery of Object.values(object(data.deliveries))) {
|
|
93
|
+
const row = object(delivery);
|
|
94
|
+
if (!str(row.nonce) || ['message', 'chat'].some((key) => row[key] !== undefined && typeof row[key] !== 'string'))
|
|
95
|
+
throw new Error('Invalid Feishu delivery');
|
|
96
|
+
}
|
|
97
|
+
if (data.scopeConfigured !== undefined && typeof data.scopeConfigured !== 'boolean')
|
|
98
|
+
throw new Error('Invalid Feishu scope state');
|
|
99
|
+
if (data.consentSince !== undefined && !Number.isFinite(Date.parse(str(data.consentSince))))
|
|
100
|
+
throw new Error('Invalid Feishu consent state');
|
|
101
|
+
for (const from of Object.values(object(data.captureFrom ?? {})))
|
|
102
|
+
if (!Number.isFinite(Date.parse(str(from))))
|
|
103
|
+
throw new Error('Invalid Feishu capture state');
|
|
104
|
+
if (data.outbound !== undefined && typeof data.outbound !== 'boolean')
|
|
105
|
+
throw Error('Invalid outbound state');
|
|
106
|
+
if (data.outboundIdentity !== undefined) {
|
|
107
|
+
const row = object(data.outboundIdentity);
|
|
108
|
+
if (!str(row.account) || !str(row.openId) || !Number.isSafeInteger(row.generation) || Number(row.generation) < 0 || typeof row.valid !== 'boolean')
|
|
109
|
+
throw Error('Invalid outbound identity');
|
|
110
|
+
}
|
|
111
|
+
for (const value of Object.values(object(data.outboundReceipts ?? {}))) {
|
|
112
|
+
const row = object(value);
|
|
113
|
+
if (['proposal', 'nonce', 'message', 'chat'].some(key => !str(row[key])) || !Number.isSafeInteger(row.generation))
|
|
114
|
+
throw Error('Invalid outbound receipt');
|
|
115
|
+
}
|
|
116
|
+
if (data.processingConsent !== undefined)
|
|
117
|
+
processingGrantSchema.parse(data.processingConsent);
|
|
118
|
+
return data;
|
|
119
|
+
}
|
|
120
|
+
export class FeishuConnector {
|
|
121
|
+
options;
|
|
122
|
+
run;
|
|
123
|
+
saved = fresh();
|
|
124
|
+
view = { available: false, configured: false, state: 'unauthorized', chats: [], bot_enabled: false, retention_days: 30 };
|
|
125
|
+
deviceCode;
|
|
126
|
+
deviceExpiry = 0;
|
|
127
|
+
notificationLogin = false;
|
|
128
|
+
active;
|
|
129
|
+
timer;
|
|
130
|
+
busy = false;
|
|
131
|
+
mentionReads = new Set();
|
|
132
|
+
pending;
|
|
133
|
+
listener;
|
|
134
|
+
listenerController;
|
|
135
|
+
listenerRetry;
|
|
136
|
+
closed = false;
|
|
137
|
+
saving = Promise.resolve();
|
|
138
|
+
listenerApp;
|
|
139
|
+
currentApp;
|
|
140
|
+
lastPublished = '';
|
|
141
|
+
setupController;
|
|
142
|
+
setupTask;
|
|
143
|
+
constructor(options) {
|
|
144
|
+
this.options = options;
|
|
145
|
+
if (!options.bootstrapOnly && (!(options.ingest || options.ingestBatch) || !options.deleteSource || !options.onAction))
|
|
146
|
+
throw new Error('Feishu collection callbacks required');
|
|
147
|
+
this.run = options.run ?? createFeishuRunner(options.executable, options.credentialRoot);
|
|
148
|
+
}
|
|
149
|
+
snapshot() { const view = structuredClone(this.view), expected = this.options.processingGrant?.(true, 1, 0); view.processing_consent_required = !this.saved.processingConsent?.extraction_provider || this.saved.processingConsent.extraction_provider !== expected?.extraction_provider || this.saved.processingConsent.embedding_provider !== expected?.embedding_provider || JSON.stringify([...(this.saved.processingConsent.conversation_providers ?? [])].sort()) !== JSON.stringify([...(expected?.conversation_providers ?? [])].sort()); view.scope_configured = this.saved.scopeConfigured ?? this.saved.selected.length > 0; if (view.app_setup)
|
|
150
|
+
delete view.app_setup.verification_url; return view; }
|
|
151
|
+
setupSnapshot() { const view = this.snapshot(); if (this.view.app_setup)
|
|
152
|
+
view.app_setup = structuredClone(this.view.app_setup); return view; }
|
|
153
|
+
publish() {
|
|
154
|
+
if (this.closed)
|
|
155
|
+
return;
|
|
156
|
+
const snapshot = this.snapshot();
|
|
157
|
+
const key = JSON.stringify(snapshot);
|
|
158
|
+
if (key === this.lastPublished)
|
|
159
|
+
return;
|
|
160
|
+
this.lastPublished = key;
|
|
161
|
+
queueMicrotask(() => { if (!this.closed)
|
|
162
|
+
this.options.onChange?.(snapshot); });
|
|
163
|
+
}
|
|
164
|
+
async stopOwnedBus() {
|
|
165
|
+
if (!this.listenerApp)
|
|
166
|
+
return;
|
|
167
|
+
// This connector's isolated profile only; never --all or --force another consumer.
|
|
168
|
+
await this.run(['event', 'stop', '--app-id', this.listenerApp, '--json']);
|
|
169
|
+
this.listenerApp = undefined;
|
|
170
|
+
}
|
|
171
|
+
now() { return this.options.now?.() ?? new Date(); }
|
|
172
|
+
save() {
|
|
173
|
+
const contents = JSON.stringify(this.saved);
|
|
174
|
+
const saving = this.saving.then(async () => {
|
|
175
|
+
await mkdir(dirname(this.options.statePath), { recursive: true, mode: 0o700 });
|
|
176
|
+
const temporary = `${this.options.statePath}.${randomUUID()}.tmp`;
|
|
177
|
+
await writeFile(temporary, contents, { mode: 0o600 });
|
|
178
|
+
await rename(temporary, this.options.statePath);
|
|
179
|
+
});
|
|
180
|
+
this.saving = saving.catch(() => { });
|
|
181
|
+
return saving;
|
|
182
|
+
}
|
|
183
|
+
async json(args, input) {
|
|
184
|
+
return parseFeishuJson(await this.run(args, { ...(input ? { input } : {}), ...(this.active ? { signal: this.active.signal } : {}) }));
|
|
185
|
+
}
|
|
186
|
+
async open() {
|
|
187
|
+
this.closed = false;
|
|
188
|
+
try {
|
|
189
|
+
this.saved = readSaved(JSON.parse(await readFile(this.options.statePath, 'utf8')));
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (error.code !== 'ENOENT')
|
|
193
|
+
throw new Error('Cannot read Feishu state');
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
const version = await this.run(['--version']);
|
|
197
|
+
const match = /(\d+)\.(\d+)\.(\d+)/.exec(version);
|
|
198
|
+
if (!match || Number(match[1]) < 1 || (Number(match[1]) === 1 && Number(match[2]) === 0 && Number(match[3]) < 69))
|
|
199
|
+
throw new Error('飞书 CLI 需要 1.0.69 或更高版本');
|
|
200
|
+
this.view.available = true;
|
|
201
|
+
await this.status();
|
|
202
|
+
this.schedule();
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
this.view.state = 'error';
|
|
206
|
+
this.view.error = error instanceof Error ? error.message : '飞书连接不可用';
|
|
207
|
+
}
|
|
208
|
+
this.publish();
|
|
209
|
+
}
|
|
210
|
+
async close() {
|
|
211
|
+
this.closed = true;
|
|
212
|
+
await this.cancelAppSetup();
|
|
213
|
+
if (this.timer)
|
|
214
|
+
clearTimeout(this.timer);
|
|
215
|
+
this.timer = undefined;
|
|
216
|
+
if (this.listenerRetry)
|
|
217
|
+
clearTimeout(this.listenerRetry);
|
|
218
|
+
this.listenerRetry = undefined;
|
|
219
|
+
this.listenerController?.abort();
|
|
220
|
+
await this.listener?.catch(() => { });
|
|
221
|
+
this.active?.abort();
|
|
222
|
+
await this.pending?.catch(() => { });
|
|
223
|
+
await this.saving;
|
|
224
|
+
await this.stopOwnedBus();
|
|
225
|
+
}
|
|
226
|
+
schedule() {
|
|
227
|
+
if (this.closed || this.options.bootstrapOnly)
|
|
228
|
+
return;
|
|
229
|
+
this.startListener();
|
|
230
|
+
if (this.timer)
|
|
231
|
+
clearTimeout(this.timer);
|
|
232
|
+
this.timer = setTimeout(() => {
|
|
233
|
+
void this.sync().catch(() => { this.view.error = '飞书同步失败,请重试或重新登录'; this.publish(); }).finally(() => this.schedule());
|
|
234
|
+
}, 60_000);
|
|
235
|
+
this.timer.unref();
|
|
236
|
+
}
|
|
237
|
+
startListener() {
|
|
238
|
+
if (this.options.bootstrapOnly || this.listener || this.listenerRetry || this.closed || !this.callbackReady())
|
|
239
|
+
return;
|
|
240
|
+
void this.consumeActions().catch(() => { if (!this.closed && !this.saved.paused) {
|
|
241
|
+
this.view.error = '飞书提醒连接中断,正在重连';
|
|
242
|
+
this.publish();
|
|
243
|
+
} }).finally(() => {
|
|
244
|
+
if (this.closed || !this.callbackReady())
|
|
245
|
+
return;
|
|
246
|
+
this.listenerRetry = setTimeout(() => { this.listenerRetry = undefined; this.startListener(); }, 5_000);
|
|
247
|
+
this.listenerRetry.unref();
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
async status(signal) {
|
|
251
|
+
// Preserve the preflight error instead of attempting credential access with an unsupported CLI.
|
|
252
|
+
if (!this.view.available)
|
|
253
|
+
return this.snapshot();
|
|
254
|
+
let data;
|
|
255
|
+
try {
|
|
256
|
+
data = signal ? parseFeishuJson(await this.run(['auth', 'status', '--json', '--verify'], { signal })) : await this.json(['auth', 'status', '--json', '--verify']);
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
if (!(error instanceof FeishuAppNotConfigured))
|
|
260
|
+
throw error;
|
|
261
|
+
data = {};
|
|
262
|
+
}
|
|
263
|
+
const app = str(data.appId ?? data.app_id);
|
|
264
|
+
this.currentApp = app || undefined;
|
|
265
|
+
this.view.configured = Boolean(app);
|
|
266
|
+
if (app)
|
|
267
|
+
this.view.app_id = app;
|
|
268
|
+
else
|
|
269
|
+
delete this.view.app_id;
|
|
270
|
+
const identities = data.identities ? object(data.identities) : {};
|
|
271
|
+
const user = identities.user ? object(identities.user) : {};
|
|
272
|
+
const scopes = Array.isArray(user.scopes ?? user.scope) ? user.scopes ?? user.scope : str(user.scope ?? user.scopes).split(/[ ,]+/);
|
|
273
|
+
const id = str(user.openId ?? user.open_id);
|
|
274
|
+
// CLI --verify may refresh successfully while retaining the pre-refresh status.
|
|
275
|
+
const valid = data.verified !== false && user.verified !== false && (user.status === 'authenticated' || user.tokenStatus === 'valid' || user.authenticated === true
|
|
276
|
+
|| user.status === 'needs_refresh' && user.verified === true);
|
|
277
|
+
const priorIdentity = this.saved.outboundIdentity;
|
|
278
|
+
const identityAccount = app && id && valid ? hash(JSON.stringify([app, user.tenantKey ?? user.tenant_key ?? null, id])) : null;
|
|
279
|
+
if (identityAccount) {
|
|
280
|
+
this.saved.outboundIdentity = { account: identityAccount, openId: id, generation: (priorIdentity?.generation ?? 0) + Number(!!priorIdentity && priorIdentity.account !== identityAccount), valid: true };
|
|
281
|
+
if (priorIdentity && priorIdentity.account !== identityAccount)
|
|
282
|
+
this.saved.outbound = false;
|
|
283
|
+
}
|
|
284
|
+
else if (priorIdentity)
|
|
285
|
+
this.saved.outboundIdentity = { ...priorIdentity, valid: false };
|
|
286
|
+
this.view.notification_enabled = this.saved.outbound === true;
|
|
287
|
+
this.view.notification_ready = !!this.saved.outboundIdentity?.valid;
|
|
288
|
+
if (!app || !id || !valid || !FEISHU_SCOPES.every((scope) => scopes.includes(scope))) {
|
|
289
|
+
if (app)
|
|
290
|
+
this.view.auth_issue = user.tokenStatus === 'expired' ? 'expired' : valid && id ? 'missing_scopes' : 'login_required';
|
|
291
|
+
else
|
|
292
|
+
delete this.view.auth_issue;
|
|
293
|
+
if (this.saved.processingConsent?.extraction_provider)
|
|
294
|
+
await this.setProcessingConsent(false);
|
|
295
|
+
this.view.state = 'unauthorized';
|
|
296
|
+
this.view.bot_enabled = false;
|
|
297
|
+
this.saved.connected = false;
|
|
298
|
+
this.saved.bot = false;
|
|
299
|
+
if (!this.saved.outbound) {
|
|
300
|
+
this.listenerController?.abort();
|
|
301
|
+
await this.listener?.catch(() => { });
|
|
302
|
+
}
|
|
303
|
+
await this.save();
|
|
304
|
+
return this.snapshot();
|
|
305
|
+
}
|
|
306
|
+
delete this.view.auth_issue;
|
|
307
|
+
const account = hash(JSON.stringify([app, user.tenantKey ?? user.tenant_key ?? null, id]));
|
|
308
|
+
if (this.saved.account && this.saved.account !== account) {
|
|
309
|
+
await this.setProcessingConsent(false);
|
|
310
|
+
this.listenerController?.abort();
|
|
311
|
+
await this.listener?.catch(() => { });
|
|
312
|
+
await this.stopOwnedBus();
|
|
313
|
+
const { sources, generation, outboundIdentity } = this.saved;
|
|
314
|
+
this.saved = { ...fresh(), sources, generation: generation + 1, ...(outboundIdentity ? { outboundIdentity } : {}) };
|
|
315
|
+
this.view.chats = [];
|
|
316
|
+
}
|
|
317
|
+
this.saved.mentionCaptureSince ??= this.now().toISOString();
|
|
318
|
+
this.saved.account = account;
|
|
319
|
+
this.saved.openId = id;
|
|
320
|
+
this.saved.name = str(user.name ?? user.userName) || '已登录';
|
|
321
|
+
this.view.account_name = this.saved.name;
|
|
322
|
+
this.view.account_id = account;
|
|
323
|
+
this.view.state = !this.saved.connected ? 'disconnected' : this.saved.paused ? 'paused' : 'ready';
|
|
324
|
+
this.view.bot_enabled = this.saved.bot && this.saved.connected;
|
|
325
|
+
if (this.saved.lastSync)
|
|
326
|
+
this.view.last_sync = this.saved.lastSync;
|
|
327
|
+
await this.save();
|
|
328
|
+
return this.snapshot();
|
|
329
|
+
}
|
|
330
|
+
async beginLogin(notificationOnly = false) {
|
|
331
|
+
if (this.setupController)
|
|
332
|
+
throw new Error('请先完成应用配置');
|
|
333
|
+
await this.pause();
|
|
334
|
+
this.notificationLogin = notificationOnly;
|
|
335
|
+
const data = await this.json(['auth', 'login', '--scope', notificationOnly ? 'offline_access' : FEISHU_SCOPES.join(','), '--no-wait', '--json']);
|
|
336
|
+
const url = str(data.verification_url ?? data.verification_uri_complete ?? data.verificationUrl);
|
|
337
|
+
const parsed = new URL(url);
|
|
338
|
+
if (parsed.protocol !== 'https:' || !['feishu.cn', 'larksuite.com'].some((domain) => parsed.hostname === domain || parsed.hostname.endsWith(`.${domain}`)))
|
|
339
|
+
throw new Error('Invalid Feishu verification URL');
|
|
340
|
+
this.deviceCode = str(data.device_code ?? data.deviceCode);
|
|
341
|
+
if (!this.deviceCode)
|
|
342
|
+
throw new Error('Missing Feishu device code');
|
|
343
|
+
this.deviceExpiry = this.now().getTime() + Math.min(900, Number(data.expires_in ?? 900)) * 1000;
|
|
344
|
+
this.view.verification_url = url;
|
|
345
|
+
return this.snapshot();
|
|
346
|
+
}
|
|
347
|
+
beginAppSetup(binding) {
|
|
348
|
+
if (this.closed || !this.view.available)
|
|
349
|
+
throw new Error('飞书 CLI 暂不可用');
|
|
350
|
+
if (this.setupController)
|
|
351
|
+
return Promise.resolve(this.setupSnapshot());
|
|
352
|
+
const controller = new AbortController();
|
|
353
|
+
this.setupController = controller;
|
|
354
|
+
this.view.app_setup = { state: 'waiting' };
|
|
355
|
+
this.publish();
|
|
356
|
+
const task = (async () => {
|
|
357
|
+
// Never turn an OAuth/network/scope failure into a new app: establish absence first.
|
|
358
|
+
await this.status(controller.signal);
|
|
359
|
+
controller.signal.throwIfAborted();
|
|
360
|
+
if (this.view.configured) {
|
|
361
|
+
if (binding)
|
|
362
|
+
throw new Error('app_already_configured');
|
|
363
|
+
this.view.app_setup = { state: 'ready' };
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
let output = '';
|
|
367
|
+
const inspect = (chunk) => {
|
|
368
|
+
if (controller.signal.aborted || this.closed)
|
|
369
|
+
return;
|
|
370
|
+
output = (output + chunk).slice(-8192);
|
|
371
|
+
const candidate = /https:\/\/open\.feishu\.cn\/page\/cli\?[^\s<>"'\x1b]+(?=[\s<>"'\x1b])/u.exec(output)?.[0];
|
|
372
|
+
if (!candidate || candidate.length > 4096)
|
|
373
|
+
return;
|
|
374
|
+
try {
|
|
375
|
+
const url = new URL(candidate);
|
|
376
|
+
if (url.origin !== 'https://open.feishu.cn' || url.pathname !== '/page/cli' || url.username || url.password || url.hash)
|
|
377
|
+
return;
|
|
378
|
+
this.view.app_setup = { state: 'waiting', verification_url: url.href };
|
|
379
|
+
this.publish();
|
|
380
|
+
}
|
|
381
|
+
catch { /* Incomplete streamed URL. */ }
|
|
382
|
+
};
|
|
383
|
+
if (binding)
|
|
384
|
+
await this.run(['config', 'init', '--app-id', binding.app_id, '--app-secret-stdin', '--brand', 'feishu'], { signal: controller.signal, input: binding.app_secret });
|
|
385
|
+
else
|
|
386
|
+
await this.run(['config', 'init', '--new', '--lang', 'zh'], { signal: controller.signal, onOutput: inspect });
|
|
387
|
+
controller.signal.throwIfAborted();
|
|
388
|
+
await this.status(controller.signal);
|
|
389
|
+
controller.signal.throwIfAborted();
|
|
390
|
+
if (!this.view.configured)
|
|
391
|
+
throw new Error('app_not_configured');
|
|
392
|
+
this.view.app_setup = { state: 'ready' };
|
|
393
|
+
})().catch(() => {
|
|
394
|
+
this.view.app_setup = controller.signal.aborted ? { state: 'idle' } : { state: 'error', error: '应用配置未完成,请重试;已绑定应用不会被自动替换。' };
|
|
395
|
+
}).finally(() => {
|
|
396
|
+
if (this.setupController === controller)
|
|
397
|
+
this.setupController = undefined;
|
|
398
|
+
if (this.setupTask === task)
|
|
399
|
+
this.setupTask = undefined;
|
|
400
|
+
this.publish();
|
|
401
|
+
});
|
|
402
|
+
this.setupTask = task;
|
|
403
|
+
return Promise.resolve(this.setupSnapshot());
|
|
404
|
+
}
|
|
405
|
+
async cancelAppSetup() {
|
|
406
|
+
this.setupController?.abort();
|
|
407
|
+
await this.setupTask;
|
|
408
|
+
this.view.app_setup = { state: 'idle' };
|
|
409
|
+
this.publish();
|
|
410
|
+
return this.snapshot();
|
|
411
|
+
}
|
|
412
|
+
async completeLogin() {
|
|
413
|
+
if (!this.deviceCode || this.now().getTime() >= this.deviceExpiry)
|
|
414
|
+
throw new Error('请重新开始飞书登录');
|
|
415
|
+
await this.json(['auth', 'login', '--device-code', this.deviceCode, '--json']);
|
|
416
|
+
this.deviceCode = undefined;
|
|
417
|
+
delete this.view.verification_url;
|
|
418
|
+
await this.status();
|
|
419
|
+
if (this.notificationLogin) {
|
|
420
|
+
this.notificationLogin = false;
|
|
421
|
+
if (!this.saved.outboundIdentity?.valid)
|
|
422
|
+
throw Error('飞书身份未验证');
|
|
423
|
+
await this.save();
|
|
424
|
+
return this.snapshot();
|
|
425
|
+
}
|
|
426
|
+
if (this.view.state === 'unauthorized')
|
|
427
|
+
throw new Error('飞书授权缺少所需权限');
|
|
428
|
+
this.saved.connected = true;
|
|
429
|
+
this.saved.paused = true;
|
|
430
|
+
this.view.state = 'paused';
|
|
431
|
+
await this.save();
|
|
432
|
+
return this.snapshot();
|
|
433
|
+
}
|
|
434
|
+
async listChats() {
|
|
435
|
+
await this.status();
|
|
436
|
+
if (!this.saved.openId || this.view.state === 'unauthorized')
|
|
437
|
+
throw new Error('请先登录飞书');
|
|
438
|
+
const chats = [];
|
|
439
|
+
let page = '';
|
|
440
|
+
for (let count = 0; count < 20; count++) {
|
|
441
|
+
const data = await this.json(['im', '+chat-list', '--as', 'user', '--types', 'p2p,group', '--sort', 'active_time', '--format', 'json', '--page-size', '50', ...(page ? ['--page-token', page] : [])]);
|
|
442
|
+
const items = pageItems(data, 'chats');
|
|
443
|
+
for (const item of items) {
|
|
444
|
+
const row = object(item);
|
|
445
|
+
const id = str(row.chat_id);
|
|
446
|
+
if (!id)
|
|
447
|
+
throw new Error('Missing Feishu chat ID');
|
|
448
|
+
if (!chats.some((chat) => chat.id === id))
|
|
449
|
+
chats.push({ id, name: str(row.name) || '未命名会话', selected: this.saved.selected.includes(id) });
|
|
450
|
+
}
|
|
451
|
+
if (data.has_more !== true) {
|
|
452
|
+
this.view.chats = chats;
|
|
453
|
+
return this.snapshot();
|
|
454
|
+
}
|
|
455
|
+
const next = str(data.page_token);
|
|
456
|
+
if (!next || next === page)
|
|
457
|
+
throw new Error('Invalid Feishu chat cursor');
|
|
458
|
+
page = next;
|
|
459
|
+
}
|
|
460
|
+
this.view.chats = chats;
|
|
461
|
+
throw new Error('会话列表超过本次读取上限,未完整加载');
|
|
462
|
+
}
|
|
463
|
+
async configure(chatIds, consent) {
|
|
464
|
+
if (!consent || this.view.state === 'unauthorized' || !this.saved.account || chatIds.some((id) => !this.view.chats.some((chat) => chat.id === id)))
|
|
465
|
+
throw new Error('请选择已授权的飞书会话');
|
|
466
|
+
await this.pause();
|
|
467
|
+
await this.setProcessingConsent(false, true);
|
|
468
|
+
const previous = new Set(this.saved.selected), since = this.now().toISOString();
|
|
469
|
+
this.saved.scopeConfigured = true;
|
|
470
|
+
this.saved.selected = [...new Set(chatIds)];
|
|
471
|
+
this.saved.connected = true;
|
|
472
|
+
this.saved.paused = false;
|
|
473
|
+
this.saved.captureFrom = Object.fromEntries(this.saved.selected.map((id) => [id, previous.has(id) ? this.saved.captureFrom?.[id] ?? this.saved.mentionCaptureSince ?? since : since]));
|
|
474
|
+
this.view.chats = this.view.chats.map((chat) => ({ ...chat, selected: chatIds.includes(chat.id) }));
|
|
475
|
+
this.view.state = 'ready';
|
|
476
|
+
await this.save();
|
|
477
|
+
}
|
|
478
|
+
async setProcessingConsent(consent, scopeChanged = false) {
|
|
479
|
+
const prior = this.saved.processingConsent;
|
|
480
|
+
const grant = this.options.processingGrant?.(consent, (prior?.revision ?? 0) + 1, (prior?.scope_revision ?? 0) + Number(scopeChanged));
|
|
481
|
+
if (!grant)
|
|
482
|
+
return;
|
|
483
|
+
const sources = consent ? this.saved.sources.filter(id => this.saved.selected.some(chat => id === `feishu:${this.saved.account}:${this.saved.generation}:${chat}`)) : this.saved.sources;
|
|
484
|
+
await this.options.onProcessingConsent?.(sources, grant);
|
|
485
|
+
this.saved.processingConsent = grant;
|
|
486
|
+
// Automatic capture needs live consent and starts at the grant, never at older history.
|
|
487
|
+
if (grant.extraction_provider)
|
|
488
|
+
this.saved.consentSince = this.now().toISOString();
|
|
489
|
+
else
|
|
490
|
+
delete this.saved.consentSince;
|
|
491
|
+
await this.save();
|
|
492
|
+
this.publish();
|
|
493
|
+
}
|
|
494
|
+
async sync() {
|
|
495
|
+
if (this.options.bootstrapOnly)
|
|
496
|
+
throw new Error('Feishu collection unavailable during setup');
|
|
497
|
+
if (this.pending || this.closed)
|
|
498
|
+
return;
|
|
499
|
+
const pending = this.syncNow();
|
|
500
|
+
this.pending = pending;
|
|
501
|
+
try {
|
|
502
|
+
await pending;
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
if (this.pending === pending)
|
|
506
|
+
this.pending = undefined;
|
|
507
|
+
this.publish();
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
async syncNow() {
|
|
511
|
+
if (this.busy || this.saved.paused || !this.saved.connected)
|
|
512
|
+
return;
|
|
513
|
+
this.busy = true;
|
|
514
|
+
this.active = new AbortController();
|
|
515
|
+
try {
|
|
516
|
+
await this.status();
|
|
517
|
+
if (this.view.state !== 'ready')
|
|
518
|
+
return;
|
|
519
|
+
const chats = [...this.saved.selected];
|
|
520
|
+
let next = 0;
|
|
521
|
+
let unsupported = 0;
|
|
522
|
+
const errors = [];
|
|
523
|
+
// Independent chats get four workers; a failed or capped chat cannot starve the rest.
|
|
524
|
+
await Promise.all(Array.from({ length: Math.min(4, chats.length) }, async () => {
|
|
525
|
+
while (next < chats.length && !this.active.signal.aborted) {
|
|
526
|
+
const chat = chats[next++];
|
|
527
|
+
try {
|
|
528
|
+
unsupported += await this.syncChat(chat);
|
|
529
|
+
}
|
|
530
|
+
catch (error) {
|
|
531
|
+
errors.push(error);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}));
|
|
535
|
+
if (this.active.signal.aborted)
|
|
536
|
+
return;
|
|
537
|
+
if (errors.length)
|
|
538
|
+
throw errors[0];
|
|
539
|
+
this.saved.lastSync = this.now().toISOString();
|
|
540
|
+
this.view.last_sync = this.saved.lastSync;
|
|
541
|
+
if (unsupported)
|
|
542
|
+
this.view.error = `已读取文字消息,${unsupported} 条附件或其他格式未提取正文`;
|
|
543
|
+
else
|
|
544
|
+
delete this.view.error;
|
|
545
|
+
await this.save();
|
|
546
|
+
}
|
|
547
|
+
finally {
|
|
548
|
+
this.busy = false;
|
|
549
|
+
this.active = undefined;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
async syncChat(chat) {
|
|
553
|
+
const sourceId = `feishu:${this.saved.account}:${this.saved.generation}:${chat}`;
|
|
554
|
+
if (!this.saved.sources.includes(sourceId))
|
|
555
|
+
this.saved.sources.push(sourceId);
|
|
556
|
+
const backfills = this.saved.backfills ??= {};
|
|
557
|
+
let cursor = this.saved.cursors[chat];
|
|
558
|
+
if (!cursor || cursor.end && cursor.order === undefined) {
|
|
559
|
+
// Legacy page tokens keep their ascending order; only new windows are descending.
|
|
560
|
+
backfills[chat] ??= cursor ?? { start: new Date(this.now().getTime() - 7 * 86400_000).toISOString(), end: this.now().toISOString(), order: 'desc' };
|
|
561
|
+
cursor = this.saved.cursors[chat] = { start: new Date(Date.parse(backfills[chat].end) - 60_000).toISOString(), order: 'desc' };
|
|
562
|
+
}
|
|
563
|
+
cursor.order ??= 'desc';
|
|
564
|
+
await this.save();
|
|
565
|
+
let unsupported = 0;
|
|
566
|
+
let incomplete = false;
|
|
567
|
+
// Live messages keep moving while the fixed historical window is being backfilled.
|
|
568
|
+
if (cursor.end || this.now().getTime() - Date.parse(cursor.start) >= 61_000) {
|
|
569
|
+
const result = await this.syncWindow(chat, sourceId, cursor, 2);
|
|
570
|
+
unsupported += result.unsupported;
|
|
571
|
+
incomplete ||= !result.complete;
|
|
572
|
+
}
|
|
573
|
+
if (this.active.signal.aborted)
|
|
574
|
+
return unsupported;
|
|
575
|
+
if (backfills[chat]) {
|
|
576
|
+
const result = await this.syncWindow(chat, sourceId, backfills[chat], 20);
|
|
577
|
+
unsupported += result.unsupported;
|
|
578
|
+
incomplete ||= !result.complete;
|
|
579
|
+
if (result.complete) {
|
|
580
|
+
delete backfills[chat];
|
|
581
|
+
await this.save();
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (incomplete && !this.active.signal.aborted)
|
|
585
|
+
throw new Error('消息仍有后续页,将从保存位置继续');
|
|
586
|
+
return unsupported;
|
|
587
|
+
}
|
|
588
|
+
async originalMessage(id) {
|
|
589
|
+
while (this.mentionReads.size >= 4)
|
|
590
|
+
await Promise.race(this.mentionReads).catch(() => undefined);
|
|
591
|
+
this.active?.signal.throwIfAborted();
|
|
592
|
+
const work = this.json(['api', 'GET', `/open-apis/im/v1/messages/${encodeURIComponent(id)}`, '--as', 'user', '--format', 'json']);
|
|
593
|
+
this.mentionReads.add(work);
|
|
594
|
+
try {
|
|
595
|
+
return await work;
|
|
596
|
+
}
|
|
597
|
+
finally {
|
|
598
|
+
this.mentionReads.delete(work);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
async syncWindow(chat, sourceId, cursor, pages) {
|
|
602
|
+
let unsupported = 0;
|
|
603
|
+
cursor.end ??= this.now().toISOString();
|
|
604
|
+
await this.save();
|
|
605
|
+
for (let count = 0; count < pages; count++) {
|
|
606
|
+
const data = await this.json(['im', '+chat-messages-list', '--as', 'user', '--chat-id', chat, '--start', cursor.start, '--end', cursor.end, '--order', cursor.order ?? 'asc', '--page-size', '50', '--format', 'json', '--no-reactions', ...(cursor.page ? ['--page-token', cursor.page] : [])]);
|
|
607
|
+
if (this.active.signal.aborted)
|
|
608
|
+
return { complete: false, unsupported };
|
|
609
|
+
const parsed = await Promise.allSettled(pageItems(data, 'messages').map(async (item) => {
|
|
610
|
+
const row = object(item);
|
|
611
|
+
const id = str(row.message_id);
|
|
612
|
+
if (!id || (row.chat_id && row.chat_id !== chat))
|
|
613
|
+
throw new Error('Invalid Feishu message identity');
|
|
614
|
+
if (row.deleted === true) {
|
|
615
|
+
await this.options.deleteMessage?.(sourceId, `feishu://message/${encodeURIComponent(id)}`);
|
|
616
|
+
return undefined;
|
|
617
|
+
}
|
|
618
|
+
const sender = row.sender ? object(row.sender) : {};
|
|
619
|
+
const senderId = str(sender.open_id ?? sender.openId ?? sender.id);
|
|
620
|
+
const senderType = str(sender.sender_type ?? sender.type);
|
|
621
|
+
if ((senderType && senderType !== 'user') || !senderId.startsWith('ou_'))
|
|
622
|
+
return undefined;
|
|
623
|
+
const text = messageText(row);
|
|
624
|
+
if (text === null) {
|
|
625
|
+
unsupported++;
|
|
626
|
+
return undefined;
|
|
627
|
+
}
|
|
628
|
+
if (!text)
|
|
629
|
+
throw new Error('Missing Feishu message body');
|
|
630
|
+
let mention = structuredMention(row, this.saved.openId);
|
|
631
|
+
let mentionIds = Array.isArray(row.mentions) ? row.mentions.map(item => str(object(item).id)).filter(id => id.startsWith('ou_')).slice(0, 50) : [];
|
|
632
|
+
if (senderId !== this.saved.openId && mention === 'unknown' && (text.includes('@') || (row.msg_type ?? row.message_type) === 'post')) {
|
|
633
|
+
try {
|
|
634
|
+
const raw = await this.originalMessage(id);
|
|
635
|
+
const original = Array.isArray(raw.items) ? raw.items.map(object).find(item => item.message_id === id) : undefined;
|
|
636
|
+
if (original && (!original.chat_id || original.chat_id === chat)) {
|
|
637
|
+
for (const key of ['thread_id', 'parent_id', 'root_id', 'upper_message_id'])
|
|
638
|
+
if (row[key] === undefined && original[key] !== undefined)
|
|
639
|
+
row[key] = original[key];
|
|
640
|
+
mention = structuredMention(original, this.saved.openId);
|
|
641
|
+
if (Array.isArray(original.mentions))
|
|
642
|
+
mentionIds = original.mentions.map(item => str(object(item).id)).filter(id => id.startsWith('ou_')).slice(0, 50);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
catch {
|
|
646
|
+
this.active.signal.throwIfAborted(); /* Preserve unknown; rendered @names are not identity evidence. */
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
// A message you wrote yourself never addresses you.
|
|
650
|
+
if (senderId === this.saved.openId)
|
|
651
|
+
mention = 'none';
|
|
652
|
+
const rawTime = row.create_time_iso ?? row.create_time;
|
|
653
|
+
const numeric = Number(rawTime);
|
|
654
|
+
const time = Number.isFinite(numeric) ? numeric < 1e12 ? numeric * 1000 : numeric : Date.parse(str(rawTime));
|
|
655
|
+
if (!Number.isFinite(time) || time <= 0)
|
|
656
|
+
throw new Error('Invalid Feishu message time');
|
|
657
|
+
return { ...(this.saved.processingConsent ? { processing_consent: this.saved.processingConsent } : {}), id: hash(`${sourceId}:${id}:${hash(text)}`), source_id: sourceId, source_kind: 'im', ...(typeof row.message_app_link === 'string' && row.message_app_link.length <= 4096 && row.message_app_link.startsWith('https://') ? { source_url: row.message_app_link } : {}), message_id: id, ...Object.fromEntries(['thread_id', 'parent_id', 'root_id', 'upper_message_id'].flatMap(key => { const value = row[key] ?? (key === 'parent_id' ? row.reply_to : undefined); return typeof value === 'string' && value.length > 0 && value.length <= 256 ? [[key, value]] : []; })), chat_id: chat, recipient_id: this.saved.openId, sender_name: str(sender.name ?? row.sender_name ?? (senderId === this.saved.openId ? this.saved.name : '')).slice(0, 120), mention_ids: mentionIds, mention, auto_capture: mention === 'direct' && time >= Math.max(Date.parse(this.saved.captureFrom?.[chat] ?? this.saved.mentionCaptureSince), Date.parse(this.saved.consentSince ?? '')), locator: `feishu://message/${encodeURIComponent(id)}`, raw_text: text, observed_at: new Date(time).toISOString(), retention_until: new Date(time + 30 * 86400_000).toISOString(), sender_id: senderId, account_id: this.saved.account };
|
|
658
|
+
}));
|
|
659
|
+
const messages = [];
|
|
660
|
+
for (const result of parsed) {
|
|
661
|
+
if (result.status === 'rejected')
|
|
662
|
+
throw result.reason;
|
|
663
|
+
if (result.value)
|
|
664
|
+
messages.push(result.value);
|
|
665
|
+
}
|
|
666
|
+
if (this.options.ingestBatch) {
|
|
667
|
+
if (messages.length)
|
|
668
|
+
await this.options.ingestBatch(messages, this.active.signal);
|
|
669
|
+
}
|
|
670
|
+
else
|
|
671
|
+
for (const message of messages) {
|
|
672
|
+
if (this.active.signal.aborted)
|
|
673
|
+
return { complete: false, unsupported };
|
|
674
|
+
await this.options.ingest(message);
|
|
675
|
+
}
|
|
676
|
+
if (this.active.signal.aborted)
|
|
677
|
+
return { complete: false, unsupported };
|
|
678
|
+
if (data.has_more !== true) {
|
|
679
|
+
cursor.start = new Date(Date.parse(cursor.end) - 60_000).toISOString();
|
|
680
|
+
delete cursor.end;
|
|
681
|
+
delete cursor.page;
|
|
682
|
+
cursor.order = 'desc';
|
|
683
|
+
await this.save();
|
|
684
|
+
return { complete: true, unsupported };
|
|
685
|
+
}
|
|
686
|
+
const next = str(data.page_token);
|
|
687
|
+
if (!next || next === cursor.page)
|
|
688
|
+
throw new Error('Invalid Feishu message cursor');
|
|
689
|
+
cursor.page = next;
|
|
690
|
+
await this.save();
|
|
691
|
+
}
|
|
692
|
+
return { complete: false, unsupported };
|
|
693
|
+
}
|
|
694
|
+
async pause() {
|
|
695
|
+
this.saved.paused = true;
|
|
696
|
+
this.view.state = 'paused';
|
|
697
|
+
this.active?.abort();
|
|
698
|
+
if (!this.saved.outbound) {
|
|
699
|
+
this.listenerController?.abort();
|
|
700
|
+
await this.listener?.catch(() => { });
|
|
701
|
+
}
|
|
702
|
+
await this.pending?.catch(() => { });
|
|
703
|
+
await this.save();
|
|
704
|
+
}
|
|
705
|
+
async disconnect() {
|
|
706
|
+
this.saved.outbound = false;
|
|
707
|
+
if (this.saved.outboundIdentity) {
|
|
708
|
+
this.saved.outboundIdentity.valid = false;
|
|
709
|
+
this.saved.outboundIdentity.generation++;
|
|
710
|
+
}
|
|
711
|
+
this.view.notification_enabled = false;
|
|
712
|
+
this.view.notification_ready = false;
|
|
713
|
+
await this.pause();
|
|
714
|
+
await this.setProcessingConsent(false);
|
|
715
|
+
this.saved.connected = false;
|
|
716
|
+
this.saved.bot = false;
|
|
717
|
+
this.view.bot_enabled = false;
|
|
718
|
+
this.view.state = 'disconnected';
|
|
719
|
+
this.deviceCode = undefined;
|
|
720
|
+
delete this.view.verification_url;
|
|
721
|
+
await this.save();
|
|
722
|
+
try {
|
|
723
|
+
await this.stopOwnedBus();
|
|
724
|
+
}
|
|
725
|
+
finally {
|
|
726
|
+
await this.json(['auth', 'logout', '--json']);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
async deleteHistory() {
|
|
730
|
+
if (this.options.bootstrapOnly)
|
|
731
|
+
throw new Error('Feishu collection unavailable during setup');
|
|
732
|
+
await this.pause();
|
|
733
|
+
const sources = [...this.saved.sources];
|
|
734
|
+
// Persist the new generation before deletion so a crash cannot resume into a fenced source.
|
|
735
|
+
this.saved.generation++;
|
|
736
|
+
this.saved.cursors = {};
|
|
737
|
+
this.saved.backfills = {};
|
|
738
|
+
this.saved.outboundReceipts = {};
|
|
739
|
+
this.saved.deliveries = {};
|
|
740
|
+
this.saved.actions = [];
|
|
741
|
+
delete this.saved.lastSync;
|
|
742
|
+
delete this.view.last_sync;
|
|
743
|
+
await this.save();
|
|
744
|
+
for (const source of sources) {
|
|
745
|
+
await this.options.deleteSource(source);
|
|
746
|
+
this.saved.sources = this.saved.sources.filter((item) => item !== source);
|
|
747
|
+
await this.save();
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
callbackReady() { return !!(this.saved.outbound && this.saved.outboundIdentity?.valid) || this.saved.bot && this.saved.connected && !this.saved.paused; }
|
|
751
|
+
notificationBinding(userScope) {
|
|
752
|
+
const identity = this.saved.outboundIdentity;
|
|
753
|
+
if (!identity)
|
|
754
|
+
return null;
|
|
755
|
+
return { id: 'feishu', provider: 'feishu', user_scope: userScope, generation: identity.generation, identity: identity.account, status: identity.valid && (this.saved.outbound || this.saved.bot) ? 'ready' : 'unavailable' };
|
|
756
|
+
}
|
|
757
|
+
async inspectNotificationBinding(binding, signal) {
|
|
758
|
+
await this.status(signal);
|
|
759
|
+
const current = this.notificationBinding(binding.user_scope);
|
|
760
|
+
return !!current && current.status === 'ready' && current.identity === binding.identity && current.generation === binding.generation;
|
|
761
|
+
}
|
|
762
|
+
async sendNotificationPart(part, context) {
|
|
763
|
+
try {
|
|
764
|
+
if (!await this.inspectNotificationBinding(context.binding, context.signal))
|
|
765
|
+
return { kind: 'blocked', reason: 'binding_changed' };
|
|
766
|
+
}
|
|
767
|
+
catch {
|
|
768
|
+
return { kind: 'blocked', reason: 'identity_unavailable' };
|
|
769
|
+
}
|
|
770
|
+
const identity = this.saved.outboundIdentity;
|
|
771
|
+
const nonce = hash(context.idempotency_key).slice(0, 40);
|
|
772
|
+
const actions = context.notification.feedback.map(action => ({ tag: 'button', text: { tag: 'plain_text', content: action === 'open' ? '标为已查看' : action === 'snooze' ? '稍后提醒' : '忽略' }, value: { nonce, proposal_id: context.notification.source.id, action: action === 'dismiss' ? 'ignore' : action } }));
|
|
773
|
+
const card = { config: { wide_screen_mode: true }, header: { title: { tag: 'plain_text', content: part.title } }, elements: [{ tag: 'div', text: { tag: 'plain_text', content: part.body } }, ...(actions.length ? [{ tag: 'action', actions }] : [])] };
|
|
774
|
+
if (context.signal.aborted)
|
|
775
|
+
return { kind: 'retryable', definitelyNotAccepted: true };
|
|
776
|
+
try {
|
|
777
|
+
const result = parseFeishuJson(await this.run(['im', '+messages-send', '--as', 'bot', '--user-id', identity.openId, '--msg-type', 'interactive', '--content', JSON.stringify(card), '--idempotency-key', nonce, '--format', 'json'], { signal: context.signal }));
|
|
778
|
+
const message = str(result.message_id), chat = str(result.chat_id);
|
|
779
|
+
if (!message || !chat)
|
|
780
|
+
return { kind: 'unknown', reason: 'missing_receipt' };
|
|
781
|
+
this.saved.outboundReceipts ??= {};
|
|
782
|
+
this.saved.outboundReceipts[nonce] = { proposal: context.notification.source.id, nonce, message, chat, generation: identity.generation, revision: context.notification.revision, occurrence: context.notification.occurrence, feedback: [...context.notification.feedback] };
|
|
783
|
+
for (const key of Object.keys(this.saved.outboundReceipts).slice(0, -10000))
|
|
784
|
+
delete this.saved.outboundReceipts[key];
|
|
785
|
+
await this.save();
|
|
786
|
+
return { kind: 'accepted', receipt: { message_id: message, chat_id: chat } };
|
|
787
|
+
}
|
|
788
|
+
catch {
|
|
789
|
+
return { kind: 'unknown', reason: 'feishu_send_uncertain' };
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
async sendReminder(proposal) {
|
|
793
|
+
if (this.pending || this.closed)
|
|
794
|
+
return false;
|
|
795
|
+
this.active = new AbortController();
|
|
796
|
+
const task = this.sendReminderNow(proposal);
|
|
797
|
+
const pending = task.then(() => { });
|
|
798
|
+
this.pending = pending;
|
|
799
|
+
try {
|
|
800
|
+
return await task;
|
|
801
|
+
}
|
|
802
|
+
finally {
|
|
803
|
+
await pending.catch(() => { });
|
|
804
|
+
if (this.pending === pending)
|
|
805
|
+
this.pending = undefined;
|
|
806
|
+
this.active = undefined;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
async sendReminderNow(proposal) {
|
|
810
|
+
if (!this.saved.bot || !this.saved.connected || this.saved.paused || !this.saved.openId)
|
|
811
|
+
return false;
|
|
812
|
+
await this.status();
|
|
813
|
+
if (this.view.state !== 'ready' || this.active?.signal.aborted)
|
|
814
|
+
return false;
|
|
815
|
+
const delivery = this.saved.deliveries[proposal.id] ?? { nonce: randomUUID() };
|
|
816
|
+
if (delivery.message)
|
|
817
|
+
return true;
|
|
818
|
+
this.saved.deliveries[proposal.id] = delivery;
|
|
819
|
+
await this.save();
|
|
820
|
+
const card = { config: { wide_screen_mode: true }, header: { title: { tag: 'plain_text', content: proposal.title.slice(0, 150) } }, elements: [
|
|
821
|
+
{ tag: 'div', text: { tag: 'plain_text', content: proposal.body.slice(0, 2000) } },
|
|
822
|
+
{ tag: 'action', actions: [['open', '在 Nova 中查看'], ['snooze', '稍后提醒'], ['ignore', '忽略']].map(([action, label]) => ({ tag: 'button', text: { tag: 'plain_text', content: label }, value: { nonce: delivery.nonce, proposal_id: proposal.id, action } })) },
|
|
823
|
+
] };
|
|
824
|
+
const result = await this.json(['im', '+messages-send', '--as', 'bot', '--user-id', this.saved.openId, '--msg-type', 'interactive', '--content', JSON.stringify(card), '--idempotency-key', delivery.nonce, '--format', 'json']);
|
|
825
|
+
delivery.message = str(result.message_id);
|
|
826
|
+
delivery.chat = str(result.chat_id);
|
|
827
|
+
if (!delivery.message || !delivery.chat)
|
|
828
|
+
throw new Error('Missing Feishu delivery receipt');
|
|
829
|
+
await this.save();
|
|
830
|
+
return true;
|
|
831
|
+
}
|
|
832
|
+
async consumeActions() {
|
|
833
|
+
if (this.options.bootstrapOnly)
|
|
834
|
+
throw new Error('Feishu collection unavailable during setup');
|
|
835
|
+
if (this.listener || this.closed || !this.callbackReady())
|
|
836
|
+
return;
|
|
837
|
+
const controller = new AbortController();
|
|
838
|
+
this.listenerController = controller;
|
|
839
|
+
this.listenerApp = this.currentApp;
|
|
840
|
+
let callbacks = Promise.resolve();
|
|
841
|
+
let queued = 0;
|
|
842
|
+
const task = this.run(['event', 'consume', 'card.action.trigger', '--as', 'bot', '--quiet', '--timeout', '0s', '--max-events', '0'], {
|
|
843
|
+
signal: controller.signal,
|
|
844
|
+
onLine: (line) => {
|
|
845
|
+
if (++queued > 200) {
|
|
846
|
+
controller.abort();
|
|
847
|
+
throw new Error('Feishu callback queue limit');
|
|
848
|
+
}
|
|
849
|
+
const event = jsonObject(line);
|
|
850
|
+
callbacks = callbacks.then(async () => { await this.acceptAction(event); }).catch(() => { this.view.error = '飞书操作未保存,请在 Nova 中处理'; }).finally(() => { queued--; this.publish(); });
|
|
851
|
+
},
|
|
852
|
+
});
|
|
853
|
+
const listener = task.then(() => { });
|
|
854
|
+
this.listener = listener;
|
|
855
|
+
try {
|
|
856
|
+
await listener;
|
|
857
|
+
}
|
|
858
|
+
finally {
|
|
859
|
+
if (this.listener === listener)
|
|
860
|
+
this.listener = undefined;
|
|
861
|
+
if (this.listenerController === controller)
|
|
862
|
+
this.listenerController = undefined;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
async acceptAction(event) {
|
|
866
|
+
if (this.closed || !this.callbackReady() || event.operator_id !== (this.saved.outbound ? this.saved.outboundIdentity?.openId : this.saved.openId) || event.type !== 'card.action.trigger')
|
|
867
|
+
return false;
|
|
868
|
+
const action = jsonObject(str(event.action_value));
|
|
869
|
+
const proposalId = str(action.proposal_id);
|
|
870
|
+
const outbound = this.saved.outboundReceipts?.[str(action.nonce)];
|
|
871
|
+
if (outbound && (outbound.generation !== this.saved.outboundIdentity?.generation || outbound.proposal !== proposalId))
|
|
872
|
+
return false;
|
|
873
|
+
const delivery = outbound ?? this.saved.deliveries[proposalId];
|
|
874
|
+
const eventId = str(event.event_id);
|
|
875
|
+
if (!delivery || !eventId || this.saved.actions.includes(eventId) || action.nonce !== delivery.nonce || event.message_id !== delivery.message || event.chat_id !== delivery.chat)
|
|
876
|
+
return false;
|
|
877
|
+
if (action.action !== 'open' && action.action !== 'snooze' && action.action !== 'ignore')
|
|
878
|
+
return false;
|
|
879
|
+
if (outbound && (!outbound.revision || !outbound.occurrence || !outbound.feedback?.includes(action.action === 'ignore' ? 'dismiss' : action.action)))
|
|
880
|
+
return false;
|
|
881
|
+
// Host must reuse its feed action ledger; 'open' is navigation, never execution authorization.
|
|
882
|
+
const account = this.saved.account;
|
|
883
|
+
const generation = this.saved.generation;
|
|
884
|
+
await this.options.onAction({ proposal_id: proposalId, action: action.action, event_id: eventId, ...(outbound ? { notification: { revision: outbound.revision, occurrence: outbound.occurrence } } : {}) });
|
|
885
|
+
if (!this.closed && this.saved.account === account && this.saved.generation === generation) {
|
|
886
|
+
this.saved.actions.push(eventId);
|
|
887
|
+
await this.save();
|
|
888
|
+
}
|
|
889
|
+
return true;
|
|
890
|
+
}
|
|
891
|
+
async command(method, params = {}) {
|
|
892
|
+
if (!this.view.available && method !== 'feishu.status')
|
|
893
|
+
throw new Error(this.view.error ?? '飞书 CLI 不可用');
|
|
894
|
+
if (this.options.bootstrapOnly && !['feishu.status', 'feishu.app.start', 'feishu.app.status', 'feishu.app.cancel', 'feishu.app.bind', 'feishu.login', 'feishu.complete'].includes(method))
|
|
895
|
+
throw new Error('飞书同步需要运行中的模型服务');
|
|
896
|
+
switch (method) {
|
|
897
|
+
case 'feishu.app.bind':
|
|
898
|
+
if (Object.keys(params).sort().join(',') !== 'app_id,app_secret' || typeof params.app_id !== 'string' || !/^cli_[A-Za-z0-9]{1,128}$/u.test(params.app_id)
|
|
899
|
+
|| typeof params.app_secret !== 'string' || !params.app_secret.trim() || params.app_secret.length > 4096 || /[\0\r\n]/u.test(params.app_secret))
|
|
900
|
+
throw new Error('Invalid app binding');
|
|
901
|
+
return this.beginAppSetup({ app_id: params.app_id, app_secret: params.app_secret });
|
|
902
|
+
case 'feishu.app.start':
|
|
903
|
+
case 'feishu.app.status':
|
|
904
|
+
case 'feishu.app.cancel':
|
|
905
|
+
if (Object.keys(params).length)
|
|
906
|
+
throw new Error('Invalid app setup request');
|
|
907
|
+
return method === 'feishu.app.start' ? this.beginAppSetup() : method === 'feishu.app.cancel' ? this.cancelAppSetup() : this.setupSnapshot();
|
|
908
|
+
case 'feishu.status':
|
|
909
|
+
await this.status();
|
|
910
|
+
return this.setupSnapshot();
|
|
911
|
+
case 'feishu.notification.login': return this.beginLogin(true);
|
|
912
|
+
case 'feishu.notification.configure':
|
|
913
|
+
if (typeof params.enabled !== 'boolean')
|
|
914
|
+
throw Error('invalid_request');
|
|
915
|
+
await this.status();
|
|
916
|
+
if (params.enabled && !this.saved.outboundIdentity?.valid)
|
|
917
|
+
throw Error('飞书身份未验证');
|
|
918
|
+
this.saved.outbound = params.enabled;
|
|
919
|
+
this.view.notification_enabled = params.enabled;
|
|
920
|
+
if (!this.callbackReady()) {
|
|
921
|
+
this.listenerController?.abort();
|
|
922
|
+
await this.listener?.catch(() => { });
|
|
923
|
+
}
|
|
924
|
+
await this.save();
|
|
925
|
+
break;
|
|
926
|
+
case 'feishu.login': return this.beginLogin();
|
|
927
|
+
case 'feishu.complete':
|
|
928
|
+
case 'feishu.auth.complete': return this.completeLogin();
|
|
929
|
+
case 'feishu.chats': return this.listChats();
|
|
930
|
+
case 'feishu.consent': {
|
|
931
|
+
if (typeof params.consent !== 'boolean')
|
|
932
|
+
throw Error('invalid_request');
|
|
933
|
+
await this.setProcessingConsent(params.consent);
|
|
934
|
+
break;
|
|
935
|
+
}
|
|
936
|
+
case 'feishu.configure': {
|
|
937
|
+
if (!Array.isArray(params.chat_ids) || !params.chat_ids.every((id) => typeof id === 'string'))
|
|
938
|
+
throw new Error('Invalid chat selection');
|
|
939
|
+
await this.configure(params.chat_ids, params.consent === true);
|
|
940
|
+
break;
|
|
941
|
+
}
|
|
942
|
+
case 'feishu.sync':
|
|
943
|
+
await this.sync();
|
|
944
|
+
break;
|
|
945
|
+
case 'feishu.pause':
|
|
946
|
+
await this.pause();
|
|
947
|
+
break;
|
|
948
|
+
case 'feishu.resume':
|
|
949
|
+
await this.status();
|
|
950
|
+
if (this.view.state === 'unauthorized' || !this.saved.connected)
|
|
951
|
+
throw new Error('请先重新连接飞书');
|
|
952
|
+
this.saved.paused = false;
|
|
953
|
+
this.view.state = 'ready';
|
|
954
|
+
await this.save();
|
|
955
|
+
break;
|
|
956
|
+
case 'feishu.disconnect':
|
|
957
|
+
await this.disconnect();
|
|
958
|
+
break;
|
|
959
|
+
case 'feishu.delete':
|
|
960
|
+
await this.deleteHistory();
|
|
961
|
+
break;
|
|
962
|
+
case 'feishu.bot.configure':
|
|
963
|
+
if (typeof params.enabled !== 'boolean' || !this.saved.connected)
|
|
964
|
+
throw new Error('请先连接飞书');
|
|
965
|
+
this.saved.bot = params.enabled;
|
|
966
|
+
this.view.bot_enabled = this.saved.bot;
|
|
967
|
+
if (!this.saved.bot) {
|
|
968
|
+
this.listenerController?.abort();
|
|
969
|
+
await this.listener?.catch(() => { });
|
|
970
|
+
}
|
|
971
|
+
await this.save();
|
|
972
|
+
break;
|
|
973
|
+
default: throw new Error('Unsupported Feishu operation');
|
|
974
|
+
}
|
|
975
|
+
this.startListener();
|
|
976
|
+
this.publish();
|
|
977
|
+
return this.snapshot();
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
//# sourceMappingURL=index.js.map
|