nova-personal-agent-server 0.4.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +10 -0
  3. package/bin/nova-space-host.mjs +4 -0
  4. package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
  5. package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
  6. package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
  7. package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
  8. package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
  9. package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
  10. package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
  11. package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
  12. package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
  13. package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
  14. package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
  15. package/node_modules/@nova-personal-agent/relay/package.json +1 -0
  16. package/package.json +11 -4
  17. package/runtime/dist/src/cascaded-text-provider.js +8 -3
  18. package/runtime/dist/src/composition/assembly.js +133 -35
  19. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
  20. package/runtime/dist/src/composition/production-composition.js +57 -21
  21. package/runtime/dist/src/composition/realtime-assembly.js +160 -52
  22. package/runtime/dist/src/composition/soul-context.js +22 -0
  23. package/runtime/dist/src/config/capability-registry.js +48 -3
  24. package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
  25. package/runtime/dist/src/config/config.js +541 -128
  26. package/runtime/dist/src/config/credential-rotation.js +26 -0
  27. package/runtime/dist/src/config/data-root.js +764 -0
  28. package/runtime/dist/src/config/diagnostics.js +3 -1
  29. package/runtime/dist/src/config/environment-contract.js +190 -188
  30. package/runtime/dist/src/config/model-routes.js +140 -0
  31. package/runtime/dist/src/config/voice-credentials.js +55 -0
  32. package/runtime/dist/src/connectors/composio/index.js +9 -0
  33. package/runtime/dist/src/connectors/feishu/index.js +258 -44
  34. package/runtime/dist/src/connectors/macos/mail.js +7 -3
  35. package/runtime/dist/src/connectors/macos/reader.js +3 -1
  36. package/runtime/dist/src/conversation-voice-provider.js +5 -2
  37. package/runtime/dist/src/core/causal-runtime.js +38 -3
  38. package/runtime/dist/src/core/context-view.js +7 -0
  39. package/runtime/dist/src/core/guards.js +32 -0
  40. package/runtime/dist/src/core/runtime.js +3 -0
  41. package/runtime/dist/src/core/schedule-tools.js +2 -2
  42. package/runtime/dist/src/core/source-processing-instructions.js +2 -2
  43. package/runtime/dist/src/core/source-processing-tools.js +3 -1
  44. package/runtime/dist/src/core/tool-schema.js +42 -7
  45. package/runtime/dist/src/desktop/desktop-camera.js +3 -5
  46. package/runtime/dist/src/desktop/desktop-control.js +41 -8
  47. package/runtime/dist/src/desktop/desktop-session.js +90 -19
  48. package/runtime/dist/src/desktop/desktop-wire.js +5 -7
  49. package/runtime/dist/src/desktop/startup-error.js +18 -16
  50. package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
  51. package/runtime/dist/src/desktop-entry.js +6 -2
  52. package/runtime/dist/src/desktop.js +5 -1
  53. package/runtime/dist/src/device/attempt.js +65 -0
  54. package/runtime/dist/src/device/authority.js +159 -0
  55. package/runtime/dist/src/device/gateway.js +87 -0
  56. package/runtime/dist/src/device/ledger.js +91 -0
  57. package/runtime/dist/src/device/ownership.js +92 -0
  58. package/runtime/dist/src/device/port.js +2 -0
  59. package/runtime/dist/src/device/schedule-ownership.js +103 -0
  60. package/runtime/dist/src/executors/acp/transport.js +2 -0
  61. package/runtime/dist/src/executors/browser.js +4 -3
  62. package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
  63. package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
  64. package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
  65. package/runtime/dist/src/executors/codex/common.js +1 -1
  66. package/runtime/dist/src/executors/codex/contract.js +12 -16
  67. package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
  68. package/runtime/dist/src/executors/codex/factory.js +54 -32
  69. package/runtime/dist/src/executors/codex/host-config.js +69 -20
  70. package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
  71. package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
  72. package/runtime/dist/src/executors/codex/process-owner.js +4 -6
  73. package/runtime/dist/src/executors/codex/production-host.js +33 -34
  74. package/runtime/dist/src/executors/codex/protocol.js +9 -14
  75. package/runtime/dist/src/executors/codex/session-title.js +6 -8
  76. package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
  77. package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
  78. package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
  79. package/runtime/dist/src/executors/coding/intake.js +12 -7
  80. package/runtime/dist/src/executors/computer-backend.js +18 -10
  81. package/runtime/dist/src/executors/computer-config.js +32 -0
  82. package/runtime/dist/src/executors/computer-device.js +68 -16
  83. package/runtime/dist/src/executors/computer-worker.js +18 -6
  84. package/runtime/dist/src/executors/computer.js +29 -56
  85. package/runtime/dist/src/executors/device-lock.js +14 -5
  86. package/runtime/dist/src/executors/gui-execution.js +2 -0
  87. package/runtime/dist/src/executors/index.js +0 -1
  88. package/runtime/dist/src/executors/mobile.js +9 -8
  89. package/runtime/dist/src/executors/native-process.js +4 -0
  90. package/runtime/dist/src/executors/search.js +3 -5
  91. package/runtime/dist/src/executors/task-resources.js +21 -0
  92. package/runtime/dist/src/executors/watcher.js +2 -4
  93. package/runtime/dist/src/experience/host.js +179 -0
  94. package/runtime/dist/src/index.js +2 -0
  95. package/runtime/dist/src/knowledge/assembly.js +3 -4
  96. package/runtime/dist/src/knowledge/embeddings.js +50 -34
  97. package/runtime/dist/src/knowledge/service.js +1 -0
  98. package/runtime/dist/src/knowledge/store-client.js +1 -6
  99. package/runtime/dist/src/knowledge/store-worker.js +1 -3
  100. package/runtime/dist/src/mem0/resource.js +25 -0
  101. package/runtime/dist/src/mem0/store-worker.js +234 -21
  102. package/runtime/dist/src/memory/consumer.js +31 -0
  103. package/runtime/dist/src/memory/engine-worker.js +210 -0
  104. package/runtime/dist/src/memory/entry.js +8 -1
  105. package/runtime/dist/src/memory/explicit-memory.js +20 -0
  106. package/runtime/dist/src/memory/factory.js +30 -15
  107. package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
  108. package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
  109. package/runtime/dist/src/memory/prerecall-port.js +27 -0
  110. package/runtime/dist/src/memory/prerecall.js +1 -1
  111. package/runtime/dist/src/memory/production-engine.js +151 -0
  112. package/runtime/dist/src/memory/provenance.js +1 -0
  113. package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
  114. package/runtime/dist/src/memory/retrieval.js +107 -22
  115. package/runtime/dist/src/memory/sensitivity.js +6 -2
  116. package/runtime/dist/src/memory/source-retrieval.js +11 -0
  117. package/runtime/dist/src/memory/tool-capabilities.js +46 -0
  118. package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
  119. package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
  120. package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
  121. package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
  122. package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
  123. package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
  124. package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
  125. package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
  126. package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
  127. package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
  128. package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
  129. package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
  130. package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
  131. package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
  132. package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
  133. package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
  134. package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
  135. package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
  136. package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
  137. package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
  138. package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
  139. package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
  140. package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
  141. package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
  142. package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
  143. package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
  144. package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
  145. package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
  146. package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
  147. package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
  148. package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
  149. package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
  150. package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
  151. package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
  152. package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
  153. package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
  154. package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
  155. package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
  156. package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
  157. package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
  158. package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
  159. package/runtime/dist/src/memory-ledger/store-client.js +235 -37
  160. package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
  161. package/runtime/dist/src/memory-ledger/store.js +91 -1
  162. package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
  163. package/runtime/dist/src/memory-substrate/diary.js +27 -0
  164. package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
  165. package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
  166. package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
  167. package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
  168. package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
  169. package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
  170. package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
  171. package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
  172. package/runtime/dist/src/memory-substrate/migration.js +2 -0
  173. package/runtime/dist/src/memory-substrate/purge.js +12 -2
  174. package/runtime/dist/src/memory-substrate/resource.js +514 -129
  175. package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
  176. package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
  177. package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
  178. package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
  179. package/runtime/dist/src/memory-substrate/source-state.js +8 -0
  180. package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
  181. package/runtime/dist/src/memory-substrate/store.js +125 -23
  182. package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
  183. package/runtime/dist/src/model/goal-writer.js +80 -0
  184. package/runtime/dist/src/model/jev-client.js +24 -13
  185. package/runtime/dist/src/model/model-adapters.js +2 -3
  186. package/runtime/dist/src/model/model-catalog.js +80 -0
  187. package/runtime/dist/src/model/model-gateway.js +47 -18
  188. package/runtime/dist/src/model/model-purpose.js +3 -4
  189. package/runtime/dist/src/model/personal-writer.js +536 -44
  190. package/runtime/dist/src/model/proactivity.js +50 -6
  191. package/runtime/dist/src/model/responses-model-gateway.js +59 -0
  192. package/runtime/dist/src/model/task-verifier.js +3 -3
  193. package/runtime/dist/src/model/timeline-anchors.js +77 -0
  194. package/runtime/dist/src/model/timeline-perspective.js +13 -0
  195. package/runtime/dist/src/model/timeline-selection.js +182 -0
  196. package/runtime/dist/src/model/understanding-writer.js +27 -0
  197. package/runtime/dist/src/model/vision-capability.js +3 -1
  198. package/runtime/dist/src/model/workbench-writer.js +96 -0
  199. package/runtime/dist/src/news/feeds.js +6 -10
  200. package/runtime/dist/src/news/interests.js +23 -0
  201. package/runtime/dist/src/news/service.js +87 -31
  202. package/runtime/dist/src/news/sources.json +116 -0
  203. package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
  204. package/runtime/dist/src/notifications/content.js +41 -0
  205. package/runtime/dist/src/notifications/contracts.js +4 -2
  206. package/runtime/dist/src/notifications/feed.js +6 -2
  207. package/runtime/dist/src/notifications/service.js +27 -14
  208. package/runtime/dist/src/notifications/store.js +3 -1
  209. package/runtime/dist/src/personal-agent/app-context.js +39 -4
  210. package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
  211. package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
  212. package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
  213. package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
  214. package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
  215. package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
  216. package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
  217. package/runtime/dist/src/personal-agent/contracts.js +24 -4
  218. package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
  219. package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
  220. package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
  221. package/runtime/dist/src/personal-agent/conversations.js +71 -15
  222. package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
  223. package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
  224. package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
  225. package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2379 -223
  227. package/runtime/dist/src/personal-agent/identity-context.js +33 -0
  228. package/runtime/dist/src/personal-agent/life.js +129 -11
  229. package/runtime/dist/src/personal-agent/local-shell.js +181 -0
  230. package/runtime/dist/src/personal-agent/local-tools.js +234 -0
  231. package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
  232. package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
  233. package/runtime/dist/src/personal-agent/project-digests.js +7 -3
  234. package/runtime/dist/src/personal-agent/project-history.js +36 -0
  235. package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
  236. package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
  237. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
  238. package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
  239. package/runtime/dist/src/personal-agent/sources.js +9 -1
  240. package/runtime/dist/src/personal-agent/store.js +124 -14
  241. package/runtime/dist/src/personal-agent/task-loop.js +3 -0
  242. package/runtime/dist/src/personal-agent/tasks.js +16 -4
  243. package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
  244. package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
  245. package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
  246. package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
  247. package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
  248. package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
  249. package/runtime/dist/src/personal-agent/understanding.js +7 -22
  250. package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
  251. package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
  252. package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
  253. package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
  254. package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
  255. package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
  256. package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
  257. package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +10 -8
  259. package/runtime/dist/src/projects/project-store.js +36 -4
  260. package/runtime/dist/src/realtime/bridge.js +77 -8
  261. package/runtime/dist/src/realtime/capabilities.js +19 -0
  262. package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
  263. package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
  264. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
  265. package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
  266. package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
  267. package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
  268. package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
  269. package/runtime/dist/src/realtime/evidence.js +1 -1
  270. package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
  271. package/runtime/dist/src/realtime/gemini.js +14 -3
  272. package/runtime/dist/src/realtime/host-delivery.js +37 -4
  273. package/runtime/dist/src/realtime/protocol.js +18 -3
  274. package/runtime/dist/src/realtime/provider-projection.js +4 -1
  275. package/runtime/dist/src/realtime/provider-session.js +73 -16
  276. package/runtime/dist/src/realtime/qwen-transport.js +35 -4
  277. package/runtime/dist/src/realtime/qwen.js +144 -9
  278. package/runtime/dist/src/realtime/service-state.js +0 -1
  279. package/runtime/dist/src/realtime/service.js +93 -7
  280. package/runtime/dist/src/realtime/session.js +39 -32
  281. package/runtime/dist/src/realtime/sglang-native.js +214 -0
  282. package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
  283. package/runtime/dist/src/realtime/telemetry.js +6 -3
  284. package/runtime/dist/src/realtime/tool-continuations.js +84 -7
  285. package/runtime/dist/src/realtime/transport.js +17 -0
  286. package/runtime/dist/src/realtime/usage.js +33 -17
  287. package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
  288. package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
  289. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
  290. package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
  291. package/runtime/dist/src/server/aoq-chat-server.js +1 -1
  292. package/runtime/dist/src/server/client-server.js +21 -0
  293. package/runtime/dist/src/server-entry.js +3 -0
  294. package/runtime/dist/src/space-host/admin-socket.js +115 -0
  295. package/runtime/dist/src/space-host/audio-owner.js +44 -0
  296. package/runtime/dist/src/space-host/cli.js +195 -0
  297. package/runtime/dist/src/space-host/config.js +247 -0
  298. package/runtime/dist/src/space-host/context-input.js +12 -0
  299. package/runtime/dist/src/space-host/contracts.js +10 -0
  300. package/runtime/dist/src/space-host/host-admin.js +114 -0
  301. package/runtime/dist/src/space-host/key-delivery.js +28 -0
  302. package/runtime/dist/src/space-host/mobile-tools.js +9 -0
  303. package/runtime/dist/src/space-host/model-settings.js +213 -0
  304. package/runtime/dist/src/space-host/projection.js +37 -0
  305. package/runtime/dist/src/space-host/push.js +137 -0
  306. package/runtime/dist/src/space-host/relay-transport.js +55 -0
  307. package/runtime/dist/src/space-host/service.js +841 -0
  308. package/runtime/dist/src/space-host/voice-crypto.js +240 -0
  309. package/runtime/dist/src/space-host/voice.js +600 -0
  310. package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
  311. package/runtime/dist/src/storage/private-database.js +7 -10
  312. package/runtime/dist/src/text/unicode-normalize.js +5 -1
  313. package/runtime/dist/src/understanding/candidates.js +8 -10
  314. package/runtime/dist/src/understanding/fixture.js +1 -1
  315. package/runtime/dist/src/understanding/pipeline.js +4 -4
  316. package/runtime/dist/src/usage/context.js +23 -0
  317. package/runtime/dist/src/usage/index.js +4 -0
  318. package/runtime/dist/src/usage/ledger-worker.js +90 -0
  319. package/runtime/dist/src/usage/ledger.js +74 -0
  320. package/runtime/dist/src/usage/model-call.js +63 -0
  321. package/runtime/dist/src/usage/pricing.js +68 -0
  322. package/runtime/dist/src/usage/summary.js +69 -0
  323. package/runtime/dist/src/voicemem/store-client.js +104 -21
  324. package/runtime/dist/src/voicemem/store-worker.js +5 -8
  325. package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
  326. package/src/command.mjs +8 -1
  327. package/runtime/dist/src/executors/autoglm.js +0 -376
@@ -0,0 +1,304 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ /** Quote-aware split into simple commands. `$(...)` and backticks come back as separate sub-commands. */
4
+ function scan(source) {
5
+ const segments = [], subs = [];
6
+ let seg = [], text = '', has = false, dynamic = false;
7
+ const flush = () => { if (has)
8
+ seg.push({ text, dynamic }); text = ''; has = false; dynamic = false; };
9
+ const cut = () => { flush(); if (seg.length)
10
+ segments.push(seg); seg = []; };
11
+ const group = (from) => { let depth = 1, j = from; for (; j < source.length; j++) {
12
+ const c = source[j];
13
+ if (c === '\\') {
14
+ j++;
15
+ continue;
16
+ }
17
+ if (c === '(')
18
+ depth++;
19
+ else if (c === ')' && --depth === 0)
20
+ break;
21
+ } return j; };
22
+ const substitution = (i) => {
23
+ if (source[i] === '`') {
24
+ const end = source.indexOf('`', i + 1), stop = end < 0 ? source.length : end;
25
+ subs.push(source.slice(i + 1, stop));
26
+ return stop;
27
+ }
28
+ const end = group(i + 2);
29
+ subs.push(source.slice(i + 2, end));
30
+ return end;
31
+ };
32
+ for (let i = 0; i < source.length; i++) {
33
+ const c = source[i];
34
+ if (c === '\\') {
35
+ if (source[i + 1] === '\n') {
36
+ i++;
37
+ continue;
38
+ }
39
+ text += source[++i] ?? '';
40
+ has = true;
41
+ continue;
42
+ }
43
+ if (c === "'") {
44
+ const end = source.indexOf("'", i + 1), stop = end < 0 ? source.length : end;
45
+ text += source.slice(i + 1, stop);
46
+ has = true;
47
+ i = stop;
48
+ continue;
49
+ }
50
+ if (c === '"') {
51
+ has = true;
52
+ for (i++; i < source.length && source[i] !== '"'; i++) {
53
+ const d = source[i];
54
+ if (d === '\\') {
55
+ text += source[++i] ?? '';
56
+ continue;
57
+ }
58
+ if (d === '`' || (d === '$' && source[i + 1] === '(')) {
59
+ i = substitution(i);
60
+ dynamic = true;
61
+ text += '$';
62
+ continue;
63
+ }
64
+ if (d === '$')
65
+ dynamic = true;
66
+ text += d;
67
+ }
68
+ continue;
69
+ }
70
+ if (c === '`' || (c === '$' && source[i + 1] === '(')) {
71
+ i = substitution(i);
72
+ dynamic = true;
73
+ has = true;
74
+ text += '$';
75
+ continue;
76
+ }
77
+ if (c === '$') {
78
+ dynamic = true;
79
+ has = true;
80
+ text += c;
81
+ continue;
82
+ }
83
+ if (c === '#' && !has) {
84
+ const nl = source.indexOf('\n', i);
85
+ if (nl < 0)
86
+ break;
87
+ i = nl - 1;
88
+ continue;
89
+ }
90
+ if (c === ' ' || c === '\t' || c === '\r') {
91
+ flush();
92
+ continue;
93
+ }
94
+ if (c === ';' || c === '\n' || c === '(' || c === ')' || c === '|') {
95
+ cut();
96
+ continue;
97
+ }
98
+ if (c === '&') {
99
+ if (source[i + 1] === '>') {
100
+ flush();
101
+ seg.push({ text: '>', dynamic: false, op: true });
102
+ i += source[i + 2] === '>' ? 2 : 1;
103
+ continue;
104
+ }
105
+ if (source[i - 1] === '>' && seg.at(-1)?.op) {
106
+ seg.at(-1).text = '>&';
107
+ continue;
108
+ }
109
+ cut();
110
+ continue;
111
+ }
112
+ if (c === '>' || c === '<') {
113
+ if (has && !dynamic && /^\d+$/u.test(text)) {
114
+ text = '';
115
+ has = false;
116
+ }
117
+ else
118
+ flush();
119
+ let op = c;
120
+ if (source[i + 1] === c) {
121
+ op += c;
122
+ i++;
123
+ if (c === '<' && source[i + 1] === '<') {
124
+ op = '<<<';
125
+ i++;
126
+ }
127
+ }
128
+ else if (c === '>' && source[i + 1] === '|') {
129
+ op = '>|';
130
+ i++;
131
+ }
132
+ seg.push({ text: op, dynamic: false, op: true });
133
+ continue;
134
+ }
135
+ text += c;
136
+ has = true;
137
+ }
138
+ cut();
139
+ return { segments, subs };
140
+ }
141
+ const WRAPPERS = new Set(['sudo', 'env', 'time', 'nohup', 'command', 'exec', 'nice', 'builtin']);
142
+ const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', '{', '}', '!', 'esac']);
143
+ const SKIPPED = new Set(['for', 'case', 'select', 'function']);
144
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish']);
145
+ const AMBIGUOUS = new Set(['eval', 'source', '.', 'xargs']);
146
+ const TRIVIAL = new Set(['echo', 'printf', 'true', 'false', ':', 'test', '[', '[[', 'sleep', 'pwd', 'export', 'set', 'unset', 'alias', 'read', 'wait', 'exit', 'return', 'type', 'which', 'date', 'umask']);
147
+ const SUBCOMMANDS = new Set(['git', 'npm', 'pnpm', 'yarn', 'docker', 'brew', 'pip', 'pip3', 'cargo', 'kubectl', 'gh', 'go', 'dotnet']);
148
+ const WRITE_ALL = new Set(['rm', 'rmdir', 'mv', 'touch', 'mkdir', 'ln', 'tee', 'truncate', 'chmod', 'chown', 'unlink', 'shred']);
149
+ const WRITE_LAST = new Set(['cp', 'install', 'rsync', 'scp']);
150
+ const SKIP_FIRST = new Set(['chmod', 'chown', 'truncate']);
151
+ const READERS = new Set(['cat', 'head', 'tail', 'less', 'more', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'ls', 'tree', 'wc', 'stat', 'file', 'du', 'diff', 'sort', 'uniq', 'awk', 'sed', 'cut', 'strings', 'xxd', 'od', 'hexdump', 'bat', 'tac', 'nl', 'realpath', 'readlink']);
152
+ const PATTERN_FIRST = new Set(['grep', 'egrep', 'fgrep', 'rg', 'ag', 'awk', 'sed']);
153
+ /**
154
+ * Approval classes of one shell command: one per constituent plus the file effects it can be proven to have.
155
+ * Anything that cannot be analysed statically yields `shell:*`, which conservatively matches any denied shell class.
156
+ */
157
+ export function shellClasses(command, cwd, project) {
158
+ const out = new Set(), trivial = [], home = homedir();
159
+ let ambiguous = false;
160
+ const abs = (path, base) => resolve(base, path === '~' ? home : path.startsWith('~/') ? join(home, path.slice(2)) : path);
161
+ const inside = (path) => { const rel = relative(project, path); return !rel.startsWith('..') && !isAbsolute(rel); };
162
+ const root = (path) => inside(path) ? 'rel:' + (relative(project, path).split(sep).slice(0, 2).join('/') || '.') : 'abs:' + path.split(sep).filter(Boolean).slice(0, 2).join('/');
163
+ const write = (path) => { out.add((inside(path) ? 'file-write:' : 'file-write-outside:') + path); };
164
+ const read = (path) => { if (!inside(path))
165
+ out.add('file-read-outside:' + path); };
166
+ const analyze = (text, start, depth) => {
167
+ if (depth > 3) {
168
+ ambiguous = true;
169
+ return;
170
+ }
171
+ let dir = start;
172
+ const { segments, subs } = scan(text);
173
+ for (const sub of subs)
174
+ analyze(sub, dir, depth + 1);
175
+ for (const segment of segments) {
176
+ let words = [];
177
+ for (let k = 0; k < segment.length; k++) {
178
+ const token = segment[k];
179
+ if (!token.op) {
180
+ words.push(token);
181
+ continue;
182
+ }
183
+ const target = segment[++k];
184
+ if (!target || token.text === '<<' || token.text === '<<<')
185
+ continue;
186
+ if (token.text === '>&' && (/^\d+$/u.test(target.text) || target.text === '-'))
187
+ continue;
188
+ if (target.dynamic) {
189
+ ambiguous = true;
190
+ continue;
191
+ }
192
+ const path = abs(target.text, dir);
193
+ if (token.text === '<')
194
+ read(path);
195
+ else if (target.text !== '/dev/null')
196
+ write(path);
197
+ }
198
+ while (words.length) {
199
+ const word = words[0], base = word.text.replace(/^.*[\\/]/u, '').toLowerCase();
200
+ if (!word.dynamic && /^[A-Za-z_][A-Za-z0-9_]*=/u.test(word.text) || KEYWORDS.has(word.text))
201
+ words.shift();
202
+ else if (SKIPPED.has(base)) {
203
+ words = [];
204
+ break;
205
+ }
206
+ else if (WRAPPERS.has(base)) {
207
+ words.shift();
208
+ while (words[0]?.text.startsWith('-'))
209
+ words.shift();
210
+ }
211
+ else
212
+ break;
213
+ }
214
+ const name = words[0];
215
+ if (!name)
216
+ continue;
217
+ if (name.dynamic) {
218
+ ambiguous = true;
219
+ continue;
220
+ }
221
+ const base = name.text.replace(/^.*[\\/]/u, '').toLowerCase(), args = words.slice(1);
222
+ if (base === 'cd' || base === 'pushd') {
223
+ const target = args.find(arg => !arg.text.startsWith('-') || arg.text === '-');
224
+ if (!target)
225
+ dir = home;
226
+ else if (target.dynamic || target.text === '-')
227
+ ambiguous = true;
228
+ else
229
+ dir = abs(target.text, dir);
230
+ continue;
231
+ }
232
+ if (base === 'popd')
233
+ continue;
234
+ if (AMBIGUOUS.has(base)) {
235
+ ambiguous = true;
236
+ continue;
237
+ }
238
+ if (SHELLS.has(base)) {
239
+ const index = args.findIndex(arg => /^-[a-z]*c[a-z]*$/u.test(arg.text));
240
+ if (index >= 0) {
241
+ const inner = args[index + 1];
242
+ if (!inner || inner.dynamic || /[$`]/u.test(inner.text))
243
+ ambiguous = true;
244
+ else
245
+ analyze(inner.text, dir, depth + 1);
246
+ continue;
247
+ }
248
+ }
249
+ const positional = args.filter(arg => !arg.text.startsWith('-')), statics = positional.filter(arg => !arg.dynamic);
250
+ const sub = SUBCOMMANDS.has(base) && args[0] && !args[0].text.startsWith('-') ? ' ' + args[0].text.toLowerCase() : '';
251
+ let operands = positional;
252
+ if (SKIP_FIRST.has(base))
253
+ operands = operands.slice(1);
254
+ if (base === 'find') {
255
+ const paths = args.slice(0, Math.max(0, args.findIndex(arg => /^[-!(]/u.test(arg.text)) < 0 ? args.length : args.findIndex(arg => /^[-!(]/u.test(arg.text))));
256
+ const flags = args.map(arg => arg.text);
257
+ if (flags.some(flag => ['-exec', '-execdir', '-ok', '-okdir'].includes(flag)))
258
+ ambiguous = true;
259
+ for (const path of paths.filter(arg => !arg.dynamic)) {
260
+ read(abs(path.text, dir));
261
+ if (flags.includes('-delete'))
262
+ write(abs(path.text, dir));
263
+ }
264
+ if (flags.includes('-delete') && paths.some(arg => arg.dynamic))
265
+ ambiguous = true;
266
+ }
267
+ else if (WRITE_ALL.has(base) || WRITE_LAST.has(base) || (base === 'sed' && args.some(arg => /^(-[a-z]*i|--in-place)/u.test(arg.text)))) {
268
+ if (base === 'sed')
269
+ operands = operands.slice(1);
270
+ const targets = WRITE_LAST.has(base) ? operands.slice(-1) : operands;
271
+ for (const target of targets) {
272
+ if (target.dynamic || /[*?[{]/u.test(target.text))
273
+ ambiguous = true;
274
+ else
275
+ write(abs(target.text, dir));
276
+ }
277
+ if (WRITE_LAST.has(base) || base === 'mv')
278
+ for (const source of operands.slice(0, WRITE_LAST.has(base) ? -1 : undefined)) {
279
+ if (!source.dynamic)
280
+ read(abs(source.text, dir));
281
+ }
282
+ }
283
+ else if (READERS.has(base)) {
284
+ for (const target of (PATTERN_FIRST.has(base) ? operands.slice(1) : operands).filter(arg => !arg.dynamic))
285
+ read(abs(target.text, dir));
286
+ }
287
+ const pathy = WRITE_ALL.has(base) || WRITE_LAST.has(base) || READERS.has(base), roots = (pathy ? operands.filter(arg => !arg.dynamic) : statics.filter(arg => /^[./~]/u.test(arg.text) || arg.text.includes('/'))).map(arg => root(abs(arg.text, dir)));
288
+ if (!inside(dir))
289
+ roots.push(root(dir));
290
+ const klass = 'shell:' + base + sub + (roots.length ? '@' + [...new Set(roots)].sort().slice(0, 3).join('+') : '');
291
+ if (TRIVIAL.has(base))
292
+ trivial.push(klass);
293
+ else
294
+ out.add(klass);
295
+ }
296
+ };
297
+ analyze(command, cwd ? abs(cwd, project) : project, 0);
298
+ if (ambiguous)
299
+ out.add('shell:*');
300
+ if (![...out].some(klass => klass.startsWith('shell:')))
301
+ out.add(trivial[0] ?? 'shell:');
302
+ return [...out].slice(0, 64);
303
+ }
304
+ //# sourceMappingURL=workbench-shell-class.js.map
@@ -0,0 +1,292 @@
1
+ import { contextDependenciesSchema } from './context-dependencies.js';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { mkdir, open, rename, unlink } from 'node:fs/promises';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { resizeBase64ImageToJpeg, convertImgBufferToJpeg } from '@midscene/shared/img';
7
+ import { jsonValueSchema } from '../core/events.js';
8
+ import { validateToolImage } from '../realtime/cascaded/llm.js';
9
+ import { computerApplicationSchema } from './computer-use/contract.js';
10
+ export const planSchema = z.object({ context_dependencies: contextDependenciesSchema.optional(), id: z.string(), version: z.number().int().positive(), title: z.string().min(1).max(120), content: z.string().min(1).max(131072), conversation_id: z.string(), generation: z.number().int().nonnegative(), created_at: z.string(), publication_key: z.string().optional() }).strict();
11
+ export const buildStatusSchema = z.enum(['idle', 'running', 'awaiting_approval', 'paused', 'completed', 'failed', 'outcome_unknown', 'finished']);
12
+ export const MAX_WORKBENCH_THOUGHTS = 64;
13
+ export const MAX_WORKBENCH_THOUGHT_CODEPOINTS = 8000;
14
+ export const MAX_WORKBENCH_THOUGHT_BYTES = 256 * 1024;
15
+ const thoughtSchema = z.object({ id: z.string().min(1), text: z.string(), created_at: z.string(), message_id: z.string().optional() }).strict();
16
+ /** Newest 64 bounded thoughts within 256 KiB; the oldest entries are discarded first. */
17
+ export function boundWorkbenchThoughts(thoughts) {
18
+ const kept = [];
19
+ let bytes = 0;
20
+ for (const thought of [...thoughts].reverse()) {
21
+ if (kept.length >= MAX_WORKBENCH_THOUGHTS)
22
+ break;
23
+ const text = [...thought.text].slice(0, MAX_WORKBENCH_THOUGHT_CODEPOINTS).join('');
24
+ const item = { id: thought.id, text, created_at: thought.created_at, ...(thought.message_id === undefined ? {} : { message_id: thought.message_id }) };
25
+ const size = Buffer.byteLength(JSON.stringify(item));
26
+ if (kept.length > 0 && bytes + size > MAX_WORKBENCH_THOUGHT_BYTES)
27
+ break;
28
+ kept.unshift(item);
29
+ bytes += size;
30
+ }
31
+ return kept;
32
+ }
33
+ const callSchema = z.object({ id: z.string().min(1), name: z.string().min(1), arguments: z.record(z.string(), jsonValueSchema), state: z.enum(['prepared', 'awaiting_approval', 'running', 'completed']), result: jsonValueSchema.optional(), message_id: z.string().optional(), narration: z.string().max(32001).optional(), created_at: z.string().optional(), approval_id: z.string().optional(), started_at: z.string().optional(), finished_at: z.string().optional(), process: z.object({ platform: z.enum(['darwin', 'win32']), pid: z.number().int().positive() }).strict().optional() }).strict();
34
+ const inputSchema = z.union([
35
+ z.object({ kind: z.literal('user_text'), text: z.string() }).strict(),
36
+ z.object({ kind: z.enum(['host_context', 'host_task', 'host_activation', 'packed_history']), content: z.string() }).strict(),
37
+ z.object({ kind: z.literal('tool_result'), call_id: z.string(), output: jsonValueSchema, images: z.array(z.custom(value => { try {
38
+ validateToolImage(value);
39
+ return true;
40
+ }
41
+ catch {
42
+ return false;
43
+ } })).optional() }).strict(),
44
+ ]);
45
+ export function emptyWorkbenchCheckpoint(conversation_id, generation) { return { version: 1, conversation_id, generation, run_version: 0, status: 'idle', reason: null, model: null, inputs: [], pending_calls: [], calls: [], thoughts: [], last_user: '', assistant: '', updated_at: new Date().toISOString() }; }
46
+ /** Durable private state is separate from the bounded UI transcript. Never stores model credentials. */
47
+ const storeOperations = new Map();
48
+ export class WorkbenchStore {
49
+ root;
50
+ constructor(root) {
51
+ this.root = root;
52
+ }
53
+ async computerApplicationAllowed(application) {
54
+ const app = computerApplicationSchema.parse(application), key = JSON.stringify([app.bundleId, app.path]);
55
+ const saved = await this.#read(this.#file('computer-app-consent', key), 8192);
56
+ return saved !== null && JSON.stringify(saved) === JSON.stringify({ bundleId: app.bundleId, path: app.path, allowed: true });
57
+ }
58
+ async allowComputerApplication(application) {
59
+ const app = computerApplicationSchema.parse(application), key = JSON.stringify([app.bundleId, app.path]);
60
+ await this.#write(this.#file('computer-app-consent', key), { bundleId: app.bundleId, path: app.path, allowed: true });
61
+ }
62
+ #file(kind, id) { return join(this.root, kind + '-' + createHash('sha256').update(id).digest('hex') + '.json'); }
63
+ async #io(path, operation) {
64
+ const key = process.platform === 'win32' ? resolve(path).toLowerCase() : resolve(path);
65
+ const pending = (storeOperations.get(key) ?? Promise.resolve()).then(operation), tail = pending.then(() => { }, () => { });
66
+ storeOperations.set(key, tail);
67
+ try {
68
+ return await pending;
69
+ }
70
+ finally {
71
+ if (storeOperations.get(key) === tail)
72
+ storeOperations.delete(key);
73
+ }
74
+ }
75
+ async #read(path, maxBytes = 64 * 1024 * 1024) { return this.#io(path, async () => { try {
76
+ const file = await open(path, 'r');
77
+ try {
78
+ if ((await file.stat()).size > maxBytes)
79
+ throw Error('workbench_store_capacity');
80
+ return JSON.parse(await file.readFile('utf8'));
81
+ }
82
+ finally {
83
+ await file.close();
84
+ }
85
+ }
86
+ catch (error) {
87
+ if (error.code === 'ENOENT')
88
+ return null;
89
+ throw error;
90
+ } }); }
91
+ #write(path, value) {
92
+ // Capture before queuing: later tool completions must not rewrite an earlier receipt.
93
+ return this.#writeBytes(path, JSON.stringify(value));
94
+ }
95
+ #writeBytes(path, content) {
96
+ return this.#io(path, async () => {
97
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
98
+ const temporary = path + '.' + randomUUID() + '.tmp', file = await open(temporary, 'wx', 0o600);
99
+ try {
100
+ await file.writeFile(content);
101
+ await file.sync();
102
+ await file.close();
103
+ await rename(temporary, path);
104
+ if (process.platform !== 'win32') {
105
+ const folder = await open(dirname(path), 'r');
106
+ try {
107
+ await folder.sync();
108
+ }
109
+ finally {
110
+ await folder.close();
111
+ }
112
+ }
113
+ }
114
+ finally {
115
+ await file.close().catch(() => { });
116
+ await unlink(temporary).catch(() => { });
117
+ }
118
+ });
119
+ }
120
+ #imagePath(id, generation, ref) {
121
+ if (!/^[a-f0-9]{64}\.(png|jpeg)$/u.test(ref))
122
+ throw Error('invalid_image_ref');
123
+ return join(this.root, 'images-' + createHash('sha256').update(id + ':' + generation).digest('hex'), ref);
124
+ }
125
+ async saveImage(id, generation, image) {
126
+ validateToolImage(image);
127
+ const bytes = Buffer.from(image.data_base64, 'base64'), ref = createHash('sha256').update(bytes).update(JSON.stringify({ ...image, data_base64: '' })).digest('hex') + '.' + (image.media_type === 'image/png' ? 'png' : 'jpeg');
128
+ const path = this.#imagePath(id, generation, ref);
129
+ await this.#writeBytes(path, bytes);
130
+ await this.#write(path + '.json', { media_type: image.media_type, width: image.width, height: image.height, captured_at: image.captured_at });
131
+ return ref;
132
+ }
133
+ async loadImage(id, generation, ref) {
134
+ const path = this.#imagePath(id, generation, ref), metadata = await this.#read(path + '.json', 4096);
135
+ const file = await open(path, 'r');
136
+ try {
137
+ if ((await file.stat()).size > 16 * 1024 * 1024)
138
+ throw Error('workbench_image_capacity');
139
+ return validateToolImage({ ...metadata, data_base64: (await file.readFile()).toString('base64') });
140
+ }
141
+ finally {
142
+ await file.close();
143
+ }
144
+ }
145
+ async thumbnail(id, generation, ref) {
146
+ const image = await this.loadImage(id, generation, ref), scale = Math.min(1, 480 / Math.max(image.width, image.height));
147
+ const width = Math.max(1, Math.round(image.width * scale)), height = Math.max(1, Math.round(image.height * scale));
148
+ const resized = await resizeBase64ImageToJpeg('data:' + image.media_type + ';base64,' + image.data_base64, { sourceSize: { width: image.width, height: image.height }, targetSize: { width, height }, jpegQuality: 60 });
149
+ // Re-encode even unchanged JPEGs to strip oversized source metadata.
150
+ const bytes = await convertImgBufferToJpeg(Buffer.from(resized.slice(resized.indexOf(',') + 1), 'base64'), 60);
151
+ const thumbnail = { media_type: 'image/jpeg', data_base64: bytes.toString('base64'), width, height, captured_at: image.captured_at };
152
+ if (Buffer.byteLength(JSON.stringify(thumbnail)) > 200_000)
153
+ throw Error('workbench_thumbnail_capacity');
154
+ return thumbnail;
155
+ }
156
+ async #images(value, id, generation, restore) {
157
+ if (Array.isArray(value))
158
+ return Promise.all(value.map(item => this.#images(item, id, generation, restore)));
159
+ if (value === null || typeof value !== 'object')
160
+ return value;
161
+ const item = value;
162
+ if (restore && typeof item.workbench_image_ref === 'string') {
163
+ const image = await this.loadImage(id, generation, item.workbench_image_ref);
164
+ return item.encoding === 'data_url' ? 'data:' + image.media_type + ';base64,' + image.data_base64 : image;
165
+ }
166
+ if (!restore && typeof item.data_base64 === 'string' && (item.media_type === 'image/png' || item.media_type === 'image/jpeg') && typeof item.width === 'number' && typeof item.height === 'number' && typeof item.captured_at === 'string') {
167
+ return { workbench_image_ref: await this.saveImage(id, generation, item), encoding: 'tool_image' };
168
+ }
169
+ const entries = await Promise.all(Object.entries(item).map(async ([key, entry]) => {
170
+ if (!restore && (key === 'url' || key === 'image_url') && typeof entry === 'string' && /^data:image\/(png|jpeg);base64,/u.test(entry)) {
171
+ const [prefix, data_base64] = entry.split(',');
172
+ const image = { media_type: prefix.includes('png') ? 'image/png' : 'image/jpeg', data_base64: data_base64, width: 1, height: 1, captured_at: '1970-01-01T00:00:00Z' };
173
+ return [key, { workbench_image_ref: await this.saveImage(id, generation, image), encoding: 'data_url' }];
174
+ }
175
+ return [key, await this.#images(entry, id, generation, restore)];
176
+ }));
177
+ return Object.fromEntries(entries);
178
+ }
179
+ async plan(id, version) { const value = planSchema.parse(await this.#read(this.#file('plan', id + ':' + version))); if (value.id !== id || value.version !== version)
180
+ throw Error('plan_version_conflict'); return value; }
181
+ async savePlan(plan) { await this.#write(this.#file('plan', plan.id + ':' + plan.version), planSchema.parse(plan)); }
182
+ #readCheckpoint(id, generation) {
183
+ const path = this.#file('build', id + ':' + generation);
184
+ return this.#io(path + ':images', () => this.#read(path));
185
+ }
186
+ async checkpointStatus(id, generation) {
187
+ const value = await this.#readCheckpoint(id, generation);
188
+ return value === null ? null : z.object({ conversation_id: z.literal(id), generation: z.literal(generation), status: buildStatusSchema, reason: z.string().nullable() }).parse(value);
189
+ }
190
+ async checkpoint(id, generation) {
191
+ const value = await this.#images(await this.#readCheckpoint(id, generation), id, generation, true);
192
+ if (value === null)
193
+ return emptyWorkbenchCheckpoint(id, generation);
194
+ const checked = z.object({ version: z.literal(1), conversation_id: z.literal(id), generation: z.literal(generation), context_dependencies: contextDependenciesSchema.optional(), confirmed_plan_omitted: z.boolean().optional(), run_version: z.number().int().nonnegative(), status: buildStatusSchema, reason: z.string().nullable(), model: jsonValueSchema.nullable(), inputs: z.array(inputSchema), pending_calls: z.array(callSchema), calls: z.array(callSchema), thoughts: z.array(thoughtSchema).optional(), last_user: z.string(), denied_classes: z.array(z.string().max(1100)).max(256).optional(), assistant: z.string(), updated_at: z.string(), voice_message_ids: z.array(z.string()).max(512).optional(), model_failure: z.object({ code: z.string().regex(/^[a-z_]{1,64}$/u), detail: z.string().regex(/^[a-z_]{1,64}$/u).optional(), tool_call_count: z.number().int().nonnegative().max(128).optional() }).strict().optional() }).strict().parse(value);
195
+ const calls = new Map(checked.calls.map(call => [call.id, call]));
196
+ if (calls.size !== checked.calls.length)
197
+ throw Error('duplicate_tool_call');
198
+ checked.pending_calls = checked.pending_calls.map(call => { const prior = calls.get(call.id); if (prior?.name !== call.name || JSON.stringify(prior.arguments) !== JSON.stringify(call.arguments))
199
+ throw Error('tool_call_id_conflict'); return prior; });
200
+ checked.thoughts = boundWorkbenchThoughts((checked.thoughts ?? []).map(thought => ({ id: thought.id, text: thought.text, created_at: thought.created_at, ...(thought.message_id === undefined ? {} : { message_id: thought.message_id }) })));
201
+ return checked;
202
+ }
203
+ async saveCheckpoint(checkpoint) {
204
+ const snapshot = structuredClone(checkpoint), path = this.#file('build', snapshot.conversation_id + ':' + snapshot.generation);
205
+ // Thoughts stay inside the private checkpoint; no caller-supplied size can exceed the bound.
206
+ snapshot.thoughts = boundWorkbenchThoughts(snapshot.thoughts ?? []);
207
+ await this.#io(path + ':images', async () => this.#write(path, await this.#images(snapshot, snapshot.conversation_id, snapshot.generation, false)));
208
+ }
209
+ async resetCheckpoint(id, generation) {
210
+ const previous = await this.checkpoint(id, generation);
211
+ if (previous.model !== null || previous.inputs.length)
212
+ await this.#write(this.#file('archive', id + ':' + generation + ':' + randomUUID()), await this.#images(previous, id, generation, false));
213
+ await this.saveCheckpoint(emptyWorkbenchCheckpoint(id, generation));
214
+ }
215
+ async detail(id, generation, offset = 0) { const value = JSON.stringify(await this.#readCheckpoint(id, generation) ?? emptyWorkbenchCheckpoint(id, generation), null, 2); return { text: value.slice(offset, offset + 6000), next_offset: offset + 6000 < value.length ? offset + 6000 : null }; }
216
+ async saveReply(id, generation, messageId, text) { if (Buffer.byteLength(text) > 32 * 1024 * 1024)
217
+ throw Error('workbench_reply_capacity'); await this.#write(this.#file('reply', `${id}:${generation}:${messageId}`), { conversation_id: id, generation, message_id: messageId, text }); }
218
+ async reply(id, generation, messageId, offset = 0) { const value = await this.#read(this.#file('reply', `${id}:${generation}:${messageId}`), 128 * 1024 * 1024); if (!value || typeof value !== 'object')
219
+ throw Error('workbench_reply_not_found'); const checked = z.object({ conversation_id: z.literal(id), generation: z.literal(generation), message_id: z.literal(messageId), text: z.string().max(32 * 1024 * 1024) }).strict().parse(value), size = 24000; let end = Math.min(checked.text.length, offset + size); if (end < checked.text.length && end > offset) {
220
+ const previous = checked.text.charCodeAt(end - 1), next = checked.text.charCodeAt(end);
221
+ if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff)
222
+ end--;
223
+ } return { text: checked.text.slice(offset, end), next_offset: end < checked.text.length ? end : null }; }
224
+ async calls(id, generation, offset = 0) {
225
+ const raw = await this.#readCheckpoint(id, generation), state = raw === null ? emptyWorkbenchCheckpoint(id, generation) : z.object({ calls: z.array(callSchema) }).parse(raw), items = [];
226
+ let bytes = 0, index = offset;
227
+ for (const call of state.calls.slice(offset, offset + 4)) {
228
+ const item = workbenchCallPreview(call, index), size = Buffer.byteLength(JSON.stringify(item));
229
+ if (items.length && bytes + size > 10000)
230
+ break;
231
+ items.push(item);
232
+ bytes += size;
233
+ index++;
234
+ }
235
+ return { items, total: state.calls.length, next_offset: index < state.calls.length ? index : null, generation };
236
+ }
237
+ /** Chronological display timeline: thoughts and tool calls merged, never model input. */
238
+ async steps(id, generation, offset = 0) {
239
+ const raw = await this.#readCheckpoint(id, generation);
240
+ const state = raw === null ? emptyWorkbenchCheckpoint(id, generation) : z.object({ calls: z.array(callSchema), thoughts: z.array(thoughtSchema).optional() }).parse(raw);
241
+ const thoughts = boundWorkbenchThoughts(state.thoughts ?? []);
242
+ const merged = [
243
+ ...thoughts.map(thought => ({ kind: 'thinking', id: thought.id, text: thought.text, created_at: thought.created_at, message_id: thought.message_id ?? null })),
244
+ ...state.calls.map((call, index) => ({ kind: 'tool', ...workbenchCallPreview(call, index) })),
245
+ ];
246
+ merged.sort((left, right) => { const a = left.created_at ?? '', b = right.created_at ?? ''; return a < b ? -1 : a > b ? 1 : 0; });
247
+ const items = [];
248
+ let bytes = 0, index = offset;
249
+ for (const step of merged.slice(offset, offset + 20)) {
250
+ const size = Buffer.byteLength(JSON.stringify(step));
251
+ if (items.length && bytes + size > 12000)
252
+ break;
253
+ items.push(step);
254
+ bytes += size;
255
+ index++;
256
+ }
257
+ // `first_id` catches a removed first row; `thoughts_first_id` also catches a thought
258
+ // evicted after a permanent leading tool call, which leaves `first_id` unchanged.
259
+ return { items, total: merged.length, next_offset: index < merged.length ? index : null, generation, first_id: merged[0]?.id ?? null, thoughts_first_id: thoughts[0]?.id ?? null };
260
+ }
261
+ }
262
+ function firstImageRef(value) {
263
+ if (value === null || typeof value !== 'object')
264
+ return null;
265
+ if (!Array.isArray(value)) {
266
+ const ref = value.workbench_image_ref ?? value.image_ref;
267
+ if (typeof ref === 'string' && /^[a-f0-9]{64}\.(png|jpeg)$/u.test(ref))
268
+ return ref;
269
+ }
270
+ for (const child of Object.values(value)) {
271
+ const ref = firstImageRef(child);
272
+ if (ref)
273
+ return ref;
274
+ }
275
+ return null;
276
+ }
277
+ /** Small, display-only projections. Full arguments and results remain in the private journal. */
278
+ export function workbenchCallPreview(call, sequence) {
279
+ const result = call.result && typeof call.result === 'object' && !Array.isArray(call.result) ? call.result : {};
280
+ const status = call.state === 'completed' ? typeof result.status === 'string' ? result.status : result.code ? 'failed' : result.state === 'refused' || result.accepted === false ? 'refused' : 'completed' : call.state;
281
+ const target = call.arguments.path ?? call.arguments.command;
282
+ const input = JSON.stringify(call.arguments, null, 2), output = call.result === undefined ? '' : JSON.stringify(call.result, null, 2);
283
+ return { image_ref: firstImageRef(call.result), sequence, id: call.id.slice(0, 512), name: call.name.slice(0, 128), message_id: call.message_id ?? null, state: call.state, status,
284
+ ...(call.narration ? { narration: call.narration } : {}),
285
+ ...(['file_read', 'file_write', 'file_edit'].includes(call.name) && status === 'completed'
286
+ ? { file_key: typeof result.path === 'string' && result.type !== 'directory' ? createHash('sha256').update(result.path).digest('hex') : null } : {}),
287
+ target: typeof target === 'string' ? target.slice(0, 180) : '', input: input.slice(0, 500), output: output.slice(0, 700),
288
+ input_truncated: input.length > 500, output_truncated: output.length > 700 || result.truncated === true,
289
+ exit_code: typeof result.exit_code === 'number' ? result.exit_code : null,
290
+ created_at: call.created_at ?? call.started_at ?? null, started_at: call.started_at ?? null, finished_at: call.finished_at ?? null };
291
+ }
292
+ //# sourceMappingURL=workbench-store.js.map