nova-personal-agent-server 0.4.0 → 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 +12 -2
  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 +13 -6
  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
@@ -0,0 +1,183 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { open, rename, unlink } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { preparePrivateDatabasePath } from '../storage/private-database.js';
6
+ const titles = { 'profile.md': '个人画像', 'timeline.md': '时间线', 'todos.md': '待办', 'goals.md': '目标', 'ideas.md': '想法' };
7
+ const text = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/([\\`*_{}[\]()#+|~])/g, '\\$1').replace(/^(\s*)(-|[0-9]+\.) /gm, '$1\\$2 ');
8
+ const line = (value) => text(value).replace(/[\r\n]+/g, ' ');
9
+ const web = (value) => { try {
10
+ const u = new URL(value ?? '');
11
+ return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password ? u.href.replace(/[<>()]/g, c => encodeURIComponent(c)) : null;
12
+ }
13
+ catch {
14
+ return null;
15
+ } };
16
+ const sourceLines = (sources) => sources.map(s => { const url = web(s.url), label = line(s.label ?? s.type ?? '来源'); return `- ${url ? `[${label}](<${url}>)` : label}${s.available === false ? '(来源已不可用)' : ''}${s.id || s.evidence_id ? ` · ID:${line(s.id ?? s.evidence_id)}` : ''}`; }).join('\n');
17
+ const notice = '> 应用自动维护的阅读副本。数据库和应用保存状态为权威来源;手工修改不会回写,下次同步会覆盖。\n';
18
+ const scopeMarker = (scope) => `<!-- nova-reading-copy:v1 scope=${createHash('sha256').update(scope).digest('hex')} -->`;
19
+ export function renderReadingCopies(s) {
20
+ const result = {};
21
+ const wrap = (name, body) => `${scopeMarker(s.scope)}\n# ${titles[name]}\n\n${notice}\n${body.trim()}\n`;
22
+ const history = s.profile.last_success, draft = history?.draft ?? s.profile.draft, manual = s.life.profile.version > 0;
23
+ let profile = '';
24
+ if (manual)
25
+ profile = `你手写的介绍(版本 ${s.life.profile.version})\n\n${text(s.life.profile.about) || '你已清空个人介绍。'}`;
26
+ else if (draft) {
27
+ profile = history?.generated_at ? `生成时间:${line(history.generated_at)}\n\n` : '生成时间未记录。\n\n';
28
+ if (draft.about)
29
+ profile += `## 关于我\n\n${text(draft.about.text)}\n\n`;
30
+ for (const work of draft.work)
31
+ profile += `## ${line(work.title)}\n\n${text(work.text)}\n\n`;
32
+ if (draft.interests.length)
33
+ profile += `## 兴趣与关注\n\n${draft.interests.map(i => '- ' + text(i.text)).join('\n')}\n\n`;
34
+ const sources = sourceLines(history?.sources ?? s.profile.sources);
35
+ if (sources)
36
+ profile += '## 来源\n\n' + sources;
37
+ }
38
+ else
39
+ profile = '暂无已保存画像。';
40
+ result['profile.md'] = !manual && !draft && s.profile.status === 'failed' ? null : wrap('profile.md', profile);
41
+ let timeline = s.timeline.updated_at ? `整理时间:${line(s.timeline.updated_at)}\n\n` : '';
42
+ for (const card of s.timeline.cards) {
43
+ timeline += `## ${line(card.title)}\n\nID:${line(card.id)} · 分类:${line(card.category)}${card.status_label ? ' · ' + line(card.status_label) : ''}\n\n`;
44
+ const dates = [['发生', card.time.occurred_on], ['开始', card.time.started_on], ['截止', card.time.due_on], ['计划', card.time.scheduled_on], ['最近报告', card.time.last_reported_on]].filter(([, d]) => d);
45
+ if (dates.length)
46
+ timeline += dates.map(([label, d]) => `${label}:${line(d)}`).join(' · ') + '\n\n';
47
+ timeline += text(card.why_now) + '\n\n' + card.facts.map(f => '- ' + text(f.text)).join('\n') + '\n\n';
48
+ if (card.uncertainty)
49
+ timeline += '待确认:' + text(card.uncertainty) + '\n\n';
50
+ for (const step of card.next_steps)
51
+ timeline += `- 建议:${text(step.title)};${text(step.detail)}\n`;
52
+ if (!card.sources_available)
53
+ timeline += '\n部分原始来源已不可用,保留历史整理内容。\n';
54
+ const sources = sourceLines(card.sources);
55
+ if (sources)
56
+ timeline += '\n来源:\n' + sources + '\n';
57
+ timeline += '\n';
58
+ }
59
+ result['timeline.md'] = s.timelineLoadFailed ? null : wrap('timeline.md', timeline + (s.timeline.cards.length ? '' : '暂无已保存时间线。'));
60
+ const statuses = { open: '未开始', doing: '进行中', waiting: '等待中', done: '已完成', cancelled: '已取消', active: '推进中', paused: '暂停', completed: '已完成', archived: '已归档' };
61
+ for (const kind of ['todos', 'goals', 'ideas']) {
62
+ const rows = s.life[kind];
63
+ let body = '';
64
+ const groups = kind === 'todos' ? [['未完成', ['open', 'doing', 'waiting']], ['已完成', ['done']], ['已取消', ['cancelled']]] : kind === 'goals' ? [['进行中', ['active', 'paused']], ['已完成', ['completed']], ['已归档', ['archived']]] : [['有效想法', ['active']], ['已归档', ['archived']]];
65
+ for (const [heading, status] of groups) {
66
+ const selected = rows.filter(r => status.includes(r.status));
67
+ if (!selected.length)
68
+ continue;
69
+ body += `## ${heading}\n\n`;
70
+ for (const row of selected) {
71
+ body += `### ${line(row.title)}\n\nID:${line(row.id)} · 状态:${statuses[row.status]} · 版本:${row.version}\n\n`;
72
+ body += `创建:${line(row.created_at)} · 更新:${line(row.updated_at)}\n\n`;
73
+ if (row.note)
74
+ body += text(row.note) + '\n\n';
75
+ if (row.importance === 'high')
76
+ body += '重要程度:高\n\n';
77
+ if ('due' in row && row.due)
78
+ body += '到期:' + line(row.due) + '\n\n';
79
+ if ('success_criteria' in row)
80
+ body += `达成标准:${text(row.success_criteria) || '未填写'}\n\n关联待办完成:${row.progress.done}/${row.progress.total}(不代表目标已达成)\n\n`;
81
+ if ('goal_id' in row && row.goal_id)
82
+ body += '关联目标:' + line(row.goal_id) + '\n\n';
83
+ if ('idea_id' in row && row.idea_id)
84
+ body += '来自想法:' + line(row.idea_id) + '\n\n';
85
+ if (kind === 'ideas') {
86
+ const targets = [...s.life.todos, ...s.life.goals].filter(r => r.idea_id === row.id);
87
+ if (targets.length)
88
+ body += '已关联:' + targets.map(r => line(r.title) + '(' + line(r.id) + ')').join('、') + '\n\n';
89
+ }
90
+ const sources = sourceLines(row.sources ?? []);
91
+ if (sources)
92
+ body += '来源:\n' + sources + '\n\n';
93
+ }
94
+ }
95
+ const name = `${kind}.md`;
96
+ result[name] = wrap(name, body || '暂无已保存记录。');
97
+ }
98
+ return result;
99
+ }
100
+ /** One host owns these derived files under its existing process lock. */
101
+ export class ReadingCopies {
102
+ directory;
103
+ snapshot;
104
+ diagnostic;
105
+ #active = false;
106
+ #timer;
107
+ #tail = Promise.resolve();
108
+ constructor(directory, snapshot, diagnostic = () => { }) {
109
+ this.directory = directory;
110
+ this.snapshot = snapshot;
111
+ this.diagnostic = diagnostic;
112
+ }
113
+ start() { this.#active = true; this.schedule(); }
114
+ schedule() { if (!this.#active || this.#timer)
115
+ return; this.#timer = setTimeout(() => { this.#timer = undefined; void this.flush(); }, 500); this.#timer.unref(); }
116
+ flush() {
117
+ clearTimeout(this.#timer);
118
+ this.#timer = undefined;
119
+ if (!this.#active)
120
+ return this.#tail;
121
+ const run = this.#tail.then(async () => {
122
+ const s = this.snapshot(), docs = renderReadingCopies(s);
123
+ for (const name of Object.keys(titles))
124
+ try {
125
+ await this.#write(name, docs[name], s.scope);
126
+ }
127
+ catch {
128
+ this.diagnostic('reading_copy_write_failed:' + name);
129
+ }
130
+ }).catch(() => { this.diagnostic('reading_copies_snapshot_failed'); });
131
+ this.#tail = run;
132
+ return run;
133
+ }
134
+ async close() { if (!this.#active)
135
+ return; const last = this.flush(); this.#active = false; await last; }
136
+ async #write(name, content, scope) {
137
+ const path = preparePrivateDatabasePath(join(this.directory, name));
138
+ const previous = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
139
+ let old;
140
+ try {
141
+ old = await previous.readFile('utf8');
142
+ }
143
+ finally {
144
+ await previous.close();
145
+ }
146
+ if (content === null) {
147
+ if (old.startsWith(scopeMarker(scope)))
148
+ return;
149
+ content = `${scopeMarker(scope)}\n# ${titles[name]}\n\n${notice}\n当前资料暂时无法读取,等待下次同步。\n`;
150
+ }
151
+ if (content === old)
152
+ return;
153
+ const tmp = path + '.' + randomUUID() + '.tmp';
154
+ let renamed = false;
155
+ try {
156
+ const file = await open(tmp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
157
+ try {
158
+ await file.writeFile(content);
159
+ await file.sync();
160
+ }
161
+ finally {
162
+ await file.close();
163
+ }
164
+ preparePrivateDatabasePath(path);
165
+ await rename(tmp, path);
166
+ renamed = true;
167
+ if (process.platform !== 'win32') {
168
+ const directory = await open(this.directory, constants.O_RDONLY);
169
+ try {
170
+ await directory.sync();
171
+ }
172
+ finally {
173
+ await directory.close();
174
+ }
175
+ }
176
+ }
177
+ finally {
178
+ if (!renamed)
179
+ await unlink(tmp).catch(() => { });
180
+ }
181
+ }
182
+ }
183
+ //# sourceMappingURL=reading-copies.js.map
@@ -1,5 +1,6 @@
1
1
  import { SOURCE_PROCESSING_GOAL } from '../core/source-processing-instructions.js';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
+ import { isDeepStrictEqual } from 'node:util';
3
4
  import { z } from 'zod';
4
5
  import { BoundedJsonStore } from '../storage/bounded-json.js';
5
6
  import { canonicalJson } from '../text/canonical-json.js';
@@ -10,9 +11,10 @@ export const scheduleContextSchema = z.object({ todos: z.boolean(), goals: z.boo
10
11
  export const scheduleInputSchema = z.object({ title: z.string().trim().min(1).max(200), goal: z.string().trim().min(1).max(16000), acceptance: z.array(z.string().trim().min(1).max(2000)).min(1).max(64), rule: scheduleRuleSchema, context: scheduleContextSchema }).strict();
11
12
  const authoritySchema = z.object({ user_scope: id, source: z.enum(['ui', 'user_turn', 'builtin']), origin_ref: id, source_refs: z.array(id).max(128), allowed_context: scheduleContextSchema }).strict();
12
13
  const slotSchema = z.object({ scheduled_at: instant, local_date: z.string(), local_time: z.string(), slot_key: id }).strict();
13
- const definitionSchema = scheduleInputSchema.extend({ processing: z.object({ failures: z.number().int().nonnegative(), next_attempt: instant }).strict().optional(), id, revision: z.number().int().positive(), enabled: z.boolean(), archived: z.boolean(), authority: authoritySchema, cursor: instant, next_slot: slotSchema.nullable(), missed_count: z.number().int().nonnegative(), dst_gap_count: z.number().int().nonnegative() }).strict();
14
- const summarySchema = z.object({ outcome: z.enum(['completed', 'cancelled', 'missed', 'skipped', 'failed']), text: z.string().max(16000), evidence_refs: z.array(id).max(128), consumer: id.nullable().optional(), published: z.boolean() }).strict();
15
- const runSchema = z.object({ processing: z.object({ batch_id: id, recipe: id, exhausted: z.boolean().default(false), calls: z.array(id).max(24) }).strict().optional(), run_id: id, schedule_id: id, definition_revision: z.number().int().positive(), definition_hash: id, definition: scheduleInputSchema, authority: authoritySchema, slot: slotSchema.nullable(), trigger: z.enum(['scheduled', 'manual']), claimed_at: instant, input: internalTaskInputSchema, stage: z.enum(['claimed', 'bound', 'prepared', 'terminal']), task_id: id.nullable(), prepared_namespace: id.nullable(), terminal_summary: summarySchema.nullable() }).strict();
14
+ const definitionSchema = scheduleInputSchema.extend({ shared: z.object({ owner_revision: z.number().int().nonnegative() }).optional(), processing: z.object({ failures: z.number().int().nonnegative(), next_attempt: instant }).strict().optional(), id, revision: z.number().int().positive(), enabled: z.boolean(), archived: z.boolean(), authority: authoritySchema, cursor: instant, next_slot: slotSchema.nullable(), missed_count: z.number().int().nonnegative(), dst_gap_count: z.number().int().nonnegative() }).strict();
15
+ const summarySchema = z.object({ outcome: z.enum(['completed', 'cancelled', 'missed', 'skipped', 'failed']), text: z.string().max(16000), evidence_refs: z.array(id).max(128), consumer: id.nullable().optional(), memory_origin: z.enum(['non_product']).optional(), published: z.boolean() }).strict();
16
+ // Preserve accounting metadata written by newer runtimes sharing this local store.
17
+ const runSchema = z.object({ processing: z.object({ batch_id: id, recipe: id, attempts: z.array(id).max(24).default([]), exhausted: z.boolean().default(false), model_calls: z.number().int().nonnegative().optional(), reserved_output_tokens: z.number().int().nonnegative().optional(), calls: z.array(id).max(24) }).strict().optional(), run_id: id, schedule_id: id, definition_revision: z.number().int().positive(), definition_hash: id, definition: scheduleInputSchema, authority: authoritySchema, slot: slotSchema.nullable(), trigger: z.enum(['scheduled', 'manual']), claimed_at: instant, input: internalTaskInputSchema, stage: z.enum(['claimed', 'bound', 'prepared', 'terminal']), task_id: id.nullable(), prepared_namespace: id.nullable(), terminal_summary: summarySchema.nullable() }).strict();
16
18
  const adoptionResultSchema = z.object({ id, version: z.number().int().positive() }).strict();
17
19
  const stateSchema = z.object({ items: z.array(definitionSchema).max(4096), runs: z.array(runSchema).max(4096), receipts: z.record(z.string(), z.object({ hash: id, kind: z.enum(['schedule', 'run']), id }).strict()), adoptions: z.record(z.string(), z.object({ hash: id, run_id: id, result: adoptionResultSchema.nullable() }).strict()).default({}) }).strict();
18
20
  const empty = () => ({ items: [], runs: [], receipts: {}, adoptions: {} });
@@ -31,8 +33,18 @@ export class ScheduleService {
31
33
  this.now = now;
32
34
  this.#store = new BoundedJsonStore(path, stateSchema, 16 * 1024 * 1024);
33
35
  }
36
+ // Retired Hub ownership must never become local execution authority on upgrade.
34
37
  async open() { try {
35
38
  this.#state = await this.#store.read(empty());
39
+ if (this.#state.items.some(item => item.shared && (!item.archived || item.enabled || item.next_slot))) {
40
+ for (const item of this.#state.items)
41
+ if (item.shared) {
42
+ item.archived = true;
43
+ item.enabled = false;
44
+ item.next_slot = null;
45
+ }
46
+ await this.#store.write(this.#state);
47
+ }
36
48
  }
37
49
  catch (error) {
38
50
  if (error.code !== 'ENOENT')
@@ -46,7 +58,7 @@ export class ScheduleService {
46
58
  getRun(runId) { const run = this.findRun(runId); if (!run)
47
59
  throw Error('schedule_run_not_found'); return run; }
48
60
  runForTask(taskId) { const run = this.#state.runs.find(run => run.task_id === taskId); return run ? structuredClone(run) : null; }
49
- activeRuns() { return structuredClone(this.#state.runs.filter(run => run.stage !== 'terminal')); }
61
+ activeRuns() { return structuredClone(this.#state.runs.filter(run => run.stage !== 'terminal' && !this.#state.items.find(item => item.id === run.schedule_id)?.shared)); }
50
62
  terminalRuns() { return structuredClone(this.#state.runs.filter(run => run.stage === 'terminal')); }
51
63
  reserveAdoption(requestId, runId, input) {
52
64
  const run = this.getRun(runId), key = scheduleHash([run.authority.user_scope, id.parse(requestId)]), payload = scheduleHash({ runId, input });
@@ -102,14 +114,36 @@ export class ScheduleService {
102
114
  throw Error('processing_backoff');
103
115
  if (next.runs.some(run => run.schedule_id === item.id && run.stage !== 'terminal'))
104
116
  throw Error('schedule_running');
105
- const run = this.#run({ ...item, goal: item.goal + ' Batch: ' + batchId + '; recipe: ' + recipe }, null, 'scheduled', runId);
106
- run.processing = { batch_id: batchId, recipe, exhausted: false, calls: [] };
117
+ const run = this.#run(item, null, 'scheduled', runId);
118
+ run.processing = { batch_id: batchId, recipe, attempts: [], exhausted: false, calls: [] };
107
119
  next.runs.push(run);
108
120
  return structuredClone(run);
109
121
  });
110
122
  }
111
123
  exhaustSourceProcessing(runId) { return this.#changeRun(runId, run => { if (run.processing)
112
124
  run.processing.exhausted = true; }); }
125
+ reserveSourceProcessingModelCall(runId, maxTokens) {
126
+ return this.#changeRun(runId, run => {
127
+ if (!run.processing || run.stage === 'terminal')
128
+ throw Error('builtin_schedule');
129
+ const count = run.processing.model_calls ?? 0, budget = run.processing.reserved_output_tokens ?? 0;
130
+ if (count >= 8 || budget + maxTokens > 64000)
131
+ throw Error('processing_model_budget_exhausted');
132
+ run.processing.model_calls = count + 1;
133
+ run.processing.reserved_output_tokens = budget + maxTokens;
134
+ });
135
+ }
136
+ reserveSourceProcessingAttempt(runId, attemptId) {
137
+ return this.#changeRun(runId, run => {
138
+ if (!run.processing || run.stage === 'terminal')
139
+ throw Error('builtin_schedule');
140
+ if (run.processing.attempts.includes(id.parse(attemptId)))
141
+ return;
142
+ if (run.processing.exhausted || run.processing.attempts.length >= 24)
143
+ throw Error('processing_budget_exhausted');
144
+ run.processing.attempts.push(attemptId);
145
+ });
146
+ }
113
147
  reserveSourceProcessingCall(runId, callId) {
114
148
  return this.#changeRun(runId, run => {
115
149
  if (!run.processing || run.stage === 'terminal')
@@ -213,13 +247,13 @@ export class ScheduleService {
213
247
  if (scheduleHash({ ...run.terminal_summary, published: false }) !== scheduleHash({ ...parsed, published: false }))
214
248
  throw Error('run_result_conflict');
215
249
  return;
216
- } run.stage = 'terminal'; run.terminal_summary = parsed; const item = next.items.find(item => item.id === run.schedule_id); if (item?.processing) {
217
- item.processing.failures = parsed.outcome === 'completed' ? 0 : item.processing.failures + 1;
218
- item.processing.next_attempt = new Date(this.now().getTime() + (parsed.outcome === 'completed' ? 0 : Math.min(3600000, 60000 * 2 ** Math.min(item.processing.failures - 1, 6)))).toISOString();
250
+ } run.stage = 'terminal'; run.terminal_summary = parsed; const current = next.items.find(item => item.id === run.schedule_id); if (current?.processing) {
251
+ current.processing.failures = parsed.outcome === 'completed' ? 0 : current.processing.failures + 1;
252
+ current.processing.next_attempt = new Date(this.now().getTime() + (parsed.outcome === 'completed' ? 0 : Math.min(3600000, 60000 * 2 ** Math.min(current.processing.failures - 1, 6)))).toISOString();
219
253
  } });
220
254
  }
221
255
  markWithheld(runId) { return this.#changeRun(runId, run => { if (run.terminal_summary?.published)
222
- return; run.stage = 'terminal'; run.terminal_summary = { outcome: 'failed', text: '相关资料已变化,本次结果未发送。请重新运行以读取最新资料。', evidence_refs: [], published: true }; }); }
256
+ return; run.stage = 'terminal'; run.terminal_summary = { ...(run.terminal_summary?.memory_origin ? { memory_origin: run.terminal_summary.memory_origin } : {}), outcome: 'failed', text: '相关资料已变化,本次结果未发送。请重新运行以读取最新资料。', evidence_refs: [], published: true }; }); }
223
257
  markPublished(runId) { return this.#changeRun(runId, run => { if (!run.terminal_summary)
224
258
  throw Error('run_not_terminal'); run.terminal_summary.published = true; }); }
225
259
  #run(item, slot, trigger, run_id) {
@@ -256,15 +290,18 @@ export class ScheduleService {
256
290
  next.receipts[key] = { hash: payload, kind, id: kind === 'schedule' ? result.id : result.run_id };
257
291
  return structuredClone(result);
258
292
  }
259
- #changeRun(runId, change) { return this.#mutate(next => { const run = next.runs.find(run => run.run_id === id.parse(runId)); if (!run)
260
- throw Error('schedule_run_not_found'); change(run, next); return structuredClone(run); }); }
293
+ #changeRun(runId, change) { return this.#mutate(async (next) => { const run = next.runs.find(run => run.run_id === id.parse(runId)); if (!run)
294
+ throw Error('schedule_run_not_found'); await change(run, next); return structuredClone(run); }); }
261
295
  #mutate(change) {
262
296
  const pending = this.#tail.then(async () => {
263
- const next = structuredClone(this.#state), result = change(next);
297
+ const next = structuredClone(this.#state), result = await change(next);
264
298
  const terminal = next.runs.filter(run => run.stage === 'terminal' && run.terminal_summary?.published), retire = new Set(terminal.slice(0, Math.max(0, terminal.length - 2000)).map(run => run.run_id));
265
299
  next.runs = next.runs.filter(run => !retire.has(run.run_id));
266
300
  if (next.runs.length > 4096)
267
301
  throw Error('schedule_capacity');
302
+ // Idempotent ticks must not rewrite state or advance context authority, or foreground authorization never settles.
303
+ if (isDeepStrictEqual(next, this.#state))
304
+ return result;
268
305
  await this.#store.write(next);
269
306
  this.#state = next;
270
307
  try {
@@ -1,14 +1,15 @@
1
- import { randomUUID } from 'node:crypto';
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+ import { sourceFilterSchema } from '../memory/source-retrieval.js';
2
3
  import { z } from 'zod';
3
4
  import { appContextArguments } from '../core/schedule-tools.js';
4
5
  import { validParams } from '../realtime/bridge.js';
5
- const recallSchema = z.object({ query: z.string().trim().min(1).max(512), scope: z.enum(['recent', 'any']), source: z.literal('personal').optional() }).strict();
6
+ const recallSchema = z.object({ query: z.string().trim().min(1).max(512), scope: z.enum(['recent', 'any']), source: z.literal('personal').optional(), source_filter: sourceFilterSchema.optional() }).strict();
6
7
  const evidenceSchema = z.object({ evidence_id: z.string().min(1).max(512) }).strict();
7
- export function scheduledToolResult(call, data, code = 'ok', accepted = true, maxBytes = 32768) {
8
+ export function scheduledToolResult(call, data, code = 'ok', accepted = true, maxBytes = 32768, sourceProcessing = false) {
8
9
  const content = JSON.stringify(data);
9
10
  if (Buffer.byteLength(content) > maxBytes)
10
11
  throw Error('context_capacity');
11
- const item = { kind: 'tool_output', context_read: true, host_item_id: randomUUID(), event_id: randomUUID(), call_id: call.call_id, content };
12
+ const item = { kind: 'tool_output', context_read: true, ...(sourceProcessing ? { source_processing_read: true } : {}), host_item_id: randomUUID(), event_id: randomUUID(), call_id: call.call_id, content };
12
13
  return { accepted, code, host_item: item, response_intent: { kind: 'tool_result', item, task_summary: null, origin_spoken: false }, delegate_id: null, sync_result: false, executor: null, op: null, inline_fulfilled: accepted, telemetry: null };
13
14
  }
14
15
  export class ScheduledToolRuntime {
@@ -39,18 +40,32 @@ export class ScheduledToolRuntime {
39
40
  return false;
40
41
  }
41
42
  async accept(call) {
42
- const { host, grant, scope, tools, retrieval } = this.options, session = this.options.session(), responseId = call.response_id ?? session.activeProviderResponseId;
43
+ const { host, grant, scope, tools, retrieval } = this.options, session = this.options.session(), responseId = call.response_id ?? session.activeProviderResponseId, active = !!responseId && call.session_epoch === session.sessionEpoch && session.activeProviderResponseId === responseId && session.providerTurnPhase(responseId) === 'active' && !session.providerTurnWasFenced(responseId);
43
44
  try {
45
+ // A provider refusal is still a paid attempt. Attribute it only to this
46
+ // current host grant; authorization and response-scope checks remain below.
47
+ host.scheduledAuthority.assert(grant, grant.fence);
48
+ if (host.schedules.getRun(grant.run_id).processing) {
49
+ const attempt = createHash('sha256').update(JSON.stringify([call.session_epoch, responseId, call.call_id])).digest('hex');
50
+ try {
51
+ await host.schedules.reserveSourceProcessingAttempt(grant.run_id, attempt);
52
+ }
53
+ catch (error) {
54
+ if (error instanceof Error && error.message === 'processing_budget_exhausted')
55
+ await host.schedules.exhaustSourceProcessing(grant.run_id);
56
+ throw error;
57
+ }
58
+ }
44
59
  if (!responseId)
45
60
  throw Error('scheduled_response_unbound');
46
- scope.acceptCall(call.session_epoch, responseId, call.call_id, call.session_epoch === session.sessionEpoch && session.activeProviderResponseId === responseId && session.providerTurnPhase(responseId) === 'active' && !session.providerTurnWasFenced(responseId));
61
+ scope.acceptCall(call.session_epoch, responseId, call.call_id, active);
47
62
  if (!await this.validateContext())
48
63
  throw Error('context_authorization_changed');
49
64
  const run = host.schedules.getRun(grant.run_id), context = run.definition.context, binding = tools.bindings.get(call.name);
50
65
  if (run.processing) {
51
66
  if (call.name !== 'source__process')
52
- throw Error('scheduled_tool_readonly');
53
- return scheduledToolResult(call, await host.sourceProcessingAgent.call(grant, call.call_id, call.arguments), 'ok', true, 131072);
67
+ return scheduledToolResult(call, { state: 'refused', code: 'scheduled_tool_readonly', hint: 'The only provided function name is source__process. read, topics, profile, evidence, compose, finish, projects and project_diff are action values, not function names. Call function source__process with arguments {"action":"read"} to read the current batch; use that same function name for every subsequent action.' }, 'scheduled_tool_readonly', false);
68
+ return scheduledToolResult(call, await host.sourceProcessingAgent.call(grant, call.call_id, call.arguments), 'ok', true, 131072, true);
54
69
  }
55
70
  if (call.name === 'app__context') {
56
71
  const args = appContextArguments.parse(call.arguments);
@@ -63,7 +78,7 @@ export class ScheduledToolRuntime {
63
78
  if (call.name === 'memory__recall') {
64
79
  if (!context.memory && !context.knowledge)
65
80
  throw Error('context_not_authorized');
66
- const args = recallSchema.parse(call.arguments), found = await retrieval.recall(args.query, { scope: args.scope, consumer: grant.consumer, limit: 8 });
81
+ const args = recallSchema.parse(call.arguments), found = await retrieval.recall(args.query, { scope: args.scope, consumer: grant.consumer, limit: 8, ...(args.source_filter ? { sourceFilter: args.source_filter } : {}) });
67
82
  result = { ...found, entries: context.memory ? found.entries : [], snippets: context.knowledge ? found.snippets : [] };
68
83
  refs = [...new Set([...result.entries.flatMap(entry => entry.evidence_refs), ...result.snippets.map(snippet => snippet.evidence_id)])];
69
84
  }
@@ -102,7 +117,8 @@ export class ScheduledToolRuntime {
102
117
  }
103
118
  catch (error) {
104
119
  const code = error instanceof z.ZodError ? 'invalid_params' : error instanceof Error ? error.message : 'scheduled_tool_failed';
105
- return scheduledToolResult(call, { state: 'refused', code }, code, false);
120
+ const hint = error instanceof z.ZodError && call.name === 'source__process' ? 'Use only the fields declared for the chosen action. read accepts exactly {"action":"read"}. Batch, task, run and recipe identifiers are bound by the host; never include batch_id, task_id, run_id or recipe. Correct the arguments and retry.' : undefined;
121
+ return scheduledToolResult(call, { state: 'refused', code, ...(hint ? { hint } : {}) }, code, false);
106
122
  }
107
123
  }
108
124
  }