nova-personal-agent-server 0.0.0-stage → 0.4.1

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 (345) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/bin/novapersonal-server.mjs +4 -0
  4. package/package.json +61 -4
  5. package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
  6. package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
  7. package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
  8. package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
  9. package/resources/native/codex-sandbox-probe +0 -0
  10. package/resources/native/project-native/nova_project_native.node +0 -0
  11. package/resources/native-resources-v1.json +1 -0
  12. package/runtime/dist/eval/demos.js +156 -0
  13. package/runtime/dist/eval/fixture-host.js +385 -0
  14. package/runtime/dist/eval/fixtures.js +319 -0
  15. package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
  16. package/runtime/dist/eval/scorecard.js +285 -0
  17. package/runtime/dist/eval/sim.js +43 -0
  18. package/runtime/dist/src/cascaded-text-provider.js +31 -0
  19. package/runtime/dist/src/cli.js +96 -0
  20. package/runtime/dist/src/composition/assembly.js +352 -0
  21. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
  22. package/runtime/dist/src/composition/production-composition.js +389 -0
  23. package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
  24. package/runtime/dist/src/config/capability-registry.js +315 -0
  25. package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
  26. package/runtime/dist/src/config/coding-backends.js +8 -0
  27. package/runtime/dist/src/config/coding-profiles.js +98 -0
  28. package/runtime/dist/src/config/config.js +857 -0
  29. package/runtime/dist/src/config/diagnostics.js +139 -0
  30. package/runtime/dist/src/config/environment-contract.js +202 -0
  31. package/runtime/dist/src/config/self-hosted.js +23 -0
  32. package/runtime/dist/src/connectors/composio/client.js +195 -0
  33. package/runtime/dist/src/connectors/composio/google.js +208 -0
  34. package/runtime/dist/src/connectors/composio/index.js +334 -0
  35. package/runtime/dist/src/connectors/feishu/cli.js +220 -0
  36. package/runtime/dist/src/connectors/feishu/index.js +980 -0
  37. package/runtime/dist/src/connectors/macos/calendar.js +35 -0
  38. package/runtime/dist/src/connectors/macos/mail.js +32 -0
  39. package/runtime/dist/src/connectors/macos/reader.js +62 -0
  40. package/runtime/dist/src/conversation-voice-provider.js +41 -0
  41. package/runtime/dist/src/core/approval-port.js +9 -0
  42. package/runtime/dist/src/core/approval.js +1328 -0
  43. package/runtime/dist/src/core/calls.js +35 -0
  44. package/runtime/dist/src/core/camera-session.js +32 -0
  45. package/runtime/dist/src/core/causal-runtime.js +650 -0
  46. package/runtime/dist/src/core/clock.js +139 -0
  47. package/runtime/dist/src/core/context-view.js +156 -0
  48. package/runtime/dist/src/core/effects.js +62 -0
  49. package/runtime/dist/src/core/events.js +217 -0
  50. package/runtime/dist/src/core/executor-diagnostic.js +9 -0
  51. package/runtime/dist/src/core/ids.js +32 -0
  52. package/runtime/dist/src/core/media-store.js +104 -0
  53. package/runtime/dist/src/core/memory.js +296 -0
  54. package/runtime/dist/src/core/pending-decision.js +64 -0
  55. package/runtime/dist/src/core/ports.js +125 -0
  56. package/runtime/dist/src/core/runtime.js +1459 -0
  57. package/runtime/dist/src/core/schedule-tools.js +15 -0
  58. package/runtime/dist/src/core/sims.js +186 -0
  59. package/runtime/dist/src/core/slots.js +97 -0
  60. package/runtime/dist/src/core/source-processing-instructions.js +3 -0
  61. package/runtime/dist/src/core/source-processing-tools.js +12 -0
  62. package/runtime/dist/src/core/suggestions.js +143 -0
  63. package/runtime/dist/src/core/task-tools.js +22 -0
  64. package/runtime/dist/src/core/tool-schema.js +212 -0
  65. package/runtime/dist/src/core/trace.js +34 -0
  66. package/runtime/dist/src/core/work-tools.js +94 -0
  67. package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
  68. package/runtime/dist/src/desktop/desktop-camera.js +281 -0
  69. package/runtime/dist/src/desktop/desktop-control.js +140 -0
  70. package/runtime/dist/src/desktop/desktop-progress.js +162 -0
  71. package/runtime/dist/src/desktop/desktop-session.js +2106 -0
  72. package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
  73. package/runtime/dist/src/desktop/desktop-wire.js +605 -0
  74. package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
  75. package/runtime/dist/src/desktop/startup-error.js +18 -0
  76. package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
  77. package/runtime/dist/src/desktop-entry.js +106 -0
  78. package/runtime/dist/src/desktop.js +1092 -0
  79. package/runtime/dist/src/executors/acp/backends.js +105 -0
  80. package/runtime/dist/src/executors/acp/mcp.js +81 -0
  81. package/runtime/dist/src/executors/acp/preflight.js +14 -0
  82. package/runtime/dist/src/executors/acp/process-owner.js +112 -0
  83. package/runtime/dist/src/executors/acp/transport.js +760 -0
  84. package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
  85. package/runtime/dist/src/executors/agent-controller.js +244 -0
  86. package/runtime/dist/src/executors/autoglm.js +376 -0
  87. package/runtime/dist/src/executors/browser-device.js +102 -0
  88. package/runtime/dist/src/executors/browser.js +61 -0
  89. package/runtime/dist/src/executors/camera.js +101 -0
  90. package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
  91. package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
  92. package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
  93. package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
  94. package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
  95. package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
  96. package/runtime/dist/src/executors/codex/common.js +655 -0
  97. package/runtime/dist/src/executors/codex/contract.js +581 -0
  98. package/runtime/dist/src/executors/codex/controller.js +141 -0
  99. package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
  100. package/runtime/dist/src/executors/codex/factory.js +463 -0
  101. package/runtime/dist/src/executors/codex/host-config.js +238 -0
  102. package/runtime/dist/src/executors/codex/host.js +17 -0
  103. package/runtime/dist/src/executors/codex/index.js +19 -0
  104. package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
  105. package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
  106. package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
  107. package/runtime/dist/src/executors/codex/process-owner.js +398 -0
  108. package/runtime/dist/src/executors/codex/production-host.js +887 -0
  109. package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
  110. package/runtime/dist/src/executors/codex/protocol.js +581 -0
  111. package/runtime/dist/src/executors/codex/safe-json.js +87 -0
  112. package/runtime/dist/src/executors/codex/session-title.js +61 -0
  113. package/runtime/dist/src/executors/codex/shared-home.js +29 -0
  114. package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
  115. package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
  116. package/runtime/dist/src/executors/codex/version.js +38 -0
  117. package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
  118. package/runtime/dist/src/executors/coding/intake-model.js +103 -0
  119. package/runtime/dist/src/executors/coding/intake.js +824 -0
  120. package/runtime/dist/src/executors/coding/json-completion.js +14 -0
  121. package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
  122. package/runtime/dist/src/executors/coding/work-order.js +50 -0
  123. package/runtime/dist/src/executors/coding-executor.js +23 -0
  124. package/runtime/dist/src/executors/computer-backend.js +188 -0
  125. package/runtime/dist/src/executors/computer-device.js +187 -0
  126. package/runtime/dist/src/executors/computer-worker.js +125 -0
  127. package/runtime/dist/src/executors/computer.js +100 -0
  128. package/runtime/dist/src/executors/device-lock.js +127 -0
  129. package/runtime/dist/src/executors/frame-source.js +29 -0
  130. package/runtime/dist/src/executors/gui-evidence.js +30 -0
  131. package/runtime/dist/src/executors/gui-execution.js +237 -0
  132. package/runtime/dist/src/executors/gui-runner.js +88 -0
  133. package/runtime/dist/src/executors/host-executor-capability.js +12 -0
  134. package/runtime/dist/src/executors/index.js +13 -0
  135. package/runtime/dist/src/executors/mcp-client.js +198 -0
  136. package/runtime/dist/src/executors/mcp.js +210 -0
  137. package/runtime/dist/src/executors/mobile-android.js +180 -0
  138. package/runtime/dist/src/executors/mobile-ios.js +303 -0
  139. package/runtime/dist/src/executors/mobile.js +78 -0
  140. package/runtime/dist/src/executors/search-mcp.js +146 -0
  141. package/runtime/dist/src/executors/search.js +524 -0
  142. package/runtime/dist/src/executors/task-resources.js +38 -0
  143. package/runtime/dist/src/executors/vision/assess.js +296 -0
  144. package/runtime/dist/src/executors/vision/controller-core.js +373 -0
  145. package/runtime/dist/src/executors/vision/controller.js +164 -0
  146. package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
  147. package/runtime/dist/src/executors/vision.js +5 -0
  148. package/runtime/dist/src/executors/watcher.js +718 -0
  149. package/runtime/dist/src/http/bounded-response.js +37 -0
  150. package/runtime/dist/src/index.js +56 -0
  151. package/runtime/dist/src/knowledge/assembly.js +60 -0
  152. package/runtime/dist/src/knowledge/documents.js +520 -0
  153. package/runtime/dist/src/knowledge/embeddings.js +201 -0
  154. package/runtime/dist/src/knowledge/mcp.js +218 -0
  155. package/runtime/dist/src/knowledge/parse-worker.js +122 -0
  156. package/runtime/dist/src/knowledge/references.js +51 -0
  157. package/runtime/dist/src/knowledge/service.js +526 -0
  158. package/runtime/dist/src/knowledge/store-client.js +185 -0
  159. package/runtime/dist/src/knowledge/store-worker.js +843 -0
  160. package/runtime/dist/src/knowledge/types.js +2 -0
  161. package/runtime/dist/src/mcp/http-server.js +177 -0
  162. package/runtime/dist/src/mem0/resource.js +35 -0
  163. package/runtime/dist/src/mem0/store-worker.js +330 -0
  164. package/runtime/dist/src/memory/blackboard-session.js +205 -0
  165. package/runtime/dist/src/memory/blackboard-store.js +194 -0
  166. package/runtime/dist/src/memory/blackboard-worker.js +369 -0
  167. package/runtime/dist/src/memory/entry.js +39 -0
  168. package/runtime/dist/src/memory/factory.js +20 -0
  169. package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
  170. package/runtime/dist/src/memory/personal-memory.js +10 -0
  171. package/runtime/dist/src/memory/prerecall.js +20 -0
  172. package/runtime/dist/src/memory/provenance.js +17 -0
  173. package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
  174. package/runtime/dist/src/memory/retrieval.js +235 -0
  175. package/runtime/dist/src/memory/sensitivity.js +261 -0
  176. package/runtime/dist/src/memory-ledger/models.js +98 -0
  177. package/runtime/dist/src/memory-ledger/store-client.js +210 -0
  178. package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
  179. package/runtime/dist/src/memory-ledger/store.js +597 -0
  180. package/runtime/dist/src/memory-substrate/candidates.js +16 -0
  181. package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
  182. package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
  183. package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
  184. package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
  185. package/runtime/dist/src/memory-substrate/migration.js +87 -0
  186. package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
  187. package/runtime/dist/src/memory-substrate/purge.js +398 -0
  188. package/runtime/dist/src/memory-substrate/resolution.js +32 -0
  189. package/runtime/dist/src/memory-substrate/resource.js +867 -0
  190. package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
  191. package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
  192. package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
  193. package/runtime/dist/src/memory-substrate/source-state.js +93 -0
  194. package/runtime/dist/src/memory-substrate/store.js +534 -0
  195. package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
  196. package/runtime/dist/src/memory-substrate/workspace.js +21 -0
  197. package/runtime/dist/src/model/jev-client.js +25 -0
  198. package/runtime/dist/src/model/model-adapters.js +64 -0
  199. package/runtime/dist/src/model/model-gateway.js +399 -0
  200. package/runtime/dist/src/model/model-lane.js +34 -0
  201. package/runtime/dist/src/model/model-purpose.js +5 -0
  202. package/runtime/dist/src/model/personal-writer.js +361 -0
  203. package/runtime/dist/src/model/proactivity.js +72 -0
  204. package/runtime/dist/src/model/prompting.js +279 -0
  205. package/runtime/dist/src/model/task-verifier.js +217 -0
  206. package/runtime/dist/src/model/vision-capability.js +10 -0
  207. package/runtime/dist/src/news/feeds.js +114 -0
  208. package/runtime/dist/src/news/jev-ranking.js +25 -0
  209. package/runtime/dist/src/news/ranking.js +26 -0
  210. package/runtime/dist/src/news/service.js +262 -0
  211. package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
  212. package/runtime/dist/src/notifications/adapters/nova.js +15 -0
  213. package/runtime/dist/src/notifications/content.js +15 -0
  214. package/runtime/dist/src/notifications/contracts.js +9 -0
  215. package/runtime/dist/src/notifications/feed.js +8 -0
  216. package/runtime/dist/src/notifications/service.js +412 -0
  217. package/runtime/dist/src/notifications/store.js +4 -0
  218. package/runtime/dist/src/personal-agent/app-context.js +113 -0
  219. package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
  220. package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
  221. package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
  222. package/runtime/dist/src/personal-agent/contracts.js +32 -0
  223. package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
  224. package/runtime/dist/src/personal-agent/conversations.js +187 -0
  225. package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2403 -0
  227. package/runtime/dist/src/personal-agent/intake-task.js +37 -0
  228. package/runtime/dist/src/personal-agent/life.js +260 -0
  229. package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
  230. package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
  231. package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
  232. package/runtime/dist/src/personal-agent/project-digests.js +242 -0
  233. package/runtime/dist/src/personal-agent/sampling.js +20 -0
  234. package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
  235. package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
  236. package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
  237. package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
  238. package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
  239. package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
  240. package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
  241. package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
  242. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
  243. package/runtime/dist/src/personal-agent/source-priority.js +142 -0
  244. package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
  245. package/runtime/dist/src/personal-agent/source-walk.js +25 -0
  246. package/runtime/dist/src/personal-agent/sources.js +1484 -0
  247. package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
  248. package/runtime/dist/src/personal-agent/store.js +146 -0
  249. package/runtime/dist/src/personal-agent/task-loop.js +163 -0
  250. package/runtime/dist/src/personal-agent/tasks.js +920 -0
  251. package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
  252. package/runtime/dist/src/personal-agent/understanding.js +160 -0
  253. package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
  254. package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
  255. package/runtime/dist/src/projects/host-paths.js +133 -0
  256. package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
  257. package/runtime/dist/src/projects/project-confirmation.js +486 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +284 -0
  259. package/runtime/dist/src/projects/project-node-files.js +169 -0
  260. package/runtime/dist/src/projects/project-root-file.js +16 -0
  261. package/runtime/dist/src/projects/project-state.js +504 -0
  262. package/runtime/dist/src/projects/project-store-files.js +1271 -0
  263. package/runtime/dist/src/projects/project-store.js +1345 -0
  264. package/runtime/dist/src/realtime/aoq.js +141 -0
  265. package/runtime/dist/src/realtime/bridge.js +652 -0
  266. package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
  267. package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
  268. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
  269. package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
  270. package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
  271. package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
  272. package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
  273. package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
  274. package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
  275. package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
  276. package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
  277. package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
  278. package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
  279. package/runtime/dist/src/realtime/dictation.js +28 -0
  280. package/runtime/dist/src/realtime/evidence.js +276 -0
  281. package/runtime/dist/src/realtime/floor.js +43 -0
  282. package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
  283. package/runtime/dist/src/realtime/gemini.js +517 -0
  284. package/runtime/dist/src/realtime/history.js +122 -0
  285. package/runtime/dist/src/realtime/host-delivery.js +1711 -0
  286. package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
  287. package/runtime/dist/src/realtime/memory-board.js +105 -0
  288. package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
  289. package/runtime/dist/src/realtime/playback.js +242 -0
  290. package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
  291. package/runtime/dist/src/realtime/prompt-language.js +17 -0
  292. package/runtime/dist/src/realtime/protocol.js +428 -0
  293. package/runtime/dist/src/realtime/provider-projection.js +526 -0
  294. package/runtime/dist/src/realtime/provider-session.js +491 -0
  295. package/runtime/dist/src/realtime/qwen-transport.js +144 -0
  296. package/runtime/dist/src/realtime/qwen.js +1377 -0
  297. package/runtime/dist/src/realtime/recall.js +341 -0
  298. package/runtime/dist/src/realtime/service-ports.js +8 -0
  299. package/runtime/dist/src/realtime/service-state.js +259 -0
  300. package/runtime/dist/src/realtime/service.js +1726 -0
  301. package/runtime/dist/src/realtime/session-state.js +684 -0
  302. package/runtime/dist/src/realtime/session.js +1976 -0
  303. package/runtime/dist/src/realtime/speech-prep.js +63 -0
  304. package/runtime/dist/src/realtime/streaming-speech.js +120 -0
  305. package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
  306. package/runtime/dist/src/realtime/telemetry.js +144 -0
  307. package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
  308. package/runtime/dist/src/realtime/transport.js +8 -0
  309. package/runtime/dist/src/realtime/usage.js +55 -0
  310. package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
  311. package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
  312. package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
  313. package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
  314. package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
  315. package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
  316. package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
  317. package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
  318. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
  319. package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
  320. package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
  321. package/runtime/dist/src/server/aoq-chat-server.js +497 -0
  322. package/runtime/dist/src/server/client-pairing.js +192 -0
  323. package/runtime/dist/src/server/client-protocol.js +87 -0
  324. package/runtime/dist/src/server/client-server.js +312 -0
  325. package/runtime/dist/src/server/server-config.js +72 -0
  326. package/runtime/dist/src/server-entry.js +135 -0
  327. package/runtime/dist/src/storage/bounded-json.js +63 -0
  328. package/runtime/dist/src/storage/native-file-lock.js +8 -0
  329. package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
  330. package/runtime/dist/src/storage/private-database.js +120 -0
  331. package/runtime/dist/src/text/canonical-json.js +60 -0
  332. package/runtime/dist/src/text/python-number.js +18 -0
  333. package/runtime/dist/src/text/python-text.js +92 -0
  334. package/runtime/dist/src/text/unicode-casefold.js +29 -0
  335. package/runtime/dist/src/text/unicode-normalize.js +138 -0
  336. package/runtime/dist/src/text/unicode-tables.js +210 -0
  337. package/runtime/dist/src/understanding/candidates.js +77 -0
  338. package/runtime/dist/src/understanding/fixture.js +7 -0
  339. package/runtime/dist/src/understanding/jev.js +20 -0
  340. package/runtime/dist/src/understanding/pipeline.js +38 -0
  341. package/runtime/dist/src/voicemem/store-client.js +476 -0
  342. package/runtime/dist/src/voicemem/store-worker.js +380 -0
  343. package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
  344. package/runtime/scripts/pair-device.mjs +109 -0
  345. package/src/command.mjs +48 -0
@@ -0,0 +1,280 @@
1
+ import { SOURCE_PROCESSING_GOAL } from '../core/source-processing-instructions.js';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { z } from 'zod';
4
+ import { BoundedJsonStore } from '../storage/bounded-json.js';
5
+ import { canonicalJson } from '../text/canonical-json.js';
6
+ import { internalTaskInputSchema } from './tasks.js';
7
+ import { collectDueOccurrences, nextOccurrence, scheduleRuleSchema } from './scheduled-time.js';
8
+ const id = z.string().trim().min(1).max(512), instant = z.string().datetime();
9
+ export const scheduleContextSchema = z.object({ todos: z.boolean(), goals: z.boolean(), tasks: z.boolean(), memory: z.boolean(), knowledge: z.boolean(), search: z.boolean() }).strict();
10
+ 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
+ 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
+ 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();
16
+ const adoptionResultSchema = z.object({ id, version: z.number().int().positive() }).strict();
17
+ 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
+ const empty = () => ({ items: [], runs: [], receipts: {}, adoptions: {} });
19
+ export const scheduleHash = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
20
+ const definition = (item) => ({ title: item.title, goal: item.goal, acceptance: item.acceptance, rule: item.rule, context: item.context });
21
+ export class ScheduleService {
22
+ path;
23
+ changed;
24
+ now;
25
+ #state = empty();
26
+ #tail = Promise.resolve();
27
+ #store;
28
+ constructor(path, changed = () => { }, now = () => new Date()) {
29
+ this.path = path;
30
+ this.changed = changed;
31
+ this.now = now;
32
+ this.#store = new BoundedJsonStore(path, stateSchema, 16 * 1024 * 1024);
33
+ }
34
+ async open() { try {
35
+ this.#state = await this.#store.read(empty());
36
+ }
37
+ catch (error) {
38
+ if (error.code !== 'ENOENT')
39
+ throw error;
40
+ } }
41
+ async close() { await this.#tail; }
42
+ list() { return structuredClone(this.#state.items.filter(item => !item.archived)); }
43
+ get(scheduleId) { const item = this.#state.items.find(item => item.id === id.parse(scheduleId)); if (!item)
44
+ throw Error('schedule_not_found'); return structuredClone(item); }
45
+ findRun(runId) { const run = this.#state.runs.find(run => run.run_id === id.parse(runId)); return run ? structuredClone(run) : null; }
46
+ getRun(runId) { const run = this.findRun(runId); if (!run)
47
+ throw Error('schedule_run_not_found'); return run; }
48
+ 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')); }
50
+ terminalRuns() { return structuredClone(this.#state.runs.filter(run => run.stage === 'terminal')); }
51
+ reserveAdoption(requestId, runId, input) {
52
+ const run = this.getRun(runId), key = scheduleHash([run.authority.user_scope, id.parse(requestId)]), payload = scheduleHash({ runId, input });
53
+ return this.#mutate(next => { const prior = next.adoptions[key]; if (prior) {
54
+ if (prior.hash !== payload)
55
+ throw Error('request_conflict');
56
+ return { key, result: structuredClone(prior.result) };
57
+ } if (Object.keys(next.adoptions).length >= 20000)
58
+ throw Error('schedule_capacity'); next.adoptions[key] = { hash: payload, run_id: runId, result: null }; return { key, result: null }; });
59
+ }
60
+ finishAdoption(key, result) {
61
+ const parsed = adoptionResultSchema.parse(result);
62
+ return this.#mutate(next => { const prior = next.adoptions[id.parse(key)]; if (!prior)
63
+ throw Error('adoption_not_reserved'); if (prior.result && scheduleHash(prior.result) !== scheduleHash(parsed))
64
+ throw Error('adoption_conflict'); prior.result = parsed; return structuredClone(parsed); });
65
+ }
66
+ history(scheduleId, cursor = null, limit = 20) {
67
+ this.get(scheduleId);
68
+ z.number().int().min(1).max(100).parse(limit);
69
+ const runs = this.#state.runs.filter(run => run.schedule_id === scheduleId).reverse(), offset = cursor ? runs.findIndex(run => run.run_id === cursor) + 1 : 0;
70
+ if (cursor && offset === 0)
71
+ throw Error('history_cursor_expired');
72
+ const items = structuredClone(runs.slice(offset, offset + limit));
73
+ return { items, next_cursor: offset + limit < runs.length ? items.at(-1).run_id : null };
74
+ }
75
+ /** Host-only default registration; public schedule input cannot set processing metadata. */
76
+ ensureSourceProcessing(scope) {
77
+ const key = 'builtin-source-' + scheduleHash(scope).slice(0, 24), prior = this.#state.items.find(item => item.id === key);
78
+ if (prior?.goal === SOURCE_PROCESSING_GOAL)
79
+ return Promise.resolve(structuredClone(prior));
80
+ return this.#mutate(next => {
81
+ const existing = next.items.find(item => item.id === key);
82
+ if (existing) {
83
+ existing.goal = SOURCE_PROCESSING_GOAL;
84
+ existing.revision++;
85
+ return structuredClone(existing);
86
+ }
87
+ const context = { todos: false, goals: false, tasks: false, memory: false, knowledge: false, search: false };
88
+ const item = { id: key, revision: 1, enabled: true, archived: false, title: '资料增量整理', goal: SOURCE_PROCESSING_GOAL, acceptance: ['The batch was durably processed through source__process finish, with current authorization and grounded topic references.'], rule: { kind: 'daily', timezone: 'UTC', time: '00:00' }, context, authority: { user_scope: id.parse(scope), source: 'builtin', origin_ref: 'builtin:source-processing', source_refs: [], allowed_context: context }, cursor: this.now().toISOString(), next_slot: null, missed_count: 0, dst_gap_count: 0, processing: { failures: 0, next_attempt: this.now().toISOString() } };
89
+ next.items.push(item);
90
+ return structuredClone(item);
91
+ });
92
+ }
93
+ claimSourceProcessing(scheduleId, batchId, recipe) {
94
+ return this.#mutate(next => {
95
+ const item = next.items.find(item => item.id === scheduleId);
96
+ if (!item?.processing || !item.enabled || item.archived)
97
+ throw Error('builtin_schedule');
98
+ const runId = scheduleHash([item.id, id.parse(batchId), id.parse(recipe)]), prior = next.runs.find(run => run.run_id === runId);
99
+ if (prior)
100
+ return structuredClone(prior);
101
+ if (Date.parse(item.processing.next_attempt) > +this.now())
102
+ throw Error('processing_backoff');
103
+ if (next.runs.some(run => run.schedule_id === item.id && run.stage !== 'terminal'))
104
+ 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: [] };
107
+ next.runs.push(run);
108
+ return structuredClone(run);
109
+ });
110
+ }
111
+ exhaustSourceProcessing(runId) { return this.#changeRun(runId, run => { if (run.processing)
112
+ run.processing.exhausted = true; }); }
113
+ reserveSourceProcessingCall(runId, callId) {
114
+ return this.#changeRun(runId, run => {
115
+ if (!run.processing || run.stage === 'terminal')
116
+ throw Error('builtin_schedule');
117
+ if (run.processing.calls.includes(id.parse(callId)))
118
+ return;
119
+ if (run.processing.calls.length >= 24)
120
+ throw Error('processing_budget_exhausted');
121
+ run.processing.calls.push(callId);
122
+ });
123
+ }
124
+ async create(requestId, value, source) {
125
+ const input = scheduleInputSchema.parse(value), authority = authoritySchema.parse(source);
126
+ this.#context(input.context, authority);
127
+ return this.#mutate(next => this.#request(next, authority.user_scope, requestId, { operation: 'create', input, authority }, 'schedule', () => {
128
+ const now = this.now(), next_slot = nextOccurrence(input.rule, now);
129
+ if (!next_slot)
130
+ throw Error('schedule_in_past');
131
+ const occupied = next.items.filter(item => !item.archived || next.runs.some(run => run.schedule_id === item.id && run.stage !== 'terminal')).length;
132
+ if (occupied >= 64 || next.items.length >= 4096)
133
+ throw Error('schedule_capacity');
134
+ const item = { ...input, id: randomUUID(), revision: 1, enabled: true, archived: false, authority, cursor: now.toISOString(), next_slot, missed_count: 0, dst_gap_count: 0 };
135
+ next.items.push(item);
136
+ return item;
137
+ }));
138
+ }
139
+ async update(requestId, scheduleId, expectedRevision, value, source) {
140
+ const input = scheduleInputSchema.parse(value);
141
+ const authority = source ? authoritySchema.parse(source) : undefined;
142
+ return this.#edit(requestId, scheduleId, expectedRevision, 'update', authority ? { input, authority } : input, item => {
143
+ if (authority) {
144
+ if (authority.user_scope !== item.authority.user_scope)
145
+ throw Error('schedule_not_owned');
146
+ item.authority = authority;
147
+ }
148
+ this.#context(input.context, item.authority);
149
+ const next_slot = nextOccurrence(input.rule, new Date(Math.max(this.now().getTime(), Date.parse(item.cursor))));
150
+ if (!next_slot)
151
+ throw Error('schedule_in_past');
152
+ Object.assign(item, input, { next_slot });
153
+ // A changed calendar starts in the future; editing content alone preserves pending time slots.
154
+ if (scheduleHash(input.rule) !== scheduleHash(this.get(scheduleId).rule))
155
+ item.cursor = new Date(Math.max(this.now().getTime(), Date.parse(item.cursor))).toISOString();
156
+ });
157
+ }
158
+ pause(requestId, scheduleId, revision) { return this.#edit(requestId, scheduleId, revision, 'pause', null, item => { item.enabled = false; item.next_slot = null; }); }
159
+ resume(requestId, scheduleId, revision) { return this.#edit(requestId, scheduleId, revision, 'resume', null, item => { item.enabled = true; item.cursor = new Date(Math.max(this.now().getTime(), Date.parse(item.cursor))).toISOString(); item.next_slot = nextOccurrence(item.rule, new Date(item.cursor)); if (!item.next_slot)
160
+ throw Error('schedule_in_past'); }); }
161
+ delete(requestId, scheduleId, revision) { return this.#edit(requestId, scheduleId, revision, 'delete', null, item => { item.archived = true; item.enabled = false; item.next_slot = null; }); }
162
+ async runNow(requestId, scheduleId, expectedRevision) {
163
+ const item = this.get(scheduleId);
164
+ if (item.processing)
165
+ throw Error('builtin_schedule');
166
+ return this.#mutate(next => this.#request(next, item.authority.user_scope, requestId, { operation: 'run_now', scheduleId, expectedRevision }, 'run', () => {
167
+ const current = this.#current(next, scheduleId, expectedRevision);
168
+ if (next.runs.some(run => run.schedule_id === scheduleId && run.stage !== 'terminal'))
169
+ throw Error('schedule_running');
170
+ const run = this.#run(current, null, 'manual', scheduleHash([scheduleId, 'manual', current.authority.user_scope, requestId]));
171
+ next.runs.push(run);
172
+ return run;
173
+ }));
174
+ }
175
+ claimDue() {
176
+ return this.#mutate(next => {
177
+ const now = this.now(), claimed = [];
178
+ for (const item of next.items) {
179
+ if (item.processing || !item.enabled || item.archived || +now <= Date.parse(item.cursor))
180
+ continue;
181
+ const due = collectDueOccurrences(item.rule, new Date(item.cursor), now);
182
+ item.cursor = now.toISOString();
183
+ item.next_slot = nextOccurrence(item.rule, now);
184
+ item.missed_count += due.missed_count;
185
+ item.dst_gap_count += due.dst_gaps.length;
186
+ if (!due.latest)
187
+ continue;
188
+ const runId = scheduleHash([item.id, due.latest.slot_key]);
189
+ if (next.runs.some(run => run.run_id === runId))
190
+ continue;
191
+ const run = this.#run(item, due.latest, 'scheduled', runId);
192
+ if (next.runs.some(run => run.schedule_id === item.id && run.stage !== 'terminal')) {
193
+ run.stage = 'terminal';
194
+ run.terminal_summary = { outcome: 'skipped', text: 'Previous run remains unresolved', evidence_refs: [], published: false };
195
+ }
196
+ else
197
+ claimed.push(run);
198
+ next.runs.push(run);
199
+ }
200
+ return claimed;
201
+ });
202
+ }
203
+ bindTask(runId, taskId) { return this.#changeRun(runId, run => { if (run.task_id && run.task_id !== taskId)
204
+ throw Error('run_task_conflict'); if (run.stage === 'terminal')
205
+ throw Error('run_terminal'); run.task_id = id.parse(taskId); if (run.stage === 'claimed')
206
+ run.stage = 'bound'; }); }
207
+ markPrepared(runId, namespace) { return this.#changeRun(runId, run => { if (!run.task_id || namespace !== 'schedule-run:' + run.run_id)
208
+ throw Error('invalid_run_namespace'); if (run.stage === 'terminal')
209
+ throw Error('run_terminal'); run.prepared_namespace = namespace; run.stage = 'prepared'; }); }
210
+ markFinished(runId, summary) {
211
+ const parsed = summarySchema.parse(summary);
212
+ return this.#changeRun(runId, (run, next) => { if (run.terminal_summary) {
213
+ if (scheduleHash({ ...run.terminal_summary, published: false }) !== scheduleHash({ ...parsed, published: false }))
214
+ throw Error('run_result_conflict');
215
+ 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();
219
+ } });
220
+ }
221
+ 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 }; }); }
223
+ markPublished(runId) { return this.#changeRun(runId, run => { if (!run.terminal_summary)
224
+ throw Error('run_not_terminal'); run.terminal_summary.published = true; }); }
225
+ #run(item, slot, trigger, run_id) {
226
+ const frozen = definition(item), definition_hash = scheduleHash(frozen);
227
+ const input = { execution_route: 'nova', conversation_id: 'schedule:' + item.id, conversation_generation: 0, goal: item.goal, acceptance: item.acceptance, origin_ref: 'schedule-run:' + run_id, trigger: { kind: 'schedule', schedule_id: item.id, run_id, definition_revision: item.revision, definition_hash } };
228
+ return { run_id, schedule_id: item.id, definition_revision: item.revision, definition_hash, definition: frozen, authority: structuredClone(item.authority), slot, trigger, claimed_at: this.now().toISOString(), input, stage: 'claimed', task_id: null, prepared_namespace: null, terminal_summary: null };
229
+ }
230
+ #context(context, authority) { for (const key of Object.keys(context))
231
+ if (context[key] && !authority.allowed_context[key])
232
+ throw Error('context_not_authorized'); }
233
+ #current(next, scheduleId, revision) { z.number().int().positive().parse(revision); const item = next.items.find(item => item.id === id.parse(scheduleId)); if (!item || item.archived)
234
+ throw Error('schedule_not_found'); if (item.revision !== revision)
235
+ throw Error('stale_schedule'); return item; }
236
+ #edit(requestId, scheduleId, revision, operation, input, change) {
237
+ const existing = this.get(scheduleId);
238
+ if (existing.processing)
239
+ throw Error('builtin_schedule');
240
+ const scope = existing.authority.user_scope;
241
+ return this.#mutate(next => this.#request(next, scope, requestId, { operation, scheduleId, revision, input }, 'schedule', () => { const item = this.#current(next, scheduleId, revision); change(item); item.revision++; return item; }));
242
+ }
243
+ #request(next, scope, requestId, body, kind, create) {
244
+ const key = scheduleHash([scope, id.parse(requestId)]), payload = scheduleHash(body), receipt = next.receipts[key];
245
+ if (receipt) {
246
+ if (receipt.hash !== payload)
247
+ throw Error('request_conflict');
248
+ const result = receipt.kind === 'schedule' ? next.items.find(item => item.id === receipt.id) : next.runs.find(run => run.run_id === receipt.id);
249
+ if (!result)
250
+ throw Error('schedule_request_retired');
251
+ return structuredClone(result);
252
+ }
253
+ if (Object.keys(next.receipts).length >= 20000)
254
+ throw Error('schedule_capacity');
255
+ const result = create();
256
+ next.receipts[key] = { hash: payload, kind, id: kind === 'schedule' ? result.id : result.run_id };
257
+ return structuredClone(result);
258
+ }
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); }); }
261
+ #mutate(change) {
262
+ const pending = this.#tail.then(async () => {
263
+ const next = structuredClone(this.#state), result = change(next);
264
+ 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
+ next.runs = next.runs.filter(run => !retire.has(run.run_id));
266
+ if (next.runs.length > 4096)
267
+ throw Error('schedule_capacity');
268
+ await this.#store.write(next);
269
+ this.#state = next;
270
+ try {
271
+ this.changed();
272
+ }
273
+ catch { /* persistence already committed */ }
274
+ return result;
275
+ });
276
+ this.#tail = pending.catch(() => { });
277
+ return pending;
278
+ }
279
+ }
280
+ //# sourceMappingURL=scheduled-tasks.js.map
@@ -0,0 +1,99 @@
1
+ import { z } from 'zod';
2
+ export const SCHEDULE_CATCHUP_MS = 2 * 60 * 60 * 1000;
3
+ const timezone = z.string().min(1).max(100).refine(value => { try {
4
+ new Intl.DateTimeFormat('en', { timeZone: value });
5
+ return true;
6
+ }
7
+ catch {
8
+ return false;
9
+ } }, 'invalid_timezone');
10
+ const time = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
11
+ const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine(value => { const instant = new Date(value + 'T00:00:00Z'); return Number.isFinite(+instant) && instant.toISOString().slice(0, 10) === value; }, 'invalid_date');
12
+ const ruleSchema = z.discriminatedUnion('kind', [
13
+ z.object({ kind: z.literal('once'), timezone, date, time }).strict(),
14
+ z.object({ kind: z.literal('daily'), timezone, time }).strict(),
15
+ z.object({ kind: z.literal('weekly'), timezone, time, weekdays: z.array(z.number().int().min(1).max(7)).min(1).max(7).refine(days => new Set(days).size === days.length, 'duplicate_weekday') }).strict(),
16
+ ]);
17
+ export const scheduleRuleSchema = ruleSchema.refine(rule => rule.kind !== 'once' || resolveLocal(rule.timezone, rule.date, rule.time).instant !== null, 'nonexistent_local_time');
18
+ function format(zone) { return new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); }
19
+ function local(formatter, instant) {
20
+ const p = Object.fromEntries(formatter.formatToParts(new Date(instant)).map(part => [part.type, part.value]));
21
+ return p.year + '-' + p.month + '-' + p.day + 'T' + p.hour + ':' + p.minute;
22
+ }
23
+ const resolved = new Map();
24
+ function resolveLocal(zone, day, clock) {
25
+ const key = zone + ':' + day + ':' + clock, cached = resolved.get(key);
26
+ if (cached)
27
+ return cached;
28
+ const formatter = format(zone), target = day + 'T' + clock, nominal = Date.parse(target + ':00Z'), offsets = new Set();
29
+ // Sample both sides of civil-time transitions; verify every resulting instant by round trip.
30
+ for (let hours = -48; hours <= 48; hours += 6) {
31
+ const probe = nominal + hours * 3600000;
32
+ offsets.add(Date.parse(local(formatter, probe) + ':00Z') - probe);
33
+ }
34
+ const candidates = [...offsets].map(offset => nominal - offset).sort((a, b) => a - b);
35
+ const instant = candidates.find(candidate => local(formatter, candidate) === target) ?? null;
36
+ let gap_at = 0;
37
+ if (instant === null) {
38
+ const lower = candidates[0], upper = candidates.at(-1);
39
+ for (let probe = lower; probe <= upper; probe += 60000)
40
+ if (local(formatter, probe) >= target) {
41
+ gap_at = probe;
42
+ break;
43
+ }
44
+ if (!gap_at)
45
+ gap_at = upper;
46
+ }
47
+ const value = { instant, gap_at };
48
+ if (resolved.size >= 4096)
49
+ resolved.delete(resolved.keys().next().value);
50
+ resolved.set(key, value);
51
+ return value;
52
+ }
53
+ function addDay(day, days) { return new Date(Date.parse(day + 'T00:00:00Z') + days * 86400000).toISOString().slice(0, 10); }
54
+ function matches(rule, day) { return rule.kind === 'once' ? rule.date === day : rule.kind === 'daily' || rule.weekdays.includes(new Date(day + 'T00:00:00Z').getUTCDay() || 7); }
55
+ function slot(rule, day, instant) { return { scheduled_at: new Date(instant).toISOString(), local_date: day, local_time: rule.time, slot_key: rule.timezone + ':' + day + ':' + rule.time }; }
56
+ export function nextOccurrence(input, after) {
57
+ const rule = scheduleRuleSchema.parse(input);
58
+ if (!Number.isFinite(+after))
59
+ throw Error('invalid_clock');
60
+ const first = rule.kind === 'once' ? rule.date : local(format(rule.timezone), +after).slice(0, 10);
61
+ for (let offset = 0; offset < (rule.kind === 'once' ? 1 : 370); offset++) {
62
+ const day = addDay(first, offset);
63
+ if (!matches(rule, day))
64
+ continue;
65
+ const { instant } = resolveLocal(rule.timezone, day, rule.time);
66
+ if (instant !== null && instant > +after)
67
+ return slot(rule, day, instant);
68
+ }
69
+ return null;
70
+ }
71
+ export function collectDueOccurrences(input, after, now) {
72
+ const rule = scheduleRuleSchema.parse(input), due = { latest: null, missed_count: 0, dst_gaps: [] };
73
+ if (!Number.isFinite(+after) || !Number.isFinite(+now))
74
+ throw Error('invalid_clock');
75
+ if (+now <= +after)
76
+ return due;
77
+ const formatter = format(rule.timezone), first = rule.kind === 'once' ? rule.date : local(formatter, +after).slice(0, 10), last = rule.kind === 'once' ? rule.date : local(formatter, +now).slice(0, 10);
78
+ for (let day = first; day <= last; day = addDay(day, 1)) {
79
+ if (!matches(rule, day))
80
+ continue;
81
+ const { instant, gap_at } = resolveLocal(rule.timezone, day, rule.time);
82
+ if (instant === null) {
83
+ if (gap_at > +after && gap_at <= +now)
84
+ due.dst_gaps.push(day);
85
+ continue;
86
+ }
87
+ if (instant <= +after || instant > +now)
88
+ continue;
89
+ if (instant < +now - SCHEDULE_CATCHUP_MS) {
90
+ due.missed_count++;
91
+ continue;
92
+ }
93
+ if (due.latest)
94
+ due.missed_count++;
95
+ due.latest = slot(rule, day, instant);
96
+ }
97
+ return due;
98
+ }
99
+ //# sourceMappingURL=scheduled-time.js.map
@@ -0,0 +1,109 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { appContextArguments } from '../core/schedule-tools.js';
4
+ 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 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
+ const content = JSON.stringify(data);
9
+ if (Buffer.byteLength(content) > maxBytes)
10
+ 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
+ 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
+ export class ScheduledToolRuntime {
15
+ options;
16
+ constructor(options) {
17
+ this.options = options;
18
+ }
19
+ async validateContext() {
20
+ const { host, grant } = this.options;
21
+ try {
22
+ host.scheduledAuthority.assert(grant, grant.fence);
23
+ if (host.schedules.getRun(grant.run_id).processing) {
24
+ if (!host.schedules.getRun(grant.run_id).processing.exhausted && await host.sourceProcessingAgent.validate(grant))
25
+ return true;
26
+ throw Error('processing_context_unavailable');
27
+ }
28
+ if (await host.appContext.validateTask(grant.task_id, grant.consumer))
29
+ return true;
30
+ }
31
+ catch { /* stale authority is never usable */ }
32
+ try {
33
+ const task = host.tasks.get(grant.task_id);
34
+ if (task.pending_delivery)
35
+ await host.tasks.finishDelivery(task.id, task.pending_delivery);
36
+ await host.tasks.wait(grant.fence, 'context_authorization_changed');
37
+ }
38
+ catch { /* a newer owner or terminal state wins */ }
39
+ return false;
40
+ }
41
+ async accept(call) {
42
+ const { host, grant, scope, tools, retrieval } = this.options, session = this.options.session(), responseId = call.response_id ?? session.activeProviderResponseId;
43
+ try {
44
+ if (!responseId)
45
+ 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));
47
+ if (!await this.validateContext())
48
+ throw Error('context_authorization_changed');
49
+ const run = host.schedules.getRun(grant.run_id), context = run.definition.context, binding = tools.bindings.get(call.name);
50
+ if (run.processing) {
51
+ 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);
54
+ }
55
+ if (call.name === 'app__context') {
56
+ const args = appContextArguments.parse(call.arguments);
57
+ return scheduledToolResult(call, await host.readAppContext(args.section, args.cursor, grant));
58
+ }
59
+ if (call.name === 'memory__recall' || call.name === 'memory__evidence') {
60
+ if (!grant.consumer)
61
+ throw Error('memory_consumer_unavailable');
62
+ let result, refs;
63
+ if (call.name === 'memory__recall') {
64
+ if (!context.memory && !context.knowledge)
65
+ 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 });
67
+ result = { ...found, entries: context.memory ? found.entries : [], snippets: context.knowledge ? found.snippets : [] };
68
+ refs = [...new Set([...result.entries.flatMap(entry => entry.evidence_refs), ...result.snippets.map(snippet => snippet.evidence_id)])];
69
+ }
70
+ else {
71
+ if (!context.knowledge)
72
+ throw Error('context_not_authorized');
73
+ const args = evidenceSchema.parse(call.arguments);
74
+ result = await retrieval.evidence(args.evidence_id, { consumer: grant.consumer });
75
+ refs = result.evidence ? [result.evidence.evidence_id] : [];
76
+ }
77
+ host.scheduledAuthority.assert(grant, grant.fence);
78
+ if (!await host.appContext.validateRefs(refs, grant.consumer, grant.task_id))
79
+ throw Error('context_authorization_changed');
80
+ await host.tasks.recordContextEvidence(grant.fence, call.call_id, JSON.stringify({ consumer: grant.consumer, projection: result }), refs);
81
+ if (!await this.validateContext())
82
+ throw Error('context_authorization_changed');
83
+ return scheduledToolResult(call, result);
84
+ }
85
+ if (binding?.kind === 'delegate' && binding.executor === 'search' && binding.op && context.search && this.options.readonlyOperation(binding.executor, binding.op)) {
86
+ const raw = { ...call.arguments };
87
+ delete raw.origin_ref;
88
+ const schema = tools.schemas.find(schema => schema.function?.name === call.name)?.function;
89
+ const parameters = structuredClone(schema?.parameters ?? {}), properties = parameters.properties;
90
+ if (properties)
91
+ delete properties.origin_ref;
92
+ if (Array.isArray(parameters.required))
93
+ parameters.required = parameters.required.filter(key => key !== 'origin_ref');
94
+ if (!validParams(raw, parameters))
95
+ throw Error('invalid_params');
96
+ const admitted = await this.options.dispatch(binding, raw);
97
+ if (!admitted.accepted || !admitted.delegate_id)
98
+ throw Error('runtime_rejected');
99
+ return { ...scheduledToolResult(call, { state: 'pending' }, 'accepted'), delegate_id: admitted.delegate_id, sync_result: true, executor: binding.executor, op: binding.op, inline_fulfilled: false };
100
+ }
101
+ throw Error('scheduled_tool_readonly');
102
+ }
103
+ catch (error) {
104
+ 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);
106
+ }
107
+ }
108
+ }
109
+ //# sourceMappingURL=scheduled-tool-runtime.js.map
@@ -0,0 +1,142 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { homedir } from 'node:os';
4
+ import { lstat, readFile } from 'node:fs/promises';
5
+ import { join, resolve } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { z } from 'zod';
8
+ import { BoundedJsonStore } from '../storage/bounded-json.js';
9
+ const recentGit = (root, now) => root.lastGitCommitMs !== null && now - root.lastGitCommitMs < 30 * 86_400_000;
10
+ const recentMtime = (root, now) => now - root.mtimeMs < 7 * 86_400_000;
11
+ export function orderComputerRoots(roots) {
12
+ const now = Date.now();
13
+ return [...roots].sort((a, b) => Number(b.selected) - Number(a.selected)
14
+ || Number(b.currentWorkspace) - Number(a.currentWorkspace)
15
+ || Number(recentGit(b, now)) - Number(recentGit(a, now))
16
+ || (b.lastGitCommitMs ?? 0) - (a.lastGitCommitMs ?? 0)
17
+ || Number(recentMtime(b, now)) - Number(recentMtime(a, now))
18
+ || (recentMtime(b, now) ? b.mtimeMs - a.mtimeMs : 0) || a.path.localeCompare(b.path));
19
+ }
20
+ /** Four selected/current, two recent-Git, one recent-mtime, then one other turn. */
21
+ export function nextComputerRoot(roots, turn, cursors, skipped = new Set()) {
22
+ const now = Date.now();
23
+ const tiers = [
24
+ roots.filter(root => root.selected || root.currentWorkspace),
25
+ roots.filter(root => !root.selected && !root.currentWorkspace && recentGit(root, now)),
26
+ roots.filter(root => !root.selected && !root.currentWorkspace && !recentGit(root, now) && recentMtime(root, now)),
27
+ roots.filter(root => !root.selected && !root.currentWorkspace && !recentGit(root, now) && !recentMtime(root, now)),
28
+ ];
29
+ const preferred = [0, 0, 0, 0, 1, 1, 2, 3][turn % 8];
30
+ for (const tier of [preferred, (preferred + 1) % 4, (preferred + 2) % 4, (preferred + 3) % 4]) {
31
+ const available = tiers[tier].filter(root => !skipped.has(root.path));
32
+ if (!available.length)
33
+ continue;
34
+ const cursor = cursors[tier] ?? 0;
35
+ cursors[tier] = cursor + 1;
36
+ return available[cursor % available.length];
37
+ }
38
+ return undefined;
39
+ }
40
+ const run = promisify(execFile);
41
+ export async function rootActivity(path) {
42
+ const stat = await lstat(path).catch(() => null);
43
+ let lastGitCommitMs = null, ownCommits = 0;
44
+ const marker = await lstat(join(path, '.git')).catch(() => null);
45
+ if (marker && (marker.isDirectory() || marker.isFile()) && !marker.isSymbolicLink()) {
46
+ try {
47
+ const ident = await run('git', ['-C', path, 'var', 'GIT_AUTHOR_IDENT'], { timeout: 500, maxBuffer: 512 });
48
+ const email = /<([^<>]+)>/u.exec(ident.stdout)?.[1]?.toLowerCase();
49
+ if (email) {
50
+ const { stdout } = await run('git', ['-C', path, 'log', '-50', '--since=30.days', '--format=%ae|%ct'], { timeout: 500, maxBuffer: 8192 });
51
+ for (const line of stdout.trim().split('\n')) {
52
+ const at = line.lastIndexOf('|'), seconds = Number(line.slice(at + 1));
53
+ if (at > 0 && line.slice(0, at).toLowerCase() === email && Number.isFinite(seconds) && seconds > 0) {
54
+ lastGitCommitMs = Math.max(lastGitCommitMs ?? 0, seconds * 1000);
55
+ ownCommits++;
56
+ }
57
+ }
58
+ }
59
+ }
60
+ catch { /* A missing or unavailable Git history is only an absent ranking clue. */ }
61
+ }
62
+ return { lastGitCommitMs, ownCommits, mtimeMs: stat?.mtimeMs ?? 0 };
63
+ }
64
+ /** Cheap metadata that changes whenever a commit, checkout, or identity change could alter the Git clues. */
65
+ export async function activityKey(path) {
66
+ const stamp = async (target) => { const info = await lstat(target).catch(() => null); return info ? `${info.mtimeMs}:${info.size}` : '-'; };
67
+ const git = join(path, '.git');
68
+ // A linked worktree or submodule keeps a `gitdir:` pointer file; its HEAD and reflog live there.
69
+ const pointer = /^gitdir: (.+)$/mu.exec(await readFile(git, 'utf8').catch(() => ''))?.[1]?.trim();
70
+ const dir = pointer ? resolve(path, pointer) : git;
71
+ const shared = (await readFile(join(dir, 'commondir'), 'utf8').catch(() => '')).trim();
72
+ const common = shared ? resolve(dir, shared) : dir;
73
+ // The effective author identity also comes from global config and the environment.
74
+ const config = process.env.XDG_CONFIG_HOME?.trim() ? process.env.XDG_CONFIG_HOME : join(homedir(), '.config');
75
+ const identity = ['GIT_AUTHOR_EMAIL', 'GIT_AUTHOR_NAME', 'EMAIL', 'GIT_CONFIG_GLOBAL'].map(name => process.env[name] ?? '').join(',');
76
+ const stamps = await Promise.all([path, git, dir, join(dir, 'HEAD'), join(dir, 'logs', 'HEAD'), join(common, 'config'), join(dir, 'config.worktree'), process.env.GIT_CONFIG_GLOBAL?.trim() ? process.env.GIT_CONFIG_GLOBAL : join(homedir(), '.gitconfig'), join(config, 'git', 'config')].map(stamp));
77
+ return [...stamps, createHash('sha256').update(identity).digest('hex').slice(0, 16)].join('|');
78
+ }
79
+ const activitySchema = z.object({ lastGitCommitMs: z.number().nullable(), ownCommits: z.number().int().nonnegative(), mtimeMs: z.number() });
80
+ const cacheSchema = z.object({ version: z.literal(1), roots: z.record(z.string().max(4096), z.object({ key: z.string().max(512), checked: z.number(), value: activitySchema })) });
81
+ /** Git activity survives restarts: an unchanged repository costs a few lstats, not two Git processes. */
82
+ export class GitActivityCache {
83
+ #store;
84
+ #memory = new Map();
85
+ #probe;
86
+ #dirty = false;
87
+ constructor(path, probe = rootActivity) {
88
+ this.#store = path ? new BoundedJsonStore(path, cacheSchema, 2 * 1024 * 1024) : undefined;
89
+ this.#probe = probe;
90
+ }
91
+ async open() {
92
+ const state = await this.#store?.read({ version: 1, roots: {} }).catch(() => undefined);
93
+ // A scan may already have probed a root while the file was being read; its result is newer.
94
+ for (const [path, entry] of Object.entries(state?.roots ?? {}))
95
+ if (!this.#memory.has(path))
96
+ this.#memory.set(path, { ...entry, verified: 0 });
97
+ }
98
+ peek(path) { return this.#memory.get(path)?.value; }
99
+ /** Rechecks metadata at most every `recheckMs`; runs Git only when the key moved or the record is a day old. */
100
+ async get(path, recheckMs = 300_000) {
101
+ const now = Date.now(), cached = this.#memory.get(path);
102
+ if (cached && now - cached.verified < recheckMs)
103
+ return cached.value;
104
+ const key = await activityKey(path);
105
+ if (cached?.key === key && now - cached.checked < 86_400_000) {
106
+ cached.verified = now;
107
+ return cached.value;
108
+ }
109
+ const value = await this.#probe(path);
110
+ this.#memory.set(path, { key, checked: now, value, verified: now });
111
+ this.#dirty = true;
112
+ return value;
113
+ }
114
+ async flush() {
115
+ if (!this.#store || !this.#dirty)
116
+ return;
117
+ this.#dirty = false;
118
+ // Newest 256 roots; older entries only cost a Git probe if they return.
119
+ const roots = Object.fromEntries([...this.#memory].sort((a, b) => b[1].checked - a[1].checked).slice(0, 256).map(([path, { key, checked, value }]) => [path, { key, checked, value }]));
120
+ try {
121
+ await this.#store.write({ version: 1, roots });
122
+ }
123
+ catch {
124
+ this.#dirty = true;
125
+ }
126
+ }
127
+ }
128
+ /** Directories a repository ignores (build output, data, dependencies), listed once without descending into them. */
129
+ export async function gitIgnoredDirectories(root) {
130
+ try {
131
+ const { stdout } = await run('git', ['-C', root, 'ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '--no-empty-directory', '-z'], { timeout: 5000, maxBuffer: 512 * 1024 });
132
+ const dirs = new Set();
133
+ for (const entry of stdout.split('\0'))
134
+ if (entry.endsWith('/') && dirs.size < 5000)
135
+ dirs.add(join(root, entry.slice(0, -1)));
136
+ return dirs;
137
+ }
138
+ catch {
139
+ return null; /* Without Git the walk falls back to its name exclusions. */
140
+ }
141
+ }
142
+ //# sourceMappingURL=source-priority.js.map