nova-personal-agent-server 0.4.1 → 1.0.2

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.
Files changed (327) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +10 -0
  3. package/bin/nova-space-host.mjs +4 -0
  4. package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
  5. package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
  6. package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
  7. package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
  8. package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
  9. package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
  10. package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
  11. package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
  12. package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
  13. package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
  14. package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
  15. package/node_modules/@nova-personal-agent/relay/package.json +1 -0
  16. package/package.json +11 -4
  17. package/runtime/dist/src/cascaded-text-provider.js +8 -3
  18. package/runtime/dist/src/composition/assembly.js +133 -35
  19. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
  20. package/runtime/dist/src/composition/production-composition.js +57 -21
  21. package/runtime/dist/src/composition/realtime-assembly.js +160 -52
  22. package/runtime/dist/src/composition/soul-context.js +22 -0
  23. package/runtime/dist/src/config/capability-registry.js +48 -3
  24. package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
  25. package/runtime/dist/src/config/config.js +541 -128
  26. package/runtime/dist/src/config/credential-rotation.js +26 -0
  27. package/runtime/dist/src/config/data-root.js +764 -0
  28. package/runtime/dist/src/config/diagnostics.js +3 -1
  29. package/runtime/dist/src/config/environment-contract.js +190 -188
  30. package/runtime/dist/src/config/model-routes.js +140 -0
  31. package/runtime/dist/src/config/voice-credentials.js +55 -0
  32. package/runtime/dist/src/connectors/composio/index.js +9 -0
  33. package/runtime/dist/src/connectors/feishu/index.js +258 -44
  34. package/runtime/dist/src/connectors/macos/mail.js +7 -3
  35. package/runtime/dist/src/connectors/macos/reader.js +3 -1
  36. package/runtime/dist/src/conversation-voice-provider.js +5 -2
  37. package/runtime/dist/src/core/causal-runtime.js +38 -3
  38. package/runtime/dist/src/core/context-view.js +7 -0
  39. package/runtime/dist/src/core/guards.js +32 -0
  40. package/runtime/dist/src/core/runtime.js +3 -0
  41. package/runtime/dist/src/core/schedule-tools.js +2 -2
  42. package/runtime/dist/src/core/source-processing-instructions.js +2 -2
  43. package/runtime/dist/src/core/source-processing-tools.js +3 -1
  44. package/runtime/dist/src/core/tool-schema.js +42 -7
  45. package/runtime/dist/src/desktop/desktop-camera.js +3 -5
  46. package/runtime/dist/src/desktop/desktop-control.js +41 -8
  47. package/runtime/dist/src/desktop/desktop-session.js +90 -19
  48. package/runtime/dist/src/desktop/desktop-wire.js +5 -7
  49. package/runtime/dist/src/desktop/startup-error.js +18 -16
  50. package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
  51. package/runtime/dist/src/desktop-entry.js +6 -2
  52. package/runtime/dist/src/desktop.js +5 -1
  53. package/runtime/dist/src/device/attempt.js +65 -0
  54. package/runtime/dist/src/device/authority.js +159 -0
  55. package/runtime/dist/src/device/gateway.js +87 -0
  56. package/runtime/dist/src/device/ledger.js +91 -0
  57. package/runtime/dist/src/device/ownership.js +92 -0
  58. package/runtime/dist/src/device/port.js +2 -0
  59. package/runtime/dist/src/device/schedule-ownership.js +103 -0
  60. package/runtime/dist/src/executors/acp/transport.js +2 -0
  61. package/runtime/dist/src/executors/browser.js +4 -3
  62. package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
  63. package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
  64. package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
  65. package/runtime/dist/src/executors/codex/common.js +1 -1
  66. package/runtime/dist/src/executors/codex/contract.js +12 -16
  67. package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
  68. package/runtime/dist/src/executors/codex/factory.js +54 -32
  69. package/runtime/dist/src/executors/codex/host-config.js +69 -20
  70. package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
  71. package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
  72. package/runtime/dist/src/executors/codex/process-owner.js +4 -6
  73. package/runtime/dist/src/executors/codex/production-host.js +33 -34
  74. package/runtime/dist/src/executors/codex/protocol.js +9 -14
  75. package/runtime/dist/src/executors/codex/session-title.js +6 -8
  76. package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
  77. package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
  78. package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
  79. package/runtime/dist/src/executors/coding/intake.js +12 -7
  80. package/runtime/dist/src/executors/computer-backend.js +18 -10
  81. package/runtime/dist/src/executors/computer-config.js +32 -0
  82. package/runtime/dist/src/executors/computer-device.js +68 -16
  83. package/runtime/dist/src/executors/computer-worker.js +18 -6
  84. package/runtime/dist/src/executors/computer.js +29 -56
  85. package/runtime/dist/src/executors/device-lock.js +14 -5
  86. package/runtime/dist/src/executors/gui-execution.js +2 -0
  87. package/runtime/dist/src/executors/index.js +0 -1
  88. package/runtime/dist/src/executors/mobile.js +9 -8
  89. package/runtime/dist/src/executors/native-process.js +4 -0
  90. package/runtime/dist/src/executors/search.js +3 -5
  91. package/runtime/dist/src/executors/task-resources.js +21 -0
  92. package/runtime/dist/src/executors/watcher.js +2 -4
  93. package/runtime/dist/src/experience/host.js +179 -0
  94. package/runtime/dist/src/index.js +2 -0
  95. package/runtime/dist/src/knowledge/assembly.js +3 -4
  96. package/runtime/dist/src/knowledge/embeddings.js +50 -34
  97. package/runtime/dist/src/knowledge/service.js +1 -0
  98. package/runtime/dist/src/knowledge/store-client.js +1 -6
  99. package/runtime/dist/src/knowledge/store-worker.js +1 -3
  100. package/runtime/dist/src/mem0/resource.js +25 -0
  101. package/runtime/dist/src/mem0/store-worker.js +234 -21
  102. package/runtime/dist/src/memory/consumer.js +31 -0
  103. package/runtime/dist/src/memory/engine-worker.js +210 -0
  104. package/runtime/dist/src/memory/entry.js +8 -1
  105. package/runtime/dist/src/memory/explicit-memory.js +20 -0
  106. package/runtime/dist/src/memory/factory.js +30 -15
  107. package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
  108. package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
  109. package/runtime/dist/src/memory/prerecall-port.js +27 -0
  110. package/runtime/dist/src/memory/prerecall.js +1 -1
  111. package/runtime/dist/src/memory/production-engine.js +151 -0
  112. package/runtime/dist/src/memory/provenance.js +1 -0
  113. package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
  114. package/runtime/dist/src/memory/retrieval.js +107 -22
  115. package/runtime/dist/src/memory/sensitivity.js +6 -2
  116. package/runtime/dist/src/memory/source-retrieval.js +11 -0
  117. package/runtime/dist/src/memory/tool-capabilities.js +46 -0
  118. package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
  119. package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
  120. package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
  121. package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
  122. package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
  123. package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
  124. package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
  125. package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
  126. package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
  127. package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
  128. package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
  129. package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
  130. package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
  131. package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
  132. package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
  133. package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
  134. package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
  135. package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
  136. package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
  137. package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
  138. package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
  139. package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
  140. package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
  141. package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
  142. package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
  143. package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
  144. package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
  145. package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
  146. package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
  147. package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
  148. package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
  149. package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
  150. package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
  151. package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
  152. package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
  153. package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
  154. package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
  155. package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
  156. package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
  157. package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
  158. package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
  159. package/runtime/dist/src/memory-ledger/store-client.js +235 -37
  160. package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
  161. package/runtime/dist/src/memory-ledger/store.js +91 -1
  162. package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
  163. package/runtime/dist/src/memory-substrate/diary.js +27 -0
  164. package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
  165. package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
  166. package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
  167. package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
  168. package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
  169. package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
  170. package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
  171. package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
  172. package/runtime/dist/src/memory-substrate/migration.js +2 -0
  173. package/runtime/dist/src/memory-substrate/purge.js +12 -2
  174. package/runtime/dist/src/memory-substrate/resource.js +514 -129
  175. package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
  176. package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
  177. package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
  178. package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
  179. package/runtime/dist/src/memory-substrate/source-state.js +8 -0
  180. package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
  181. package/runtime/dist/src/memory-substrate/store.js +125 -23
  182. package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
  183. package/runtime/dist/src/model/goal-writer.js +80 -0
  184. package/runtime/dist/src/model/jev-client.js +24 -13
  185. package/runtime/dist/src/model/model-adapters.js +2 -3
  186. package/runtime/dist/src/model/model-catalog.js +80 -0
  187. package/runtime/dist/src/model/model-gateway.js +47 -18
  188. package/runtime/dist/src/model/model-purpose.js +3 -4
  189. package/runtime/dist/src/model/personal-writer.js +536 -44
  190. package/runtime/dist/src/model/proactivity.js +50 -6
  191. package/runtime/dist/src/model/responses-model-gateway.js +59 -0
  192. package/runtime/dist/src/model/task-verifier.js +3 -3
  193. package/runtime/dist/src/model/timeline-anchors.js +77 -0
  194. package/runtime/dist/src/model/timeline-perspective.js +13 -0
  195. package/runtime/dist/src/model/timeline-selection.js +182 -0
  196. package/runtime/dist/src/model/understanding-writer.js +27 -0
  197. package/runtime/dist/src/model/vision-capability.js +3 -1
  198. package/runtime/dist/src/model/workbench-writer.js +96 -0
  199. package/runtime/dist/src/news/feeds.js +6 -10
  200. package/runtime/dist/src/news/interests.js +23 -0
  201. package/runtime/dist/src/news/service.js +87 -31
  202. package/runtime/dist/src/news/sources.json +116 -0
  203. package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
  204. package/runtime/dist/src/notifications/content.js +41 -0
  205. package/runtime/dist/src/notifications/contracts.js +4 -2
  206. package/runtime/dist/src/notifications/feed.js +6 -2
  207. package/runtime/dist/src/notifications/service.js +27 -14
  208. package/runtime/dist/src/notifications/store.js +3 -1
  209. package/runtime/dist/src/personal-agent/app-context.js +39 -4
  210. package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
  211. package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
  212. package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
  213. package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
  214. package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
  215. package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
  216. package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
  217. package/runtime/dist/src/personal-agent/contracts.js +24 -4
  218. package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
  219. package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
  220. package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
  221. package/runtime/dist/src/personal-agent/conversations.js +71 -15
  222. package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
  223. package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
  224. package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
  225. package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2379 -223
  227. package/runtime/dist/src/personal-agent/identity-context.js +33 -0
  228. package/runtime/dist/src/personal-agent/life.js +129 -11
  229. package/runtime/dist/src/personal-agent/local-shell.js +181 -0
  230. package/runtime/dist/src/personal-agent/local-tools.js +234 -0
  231. package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
  232. package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
  233. package/runtime/dist/src/personal-agent/project-digests.js +7 -3
  234. package/runtime/dist/src/personal-agent/project-history.js +36 -0
  235. package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
  236. package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
  237. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
  238. package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
  239. package/runtime/dist/src/personal-agent/sources.js +9 -1
  240. package/runtime/dist/src/personal-agent/store.js +124 -14
  241. package/runtime/dist/src/personal-agent/task-loop.js +3 -0
  242. package/runtime/dist/src/personal-agent/tasks.js +16 -4
  243. package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
  244. package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
  245. package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
  246. package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
  247. package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
  248. package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
  249. package/runtime/dist/src/personal-agent/understanding.js +7 -22
  250. package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
  251. package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
  252. package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
  253. package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
  254. package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
  255. package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
  256. package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
  257. package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +10 -8
  259. package/runtime/dist/src/projects/project-store.js +36 -4
  260. package/runtime/dist/src/realtime/bridge.js +77 -8
  261. package/runtime/dist/src/realtime/capabilities.js +19 -0
  262. package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
  263. package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
  264. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
  265. package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
  266. package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
  267. package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
  268. package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
  269. package/runtime/dist/src/realtime/evidence.js +1 -1
  270. package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
  271. package/runtime/dist/src/realtime/gemini.js +14 -3
  272. package/runtime/dist/src/realtime/host-delivery.js +37 -4
  273. package/runtime/dist/src/realtime/protocol.js +18 -3
  274. package/runtime/dist/src/realtime/provider-projection.js +4 -1
  275. package/runtime/dist/src/realtime/provider-session.js +73 -16
  276. package/runtime/dist/src/realtime/qwen-transport.js +35 -4
  277. package/runtime/dist/src/realtime/qwen.js +144 -9
  278. package/runtime/dist/src/realtime/service-state.js +0 -1
  279. package/runtime/dist/src/realtime/service.js +93 -7
  280. package/runtime/dist/src/realtime/session.js +39 -32
  281. package/runtime/dist/src/realtime/sglang-native.js +214 -0
  282. package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
  283. package/runtime/dist/src/realtime/telemetry.js +6 -3
  284. package/runtime/dist/src/realtime/tool-continuations.js +84 -7
  285. package/runtime/dist/src/realtime/transport.js +17 -0
  286. package/runtime/dist/src/realtime/usage.js +33 -17
  287. package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
  288. package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
  289. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
  290. package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
  291. package/runtime/dist/src/server/aoq-chat-server.js +1 -1
  292. package/runtime/dist/src/server/client-server.js +21 -0
  293. package/runtime/dist/src/server-entry.js +3 -0
  294. package/runtime/dist/src/space-host/admin-socket.js +115 -0
  295. package/runtime/dist/src/space-host/audio-owner.js +44 -0
  296. package/runtime/dist/src/space-host/cli.js +195 -0
  297. package/runtime/dist/src/space-host/config.js +247 -0
  298. package/runtime/dist/src/space-host/context-input.js +12 -0
  299. package/runtime/dist/src/space-host/contracts.js +10 -0
  300. package/runtime/dist/src/space-host/host-admin.js +114 -0
  301. package/runtime/dist/src/space-host/key-delivery.js +28 -0
  302. package/runtime/dist/src/space-host/mobile-tools.js +9 -0
  303. package/runtime/dist/src/space-host/model-settings.js +213 -0
  304. package/runtime/dist/src/space-host/projection.js +37 -0
  305. package/runtime/dist/src/space-host/push.js +137 -0
  306. package/runtime/dist/src/space-host/relay-transport.js +55 -0
  307. package/runtime/dist/src/space-host/service.js +841 -0
  308. package/runtime/dist/src/space-host/voice-crypto.js +240 -0
  309. package/runtime/dist/src/space-host/voice.js +600 -0
  310. package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
  311. package/runtime/dist/src/storage/private-database.js +7 -10
  312. package/runtime/dist/src/text/unicode-normalize.js +5 -1
  313. package/runtime/dist/src/understanding/candidates.js +8 -10
  314. package/runtime/dist/src/understanding/fixture.js +1 -1
  315. package/runtime/dist/src/understanding/pipeline.js +4 -4
  316. package/runtime/dist/src/usage/context.js +23 -0
  317. package/runtime/dist/src/usage/index.js +4 -0
  318. package/runtime/dist/src/usage/ledger-worker.js +90 -0
  319. package/runtime/dist/src/usage/ledger.js +74 -0
  320. package/runtime/dist/src/usage/model-call.js +63 -0
  321. package/runtime/dist/src/usage/pricing.js +68 -0
  322. package/runtime/dist/src/usage/summary.js +69 -0
  323. package/runtime/dist/src/voicemem/store-client.js +104 -21
  324. package/runtime/dist/src/voicemem/store-worker.js +5 -8
  325. package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
  326. package/src/command.mjs +8 -1
  327. package/runtime/dist/src/executors/autoglm.js +0 -376
@@ -3,7 +3,15 @@ import { createHash, randomUUID } from 'node:crypto';
3
3
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
4
  import { dirname } from 'node:path';
5
5
  import { createFeishuRunner, FeishuAppNotConfigured, object, parseFeishuJson } from './cli.js';
6
+ /**
7
+ * Only an explicit server-side rejection of the stored credential may invalidate a login. Every other verify failure is
8
+ * treated as temporarily unverifiable: a blocked network, a proxy returning an HTML page, a TLS, DNS or routing error
9
+ * and a bare EOF all look like failures, and a network-wording allow-list would silently log the user out on the one
10
+ * wording it does not know.
11
+ */
12
+ const FEISHU_CREDENTIAL_REJECTION = /\b(?:401|403)\b|unauthorized|forbidden|invalid[ _-]?(?:app[ _-]?)?(?:access[ _-]?)?token|token[ _-]?(?:is[ _-]?)?(?:expired|invalid|revoked|not[ _-]?found)/i;
6
13
  export const FEISHU_SCOPES = ['offline_access', 'im:chat:read', 'im:message:readonly', 'im:message.reactions:read'];
14
+ const unsupportedReasons = new Set(['unsupported_type', 'missing_body', 'malformed_body', 'invalid_identity', 'invalid_time', 'body_too_large']);
7
15
  const fresh = () => ({ paused: true, connected: false, bot: false, selected: [], cursors: {}, deliveries: {}, actions: [], generation: 0, sources: [] });
8
16
  const str = (value) => typeof value === 'string' ? value : '';
9
17
  const hash = (value) => createHash('sha256').update(value).digest('hex');
@@ -23,15 +31,43 @@ function pageItems(data, alternative) {
23
31
  }
24
32
  function messageText(row) {
25
33
  const kind = row.msg_type ?? row.message_type;
26
- if (kind !== 'text' && kind !== 'post')
34
+ if (kind !== 'text' && kind !== 'post' && kind !== 'interactive')
27
35
  return null;
28
36
  // CLI 1.0.69 returns rendered top-level content; raw API records have body.content JSON.
29
- if (typeof row.content === 'string')
37
+ if (typeof row.content === 'string' && (kind !== 'interactive' || !row.content.trim().startsWith('{')))
30
38
  return row.content;
31
39
  const raw = row.content ?? object(row.body).content;
32
40
  const content = typeof raw === 'string' ? jsonObject(raw) : object(raw);
33
41
  if (kind === 'text')
34
42
  return str(content.text);
43
+ if (kind === 'interactive') {
44
+ const lines = [];
45
+ let visited = 0;
46
+ const walk = (value, depth = 0) => {
47
+ if (depth > 12 || ++visited > 1000)
48
+ return;
49
+ if (typeof value === 'string') {
50
+ if (value.trim())
51
+ lines.push(value);
52
+ return;
53
+ }
54
+ if (Array.isArray(value)) {
55
+ for (const item of value)
56
+ walk(item, depth + 1);
57
+ return;
58
+ }
59
+ if (!value || typeof value !== 'object')
60
+ return;
61
+ const node = value;
62
+ if (['button', 'action', 'select_static', 'input'].includes(str(node.tag)))
63
+ return;
64
+ for (const key of ['header', 'title', 'text', 'content', 'elements', 'fields', 'body', 'columns', 'column_set'])
65
+ if (node[key] !== undefined)
66
+ walk(node[key], depth + 1);
67
+ };
68
+ walk(content);
69
+ return lines.join('\n').slice(0, 16000) || null;
70
+ }
35
71
  const post = Array.isArray(content.content) ? content : object(content.zh_cn ?? content.en_us ?? Object.values(content)[0]);
36
72
  if (!Array.isArray(post.content))
37
73
  throw new Error('Invalid Feishu post');
@@ -96,6 +132,16 @@ function readSaved(value) {
96
132
  }
97
133
  if (data.scopeConfigured !== undefined && typeof data.scopeConfigured !== 'boolean')
98
134
  throw new Error('Invalid Feishu scope state');
135
+ if (data.allHistory !== undefined && typeof data.allHistory !== 'boolean')
136
+ throw new Error('Invalid Feishu history mode');
137
+ for (const [key, reason] of Object.entries(object(data.unsupportedMessageKeys ?? {})))
138
+ if (!/^[a-f0-9]{64}$/.test(key) || !unsupportedReasons.has(reason))
139
+ throw new Error('Invalid Feishu unsupported message');
140
+ if (data.chatDiscovery !== undefined) {
141
+ const discovery = object(data.chatDiscovery);
142
+ if (!str(discovery.page) || !Array.isArray(discovery.chats) || discovery.chats.some(chat => !str(object(chat).id) || typeof object(chat).name !== 'string'))
143
+ throw new Error('Invalid Feishu chat discovery');
144
+ }
99
145
  if (data.consentSince !== undefined && !Number.isFinite(Date.parse(str(data.consentSince))))
100
146
  throw new Error('Invalid Feishu consent state');
101
147
  for (const from of Object.values(object(data.captureFrom ?? {})))
@@ -113,6 +159,8 @@ function readSaved(value) {
113
159
  if (['proposal', 'nonce', 'message', 'chat'].some(key => !str(row[key])) || !Number.isSafeInteger(row.generation))
114
160
  throw Error('Invalid outbound receipt');
115
161
  }
162
+ if (data.processingConsentPending !== undefined && typeof data.processingConsentPending !== 'boolean')
163
+ throw Error('Invalid Feishu consent state');
116
164
  if (data.processingConsent !== undefined)
117
165
  processingGrantSchema.parse(data.processingConsent);
118
166
  return data;
@@ -128,6 +176,8 @@ export class FeishuConnector {
128
176
  active;
129
177
  timer;
130
178
  busy = false;
179
+ /** The last verification failed without proving the login invalid, so collection waits instead of disconnecting. */
180
+ unverified = false;
131
181
  mentionReads = new Set();
132
182
  pending;
133
183
  listener;
@@ -146,7 +196,14 @@ export class FeishuConnector {
146
196
  throw new Error('Feishu collection callbacks required');
147
197
  this.run = options.run ?? createFeishuRunner(options.executable, options.credentialRoot);
148
198
  }
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)
199
+ snapshot() { const view = structuredClone(this.view); view.signed_in = this.saved.connected === true; if (this.unverified)
200
+ view.unverified = true;
201
+ else
202
+ delete view.unverified; if (this.saved.account)
203
+ view.account_id = this.saved.account;
204
+ else
205
+ delete view.account_id; const expected = this.options.processingGrant?.(true, 1, 0); view.processing_consent_required = this.saved.processingConsentPending === true || !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; view.all_history = this.saved.allHistory === true; view.chat_discovery_complete = !this.saved.chatDiscovery; view.history_complete = this.saved.selected.every(id => !this.saved.backfills?.[id]); const counts = {}; for (const reason of Object.values(this.saved.unsupportedMessageKeys ?? {}))
206
+ counts[reason] = (counts[reason] ?? 0) + 1; view.unsupported_messages = counts; if (view.app_setup)
150
207
  delete view.app_setup.verification_url; return view; }
151
208
  setupSnapshot() { const view = this.snapshot(); if (this.view.app_setup)
152
209
  view.app_setup = structuredClone(this.view.app_setup); return view; }
@@ -183,8 +240,7 @@ export class FeishuConnector {
183
240
  async json(args, input) {
184
241
  return parseFeishuJson(await this.run(args, { ...(input ? { input } : {}), ...(this.active ? { signal: this.active.signal } : {}) }));
185
242
  }
186
- async open() {
187
- this.closed = false;
243
+ async restore() {
188
244
  try {
189
245
  this.saved = readSaved(JSON.parse(await readFile(this.options.statePath, 'utf8')));
190
246
  }
@@ -192,6 +248,15 @@ export class FeishuConnector {
192
248
  if (error.code !== 'ENOENT')
193
249
  throw new Error('Cannot read Feishu state');
194
250
  }
251
+ if (this.saved.chatDiscovery)
252
+ this.view.chats = this.saved.chatDiscovery.chats.map(chat => ({ ...chat, selected: this.saved.selected.includes(chat.id) }));
253
+ }
254
+ async open() {
255
+ this.closed = false;
256
+ await this.serializeConsent(async () => {
257
+ await this.restore();
258
+ await this.recoverProcessingConsent();
259
+ });
195
260
  try {
196
261
  const version = await this.run(['--version']);
197
262
  const match = /(\d+)\.(\d+)\.(\d+)/.exec(version);
@@ -247,6 +312,17 @@ export class FeishuConnector {
247
312
  this.listenerRetry.unref();
248
313
  });
249
314
  }
315
+ /** Keep the connection and consent, fence delivery, and let observers (the notification service rebinds on a readiness edge) see the fence. */
316
+ async fenceVerification() {
317
+ this.unverified = true;
318
+ this.view.error = '飞书暂时无法验证登录,网络恢复后会自动继续';
319
+ if (this.saved.outboundIdentity)
320
+ this.saved.outboundIdentity = { ...this.saved.outboundIdentity, valid: false };
321
+ this.view.notification_ready = false;
322
+ await this.save();
323
+ this.publish();
324
+ return this.snapshot();
325
+ }
250
326
  async status(signal) {
251
327
  // Preserve the preflight error instead of attempting credential access with an unsupported CLI.
252
328
  if (!this.view.available)
@@ -256,9 +332,20 @@ export class FeishuConnector {
256
332
  data = signal ? parseFeishuJson(await this.run(['auth', 'status', '--json', '--verify'], { signal })) : await this.json(['auth', 'status', '--json', '--verify']);
257
333
  }
258
334
  catch (error) {
259
- if (!(error instanceof FeishuAppNotConfigured))
260
- throw error;
261
- data = {};
335
+ if (error instanceof FeishuAppNotConfigured)
336
+ data = {};
337
+ else {
338
+ const message = error instanceof Error ? error.message : '';
339
+ // A bare EOF, a DNS/TLS error or unparseable output proves nothing about the credential. Keep the saved
340
+ // connection and fence delivery instead of rethrowing past the caller that would publish a stale ready view.
341
+ if (!FEISHU_CREDENTIAL_REJECTION.test(message)) {
342
+ if (!this.saved.connected && !this.saved.outboundIdentity?.valid)
343
+ throw error;
344
+ return this.fenceVerification();
345
+ }
346
+ // An explicit server rejection still takes the invalidation path with the identity we already knew.
347
+ data = { appId: this.currentApp, identities: { user: { openId: this.saved.openId ?? '', status: 'verify_failed', verified: false, tokenStatus: 'valid', message } } };
348
+ }
262
349
  }
263
350
  const app = str(data.appId ?? data.app_id);
264
351
  this.currentApp = app || undefined;
@@ -275,6 +362,16 @@ export class FeishuConnector {
275
362
  const valid = data.verified !== false && user.verified !== false && (user.status === 'authenticated' || user.tokenStatus === 'valid' || user.authenticated === true
276
363
  || user.status === 'needs_refresh' && user.verified === true);
277
364
  const priorIdentity = this.saved.outboundIdentity;
365
+ // A blocked network makes the CLI report verify_failed while the stored token is still valid. That is
366
+ // not a logout: keep the connection and consent, collect nothing, and resume once verification passes.
367
+ // Only an explicit server rejection of the credential takes the invalidation path below; an unknown failure
368
+ // wording is treated as temporarily unverifiable, so it can never silently clear the login.
369
+ // Notification sends and callbacks stay fenced either way.
370
+ if (app && id && user.status === 'verify_failed' && user.tokenStatus !== 'expired' && !FEISHU_CREDENTIAL_REJECTION.test(str(user.message))) {
371
+ if (priorIdentity)
372
+ this.saved.outboundIdentity = { ...priorIdentity, valid: false };
373
+ return this.fenceVerification();
374
+ }
278
375
  const identityAccount = app && id && valid ? hash(JSON.stringify([app, user.tenantKey ?? user.tenant_key ?? null, id])) : null;
279
376
  if (identityAccount) {
280
377
  this.saved.outboundIdentity = { account: identityAccount, openId: id, generation: (priorIdentity?.generation ?? 0) + Number(!!priorIdentity && priorIdentity.account !== identityAccount), valid: true };
@@ -290,6 +387,10 @@ export class FeishuConnector {
290
387
  this.view.auth_issue = user.tokenStatus === 'expired' ? 'expired' : valid && id ? 'missing_scopes' : 'login_required';
291
388
  else
292
389
  delete this.view.auth_issue;
390
+ if (this.unverified) {
391
+ this.unverified = false;
392
+ delete this.view.error;
393
+ }
293
394
  if (this.saved.processingConsent?.extraction_provider)
294
395
  await this.setProcessingConsent(false);
295
396
  this.view.state = 'unauthorized';
@@ -304,6 +405,10 @@ export class FeishuConnector {
304
405
  return this.snapshot();
305
406
  }
306
407
  delete this.view.auth_issue;
408
+ if (this.unverified) {
409
+ this.unverified = false;
410
+ delete this.view.error;
411
+ }
307
412
  const account = hash(JSON.stringify([app, user.tenantKey ?? user.tenant_key ?? null, id]));
308
413
  if (this.saved.account && this.saved.account !== account) {
309
414
  await this.setProcessingConsent(false);
@@ -435,8 +540,8 @@ export class FeishuConnector {
435
540
  await this.status();
436
541
  if (!this.saved.openId || this.view.state === 'unauthorized')
437
542
  throw new Error('请先登录飞书');
438
- const chats = [];
439
- let page = '';
543
+ const chats = this.saved.chatDiscovery?.chats.map(chat => ({ ...chat, selected: this.saved.selected.includes(chat.id) })) ?? [];
544
+ let page = this.saved.chatDiscovery?.page ?? '';
440
545
  for (let count = 0; count < 20; count++) {
441
546
  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
547
  const items = pageItems(data, 'chats');
@@ -450,45 +555,96 @@ export class FeishuConnector {
450
555
  }
451
556
  if (data.has_more !== true) {
452
557
  this.view.chats = chats;
558
+ delete this.saved.chatDiscovery;
559
+ await this.save();
453
560
  return this.snapshot();
454
561
  }
455
562
  const next = str(data.page_token);
456
563
  if (!next || next === page)
457
564
  throw new Error('Invalid Feishu chat cursor');
458
565
  page = next;
566
+ this.saved.chatDiscovery = { page, chats: chats.map(({ id, name }) => ({ id, name })) };
567
+ this.view.chats = chats;
568
+ await this.save();
459
569
  }
460
- this.view.chats = chats;
461
- throw new Error('会话列表超过本次读取上限,未完整加载');
570
+ return this.snapshot();
462
571
  }
463
- async configure(chatIds, consent) {
572
+ async configure(chatIds, consent, allHistory = this.saved.allHistory === true) {
573
+ if (this.saved.chatDiscovery)
574
+ throw new Error('会话列表尚未完整加载');
464
575
  if (!consent || this.view.state === 'unauthorized' || !this.saved.account || chatIds.some((id) => !this.view.chats.some((chat) => chat.id === id)))
465
576
  throw new Error('请选择已授权的飞书会话');
466
577
  await this.pause();
467
578
  await this.setProcessingConsent(false, true);
468
- const previous = new Set(this.saved.selected), since = this.now().toISOString();
579
+ const previous = new Set(this.saved.selected), since = this.now().toISOString(), modeChanged = allHistory !== this.saved.allHistory;
469
580
  this.saved.scopeConfigured = true;
470
581
  this.saved.selected = [...new Set(chatIds)];
471
582
  this.saved.connected = true;
472
583
  this.saved.paused = false;
584
+ this.saved.allHistory = allHistory;
585
+ // A newly authorized scope gets a complete two-week window, including previously selected chats.
586
+ if (modeChanged || chatIds.some(id => !previous.has(id))) {
587
+ const backfills = this.saved.backfills ??= {};
588
+ for (const id of this.saved.selected)
589
+ if (modeChanged || !backfills[id])
590
+ backfills[id] = { start: allHistory ? '1970-01-01T00:00:00.000Z' : new Date(this.now().getTime() - 14 * 86400_000).toISOString(), end: since, order: 'desc' };
591
+ }
473
592
  this.saved.captureFrom = Object.fromEntries(this.saved.selected.map((id) => [id, previous.has(id) ? this.saved.captureFrom?.[id] ?? this.saved.mentionCaptureSince ?? since : since]));
474
593
  this.view.chats = this.view.chats.map((chat) => ({ ...chat, selected: chatIds.includes(chat.id) }));
475
594
  this.view.state = 'ready';
476
595
  await this.save();
477
596
  }
478
- async setProcessingConsent(consent, scopeChanged = false) {
597
+ consentTail = Promise.resolve();
598
+ consentSources() { return this.saved.sources.filter(id => this.saved.selected.some(chat => id === `feishu:${this.saved.account}:${this.saved.generation}:${chat}`)); }
599
+ async recoverProcessingConsent() {
600
+ const transition = this.options.processingConsentTransition;
601
+ if (!transition)
602
+ return;
603
+ const expected = this.saved.processingConsent ?? { revision: 0, scope_revision: 0, extraction_provider: null, embedding_provider: null, conversation_providers: [] };
604
+ const grant = await transition('reconcile', this.consentSources(), expected, this.saved.processingConsentPending === true);
605
+ this.saved.processingConsent = grant;
606
+ delete this.saved.processingConsentPending;
607
+ if (!grant.extraction_provider)
608
+ delete this.saved.consentSince;
609
+ await this.save();
610
+ await transition('activate', this.consentSources(), grant);
611
+ }
612
+ serializeConsent(work) {
613
+ const run = this.consentTail.then(work);
614
+ this.consentTail = run.catch(() => { });
615
+ return run;
616
+ }
617
+ setProcessingConsent(consent, scopeChanged = false) { return this.serializeConsent(() => this.applyProcessingConsent(consent, scopeChanged)); }
618
+ async applyProcessingConsent(consent, scopeChanged) {
479
619
  const prior = this.saved.processingConsent;
480
- const grant = this.options.processingGrant?.(consent, (prior?.revision ?? 0) + 1, (prior?.scope_revision ?? 0) + Number(scopeChanged));
620
+ let grant = this.options.processingGrant?.(consent, (prior?.revision ?? 0) + 1, (prior?.scope_revision ?? 0) + Number(scopeChanged));
481
621
  if (!grant)
482
622
  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);
623
+ const sources = consent ? this.consentSources() : this.saved.sources, transition = this.options.processingConsentTransition;
624
+ if (transition) {
625
+ await transition('suspend', sources, grant);
626
+ this.saved.processingConsentPending = true;
627
+ await this.save();
628
+ grant = await transition('apply', consent ? sources : [], grant);
629
+ }
630
+ else
631
+ await this.options.onProcessingConsent?.(sources, grant);
485
632
  this.saved.processingConsent = grant;
486
- // Automatic capture needs live consent and starts at the grant, never at older history.
487
633
  if (grant.extraction_provider)
488
634
  this.saved.consentSince = this.now().toISOString();
489
635
  else
490
636
  delete this.saved.consentSince;
491
- await this.save();
637
+ delete this.saved.processingConsentPending;
638
+ try {
639
+ await this.save();
640
+ if (transition)
641
+ await transition('activate', consent ? sources : [], grant);
642
+ }
643
+ catch (error) {
644
+ if (transition)
645
+ this.saved.processingConsentPending = true;
646
+ throw error;
647
+ }
492
648
  this.publish();
493
649
  }
494
650
  async sync() {
@@ -508,24 +664,29 @@ export class FeishuConnector {
508
664
  }
509
665
  }
510
666
  async syncNow() {
667
+ // A login that could not be verified is re-checked even when nothing is collected (notification-only or
668
+ // paused), so recovery needs no manual command. A failed check keeps the flag for the next tick.
669
+ if (this.unverified && !this.busy && (this.saved.paused || !this.saved.connected)) {
670
+ await this.status().catch(() => undefined);
671
+ return;
672
+ }
511
673
  if (this.busy || this.saved.paused || !this.saved.connected)
512
674
  return;
513
675
  this.busy = true;
514
676
  this.active = new AbortController();
515
677
  try {
516
678
  await this.status();
517
- if (this.view.state !== 'ready')
679
+ if (this.view.state !== 'ready' || this.unverified)
518
680
  return;
519
681
  const chats = [...this.saved.selected];
520
682
  let next = 0;
521
- let unsupported = 0;
522
683
  const errors = [];
523
684
  // Independent chats get four workers; a failed or capped chat cannot starve the rest.
524
685
  await Promise.all(Array.from({ length: Math.min(4, chats.length) }, async () => {
525
686
  while (next < chats.length && !this.active.signal.aborted) {
526
687
  const chat = chats[next++];
527
688
  try {
528
- unsupported += await this.syncChat(chat);
689
+ await this.syncChat(chat);
529
690
  }
530
691
  catch (error) {
531
692
  errors.push(error);
@@ -538,8 +699,9 @@ export class FeishuConnector {
538
699
  throw errors[0];
539
700
  this.saved.lastSync = this.now().toISOString();
540
701
  this.view.last_sync = this.saved.lastSync;
541
- if (unsupported)
542
- this.view.error = `已读取文字消息,${unsupported} 条附件或其他格式未提取正文`;
702
+ const total = Object.keys(this.saved.unsupportedMessageKeys ?? {}).length;
703
+ if (total)
704
+ this.view.error = `已读取文字消息,${total} 条消息未提取正文`;
543
705
  else
544
706
  delete this.view.error;
545
707
  await this.save();
@@ -557,7 +719,7 @@ export class FeishuConnector {
557
719
  let cursor = this.saved.cursors[chat];
558
720
  if (!cursor || cursor.end && cursor.order === undefined) {
559
721
  // 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' };
722
+ backfills[chat] ??= cursor ?? { start: this.saved.allHistory ? '1970-01-01T00:00:00.000Z' : new Date(this.now().getTime() - 14 * 86400_000).toISOString(), end: this.now().toISOString(), order: 'desc' };
561
723
  cursor = this.saved.cursors[chat] = { start: new Date(Date.parse(backfills[chat].end) - 60_000).toISOString(), order: 'desc' };
562
724
  }
563
725
  cursor.order ??= 'desc';
@@ -606,30 +768,52 @@ export class FeishuConnector {
606
768
  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
769
  if (this.active.signal.aborted)
608
770
  return { complete: false, unsupported };
771
+ const pageIssues = new Map();
772
+ const resolvedKeys = new Set();
773
+ const skip = (reason, item) => {
774
+ const id = item && typeof item === 'object' && !Array.isArray(item) ? str(item.message_id) : '';
775
+ pageIssues.set(hash(`${chat}:${id || hash(JSON.stringify(item))}`), reason);
776
+ return undefined;
777
+ };
609
778
  const parsed = await Promise.allSettled(pageItems(data, 'messages').map(async (item) => {
610
- const row = object(item);
779
+ if (!item || typeof item !== 'object' || Array.isArray(item))
780
+ return skip('invalid_identity', item);
781
+ const row = item;
611
782
  const id = str(row.message_id);
612
783
  if (!id || (row.chat_id && row.chat_id !== chat))
613
- throw new Error('Invalid Feishu message identity');
784
+ return skip('invalid_identity', item);
614
785
  if (row.deleted === true) {
615
786
  await this.options.deleteMessage?.(sourceId, `feishu://message/${encodeURIComponent(id)}`);
616
787
  return undefined;
617
788
  }
618
- const sender = row.sender ? object(row.sender) : {};
789
+ if (row.sender && (typeof row.sender !== 'object' || Array.isArray(row.sender)))
790
+ return skip('invalid_identity', item);
791
+ const sender = row.sender ?? {};
619
792
  const senderId = str(sender.open_id ?? sender.openId ?? sender.id);
620
793
  const senderType = str(sender.sender_type ?? sender.type);
621
- if ((senderType && senderType !== 'user') || !senderId.startsWith('ou_'))
794
+ const human = (!senderType || senderType === 'user') && senderId.startsWith('ou_');
795
+ const app = senderType === 'app' && senderId.length > 0 && senderId.length <= 512;
796
+ if (!human && !app)
622
797
  return undefined;
623
- const text = messageText(row);
624
- if (text === null) {
625
- unsupported++;
798
+ // Our own notification cards must not become fresh observations of the world.
799
+ if (app && (senderId === this.view.app_id || Object.values(this.saved.deliveries).some(item => item.message === id) || Object.values(this.saved.outboundReceipts ?? {}).some(item => item.message === id)))
626
800
  return undefined;
801
+ let text;
802
+ try {
803
+ text = messageText(row);
804
+ }
805
+ catch {
806
+ return skip('malformed_body', item);
627
807
  }
628
- if (!text)
629
- throw new Error('Missing Feishu message body');
808
+ if (text === null)
809
+ return skip('unsupported_type', item);
810
+ if (!text.trim())
811
+ return skip('missing_body', item);
812
+ if (text.length > 2_000_000)
813
+ return skip('body_too_large', item);
630
814
  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')) {
815
+ let mentionIds = Array.isArray(row.mentions) ? row.mentions.map(item => item && typeof item === 'object' ? str(item.id) : '').filter(id => id.startsWith('ou_')).slice(0, 50) : [];
816
+ if (human && senderId !== this.saved.openId && mention === 'unknown' && (text.includes('@') || (row.msg_type ?? row.message_type) === 'post')) {
633
817
  try {
634
818
  const raw = await this.originalMessage(id);
635
819
  const original = Array.isArray(raw.items) ? raw.items.map(object).find(item => item.message_id === id) : undefined;
@@ -652,9 +836,10 @@ export class FeishuConnector {
652
836
  const rawTime = row.create_time_iso ?? row.create_time;
653
837
  const numeric = Number(rawTime);
654
838
  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 };
839
+ if (!Number.isFinite(time) || time <= 0 || !Number.isFinite(new Date(time).getTime()))
840
+ return skip('invalid_time', item);
841
+ resolvedKeys.add(hash(`${chat}:${id}`));
842
+ return { sender_type: human ? 'user' : 'app', ...(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: human && 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(this.now().getTime() + 30 * 86400_000).toISOString(), sender_id: senderId, account_id: this.saved.account };
658
843
  }));
659
844
  const messages = [];
660
845
  for (const result of parsed) {
@@ -675,6 +860,19 @@ export class FeishuConnector {
675
860
  }
676
861
  if (this.active.signal.aborted)
677
862
  return { complete: false, unsupported };
863
+ const issues = this.saved.unsupportedMessageKeys ??= {};
864
+ for (const key of resolvedKeys)
865
+ delete issues[key];
866
+ for (const [key, reason] of pageIssues)
867
+ if (!resolvedKeys.has(key) && issues[key] === undefined) {
868
+ issues[key] = reason;
869
+ unsupported++;
870
+ }
871
+ const issueTotal = Object.keys(issues).length;
872
+ if (issueTotal)
873
+ this.view.error = `已读取文字消息,${issueTotal} 条消息未提取正文`;
874
+ else
875
+ delete this.view.error;
678
876
  if (data.has_more !== true) {
679
877
  cursor.start = new Date(Date.parse(cursor.end) - 60_000).toISOString();
680
878
  delete cursor.end;
@@ -735,11 +933,13 @@ export class FeishuConnector {
735
933
  this.saved.generation++;
736
934
  this.saved.cursors = {};
737
935
  this.saved.backfills = {};
936
+ this.saved.unsupportedMessageKeys = {};
738
937
  this.saved.outboundReceipts = {};
739
938
  this.saved.deliveries = {};
740
939
  this.saved.actions = [];
741
940
  delete this.saved.lastSync;
742
941
  delete this.view.last_sync;
942
+ delete this.view.error;
743
943
  await this.save();
744
944
  for (const source of sources) {
745
945
  await this.options.deleteSource(source);
@@ -747,7 +947,7 @@ export class FeishuConnector {
747
947
  await this.save();
748
948
  }
749
949
  }
750
- callbackReady() { return !!(this.saved.outbound && this.saved.outboundIdentity?.valid) || this.saved.bot && this.saved.connected && !this.saved.paused; }
950
+ callbackReady() { return !this.unverified && (!!(this.saved.outbound && this.saved.outboundIdentity?.valid) || this.saved.bot && this.saved.connected && !this.saved.paused); }
751
951
  notificationBinding(userScope) {
752
952
  const identity = this.saved.outboundIdentity;
753
953
  if (!identity)
@@ -810,7 +1010,7 @@ export class FeishuConnector {
810
1010
  if (!this.saved.bot || !this.saved.connected || this.saved.paused || !this.saved.openId)
811
1011
  return false;
812
1012
  await this.status();
813
- if (this.view.state !== 'ready' || this.active?.signal.aborted)
1013
+ if (this.view.state !== 'ready' || this.unverified || this.active?.signal.aborted)
814
1014
  return false;
815
1015
  const delivery = this.saved.deliveries[proposal.id] ?? { nonce: randomUUID() };
816
1016
  if (delivery.message)
@@ -906,7 +1106,19 @@ export class FeishuConnector {
906
1106
  throw new Error('Invalid app setup request');
907
1107
  return method === 'feishu.app.start' ? this.beginAppSetup() : method === 'feishu.app.cancel' ? this.cancelAppSetup() : this.setupSnapshot();
908
1108
  case 'feishu.status':
909
- await this.status();
1109
+ // Settings pages read the snapshot kept fresh by open() and the sync tick; only an explicit check runs the CLI.
1110
+ if (params.cached === true)
1111
+ return this.setupSnapshot();
1112
+ try {
1113
+ await this.status(AbortSignal.timeout(this.options.statusTimeoutMs ?? 15_000));
1114
+ }
1115
+ catch {
1116
+ // status() throws only when no login is known; a failed check is still a displayable state, not a page error.
1117
+ // `unverified` makes the sync tick re-check, and a successful status clears it.
1118
+ this.unverified = true;
1119
+ this.view.error = '暂时无法连接飞书,请检查网络后重试';
1120
+ this.publish();
1121
+ }
910
1122
  return this.setupSnapshot();
911
1123
  case 'feishu.notification.login': return this.beginLogin(true);
912
1124
  case 'feishu.notification.configure':
@@ -936,7 +1148,9 @@ export class FeishuConnector {
936
1148
  case 'feishu.configure': {
937
1149
  if (!Array.isArray(params.chat_ids) || !params.chat_ids.every((id) => typeof id === 'string'))
938
1150
  throw new Error('Invalid chat selection');
939
- await this.configure(params.chat_ids, params.consent === true);
1151
+ if (params.all_history !== undefined && typeof params.all_history !== 'boolean')
1152
+ throw new Error('Invalid history mode');
1153
+ await this.configure(params.chat_ids, params.consent === true, params.all_history ?? (this.saved.allHistory === true));
940
1154
  break;
941
1155
  }
942
1156
  case 'feishu.sync':
@@ -6,11 +6,15 @@ import { ComposioFailure } from '../composio/client.js';
6
6
  export const macMailScopeSchema = z.object({ kind: z.literal('macos_mail'), mailboxes: z.array(z.string().min(1).max(4096)).min(1).max(20), pastDays: z.number().int().min(1).max(180) }).strict();
7
7
  const cursorSchema = z.object({ box: z.number().int().min(0).max(20), offset: z.number().int().min(0).max(500), fingerprints: z.array(z.string().max(256)).max(20) }).strict();
8
8
  const requestSchema = z.union([z.object({ command: z.enum(['status', 'request_access', 'list_mailboxes']) }).strict(), z.object({ command: z.literal('snapshot'), mailboxes: macMailScopeSchema.shape.mailboxes, start: z.iso.datetime(), end: z.iso.datetime(), cursor: cursorSchema.nullable() }).strict()]);
9
- const messageSchema = z.object({ account: z.string().min(1).max(1024), mailbox: z.string().min(1).max(4096), id: z.string().min(1).max(128), messageId: z.string().max(4096), subject: z.string().max(10000), sender: z.string().max(10000), recipients: z.array(z.string().max(10000)).max(200), received: z.iso.datetime(), sent: z.iso.datetime(), content: z.string().max(2 * 1024 * 1024), read: z.boolean(), flagged: z.boolean() }).strict();
9
+ const messageSchema = z.object({ account: z.string().min(1).max(1024), mailbox: z.string().min(1).max(4096), id: z.string().min(1).max(128), messageId: z.string().max(4096), subject: z.string().max(10000), sender: z.string().max(10000), recipients: z.array(z.string().max(10000)).max(200), received: z.iso.datetime(), sent: z.iso.datetime(), content: z.string().max(2 * 1024 * 1024), body_unavailable: z.boolean().optional(), read: z.boolean(), flagged: z.boolean() }).strict();
10
10
  const hash = (s) => createHash('sha256').update(s).digest('hex');
11
11
  export function normalizeMacMailMessage(input) {
12
- const e = messageSchema.parse(input), { read, flagged, ...semantic } = e, key = hash(canonicalJson([e.account, e.mailbox, e.id])), text = [e.subject, e.sender, e.recipients.join(', '), e.received, e.content].join('\n');
13
- return { key, semanticHash: hash(canonicalJson(semantic)), metadata: { account: e.account, mailbox: e.mailbox, remote_id: e.id, message_id: e.messageId, read, flagged, truncated: text.length > 99000 }, text: text.length > 99000 ? text.slice(0, 99000) + '\n[正文已截断]' : text, locator: e.messageId ? 'message://' + encodeURIComponent('<' + e.messageId + '>') : 'message://', observedAt: e.received, retentionUntil: new Date(Date.parse(e.received) + 180 * 86400000).toISOString(), kind: 'mail', status: 'current' };
12
+ const e = messageSchema.parse(input), { read, flagged, ...semantic } = e, key = hash(canonicalJson([e.account, e.mailbox, e.id]));
13
+ // A stalled body arrives as empty content plus a flag, never as a placeholder sentence: a sentence would be quoted as
14
+ // fact and would retire a body read earlier. The flag stays in the semantic payload, so this hash is distinct from any
15
+ // real body and a later successful read replaces it.
16
+ const unavailable = e.body_unavailable === true, text = [e.subject, e.sender, e.recipients.join(', '), e.received, ...(unavailable ? [] : [e.content])].join('\n');
17
+ return { key, semanticHash: hash(canonicalJson(semantic)), metadata: { account: e.account, mailbox: e.mailbox, remote_id: e.id, message_id: e.messageId, read, flagged, ...(unavailable ? { body_unavailable: true } : {}), truncated: text.length > 99000 }, text: text.length > 99000 ? text.slice(0, 99000) + '\n[正文已截断]' : text, locator: e.messageId ? 'message://' + encodeURIComponent('<' + e.messageId + '>') : 'message://', observedAt: e.received, retentionUntil: new Date(Date.parse(e.received) + 180 * 86400000).toISOString(), kind: 'mail', status: 'current' };
14
18
  }
15
19
  export class MacMailClient {
16
20
  resourcesRoot;
@@ -44,9 +44,11 @@ export class MacNativeReader {
44
44
  else
45
45
  chunks.push(chunk); });
46
46
  child.on('close', code => { try {
47
+ const result = record.parse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
48
+ if (this.resource === 'macos_gui' && typeof result.error === 'string' && /^[a-z_]{1,80}$/u.test(result.error))
49
+ throw new ComposioFailure('native_gui:' + result.error);
47
50
  if (code !== 0)
48
51
  throw new ComposioFailure('native_unavailable');
49
- const result = record.parse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
50
52
  if (result.error)
51
53
  throw new ComposioFailure(z.enum(['native_unavailable', 'permission_denied', 'calendar_unavailable', 'mailbox_unavailable', 'snapshot_expired', 'response_too_large', 'timeout', 'scope_denied', 'invalid_request']).catch('native_unavailable').parse(result.error));
52
54
  resolve(result);
@@ -12,7 +12,7 @@ export function buildCascadedVoiceProvider(options, registry = cascadedProviderR
12
12
  const selected = requireSelectedCascadedRealtimeConfig(options.settings), ids = { next: options.idFactory };
13
13
  const capabilities = capabilitiesFromSettings(options.settings);
14
14
  const metering = (endpoint) => options.onUsage === undefined ? {} : { onUsage: usageReporterForEndpoint(options.onUsage, endpoint) };
15
- const instructions = frontendInstructions({ schedules: options.schedules === true, search: capabilities.modules.search.enabled, camera: options.captureFrame !== undefined, coding: capabilities.modules.coding.enabled, gui: options.settings.executors.some(name => ['browser', 'computer', 'mobile'].includes(name)), knowledge: capabilities.modules.knowledge.enabled }, options.executorApproval === true);
15
+ const instructions = frontendInstructions({ ...(options.memoryTools ? { memoryTools: options.memoryTools } : {}), schedules: options.schedules === true, search: capabilities.modules.search.enabled, camera: options.captureFrame !== undefined, coding: capabilities.modules.coding.enabled, gui: options.settings.executors.some(name => ['browser', 'computer', 'mobile'].includes(name)), knowledge: capabilities.modules.knowledge.enabled, chatToolPolicy: options.chatToolPolicy === true }, options.executorApproval === true);
16
16
  const llm = registry.llm[selected.llm.provider === 'ark' ? 'ark' : 'qwen']({ config: selected.llm.config, clock: options.clock, ids, instructions, ...metering(selected.llm.config.baseUrl) });
17
17
  return new CascadedRealtimeProvider({
18
18
  language: options.settings.language,
@@ -24,6 +24,8 @@ export function buildCascadedVoiceProvider(options, registry = cascadedProviderR
24
24
  ...(options.captureFrame === undefined ? {} : { captureFrame: options.captureFrame }),
25
25
  ...(options.prerecall === undefined ? {} : { prerecall: options.prerecall }),
26
26
  ...(options.telemetry === undefined ? {} : { telemetry: options.telemetry }),
27
+ ...(options.prerecallPolicy === undefined ? {} : { prerecallPolicy: options.prerecallPolicy }),
28
+ ...(options.prerecallMeta === undefined ? {} : { prerecallMeta: options.prerecallMeta }),
27
29
  });
28
30
  }
29
31
  export function buildConversationVoiceProvider(options) {
@@ -33,9 +35,10 @@ export function buildConversationVoiceProvider(options) {
33
35
  return integratedProviderRegistry[options.settings.integrated_provider]({
34
36
  language: options.settings.language, config: requireIntegratedRealtime(options.settings), idFactory: options.idFactory, now: () => options.clock.now(),
35
37
  executorApproval: options.executorApproval === true,
36
- modules: { schedules: options.schedules === true, search: capabilities.modules.search.enabled, camera: false, coding: capabilities.modules.coding.enabled, gui: options.settings.executors.some(name => ['browser', 'computer', 'mobile'].includes(name)), knowledge: capabilities.modules.knowledge.enabled },
38
+ modules: { ...(options.memoryTools ? { memoryTools: options.memoryTools } : {}), schedules: options.schedules === true, search: capabilities.modules.search.enabled, camera: false, coding: capabilities.modules.coding.enabled, gui: options.settings.executors.some(name => ['browser', 'computer', 'mobile'].includes(name)), knowledge: capabilities.modules.knowledge.enabled, chatToolPolicy: options.chatToolPolicy === true },
37
39
  ...(options.onUsage === undefined ? {} : { onUsage: options.onUsage }),
38
40
  ...(options.history === undefined ? {} : { history: options.history }),
41
+ ...(options.telemetry === undefined ? {} : { telemetry: options.telemetry }),
39
42
  });
40
43
  }
41
44
  //# sourceMappingURL=conversation-voice-provider.js.map