nova-personal-agent-server 0.4.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/LICENSE +674 -201
  2. package/README.md +12 -2
  3. package/bin/nova-space-host.mjs +4 -0
  4. package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
  5. package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
  6. package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
  7. package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
  8. package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
  9. package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
  10. package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
  11. package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
  12. package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
  13. package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
  14. package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
  15. package/node_modules/@nova-personal-agent/relay/package.json +1 -0
  16. package/package.json +13 -6
  17. package/runtime/dist/src/cascaded-text-provider.js +8 -3
  18. package/runtime/dist/src/composition/assembly.js +133 -35
  19. package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
  20. package/runtime/dist/src/composition/production-composition.js +57 -21
  21. package/runtime/dist/src/composition/realtime-assembly.js +160 -52
  22. package/runtime/dist/src/composition/soul-context.js +22 -0
  23. package/runtime/dist/src/config/capability-registry.js +48 -3
  24. package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
  25. package/runtime/dist/src/config/config.js +541 -128
  26. package/runtime/dist/src/config/credential-rotation.js +26 -0
  27. package/runtime/dist/src/config/data-root.js +764 -0
  28. package/runtime/dist/src/config/diagnostics.js +3 -1
  29. package/runtime/dist/src/config/environment-contract.js +190 -188
  30. package/runtime/dist/src/config/model-routes.js +140 -0
  31. package/runtime/dist/src/config/voice-credentials.js +55 -0
  32. package/runtime/dist/src/connectors/composio/index.js +9 -0
  33. package/runtime/dist/src/connectors/feishu/index.js +258 -44
  34. package/runtime/dist/src/connectors/macos/mail.js +7 -3
  35. package/runtime/dist/src/connectors/macos/reader.js +3 -1
  36. package/runtime/dist/src/conversation-voice-provider.js +5 -2
  37. package/runtime/dist/src/core/causal-runtime.js +38 -3
  38. package/runtime/dist/src/core/context-view.js +7 -0
  39. package/runtime/dist/src/core/guards.js +32 -0
  40. package/runtime/dist/src/core/runtime.js +3 -0
  41. package/runtime/dist/src/core/schedule-tools.js +2 -2
  42. package/runtime/dist/src/core/source-processing-instructions.js +2 -2
  43. package/runtime/dist/src/core/source-processing-tools.js +3 -1
  44. package/runtime/dist/src/core/tool-schema.js +42 -7
  45. package/runtime/dist/src/desktop/desktop-camera.js +3 -5
  46. package/runtime/dist/src/desktop/desktop-control.js +41 -8
  47. package/runtime/dist/src/desktop/desktop-session.js +90 -19
  48. package/runtime/dist/src/desktop/desktop-wire.js +5 -7
  49. package/runtime/dist/src/desktop/startup-error.js +18 -16
  50. package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
  51. package/runtime/dist/src/desktop-entry.js +6 -2
  52. package/runtime/dist/src/desktop.js +5 -1
  53. package/runtime/dist/src/device/attempt.js +65 -0
  54. package/runtime/dist/src/device/authority.js +159 -0
  55. package/runtime/dist/src/device/gateway.js +87 -0
  56. package/runtime/dist/src/device/ledger.js +91 -0
  57. package/runtime/dist/src/device/ownership.js +92 -0
  58. package/runtime/dist/src/device/port.js +2 -0
  59. package/runtime/dist/src/device/schedule-ownership.js +103 -0
  60. package/runtime/dist/src/executors/acp/transport.js +2 -0
  61. package/runtime/dist/src/executors/browser.js +4 -3
  62. package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
  63. package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
  64. package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
  65. package/runtime/dist/src/executors/codex/common.js +1 -1
  66. package/runtime/dist/src/executors/codex/contract.js +12 -16
  67. package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
  68. package/runtime/dist/src/executors/codex/factory.js +54 -32
  69. package/runtime/dist/src/executors/codex/host-config.js +69 -20
  70. package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
  71. package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
  72. package/runtime/dist/src/executors/codex/process-owner.js +4 -6
  73. package/runtime/dist/src/executors/codex/production-host.js +33 -34
  74. package/runtime/dist/src/executors/codex/protocol.js +9 -14
  75. package/runtime/dist/src/executors/codex/session-title.js +6 -8
  76. package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
  77. package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
  78. package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
  79. package/runtime/dist/src/executors/coding/intake.js +12 -7
  80. package/runtime/dist/src/executors/computer-backend.js +18 -10
  81. package/runtime/dist/src/executors/computer-config.js +32 -0
  82. package/runtime/dist/src/executors/computer-device.js +68 -16
  83. package/runtime/dist/src/executors/computer-worker.js +18 -6
  84. package/runtime/dist/src/executors/computer.js +29 -56
  85. package/runtime/dist/src/executors/device-lock.js +14 -5
  86. package/runtime/dist/src/executors/gui-execution.js +2 -0
  87. package/runtime/dist/src/executors/index.js +0 -1
  88. package/runtime/dist/src/executors/mobile.js +9 -8
  89. package/runtime/dist/src/executors/native-process.js +4 -0
  90. package/runtime/dist/src/executors/search.js +3 -5
  91. package/runtime/dist/src/executors/task-resources.js +21 -0
  92. package/runtime/dist/src/executors/watcher.js +2 -4
  93. package/runtime/dist/src/experience/host.js +179 -0
  94. package/runtime/dist/src/index.js +2 -0
  95. package/runtime/dist/src/knowledge/assembly.js +3 -4
  96. package/runtime/dist/src/knowledge/embeddings.js +50 -34
  97. package/runtime/dist/src/knowledge/service.js +1 -0
  98. package/runtime/dist/src/knowledge/store-client.js +1 -6
  99. package/runtime/dist/src/knowledge/store-worker.js +1 -3
  100. package/runtime/dist/src/mem0/resource.js +25 -0
  101. package/runtime/dist/src/mem0/store-worker.js +234 -21
  102. package/runtime/dist/src/memory/consumer.js +31 -0
  103. package/runtime/dist/src/memory/engine-worker.js +210 -0
  104. package/runtime/dist/src/memory/entry.js +8 -1
  105. package/runtime/dist/src/memory/explicit-memory.js +20 -0
  106. package/runtime/dist/src/memory/factory.js +30 -15
  107. package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
  108. package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
  109. package/runtime/dist/src/memory/prerecall-port.js +27 -0
  110. package/runtime/dist/src/memory/prerecall.js +1 -1
  111. package/runtime/dist/src/memory/production-engine.js +151 -0
  112. package/runtime/dist/src/memory/provenance.js +1 -0
  113. package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
  114. package/runtime/dist/src/memory/retrieval.js +107 -22
  115. package/runtime/dist/src/memory/sensitivity.js +6 -2
  116. package/runtime/dist/src/memory/source-retrieval.js +11 -0
  117. package/runtime/dist/src/memory/tool-capabilities.js +46 -0
  118. package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
  119. package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
  120. package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
  121. package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
  122. package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
  123. package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
  124. package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
  125. package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
  126. package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
  127. package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
  128. package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
  129. package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
  130. package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
  131. package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
  132. package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
  133. package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
  134. package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
  135. package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
  136. package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
  137. package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
  138. package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
  139. package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
  140. package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
  141. package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
  142. package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
  143. package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
  144. package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
  145. package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
  146. package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
  147. package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
  148. package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
  149. package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
  150. package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
  151. package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
  152. package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
  153. package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
  154. package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
  155. package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
  156. package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
  157. package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
  158. package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
  159. package/runtime/dist/src/memory-ledger/store-client.js +235 -37
  160. package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
  161. package/runtime/dist/src/memory-ledger/store.js +91 -1
  162. package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
  163. package/runtime/dist/src/memory-substrate/diary.js +27 -0
  164. package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
  165. package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
  166. package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
  167. package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
  168. package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
  169. package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
  170. package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
  171. package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
  172. package/runtime/dist/src/memory-substrate/migration.js +2 -0
  173. package/runtime/dist/src/memory-substrate/purge.js +12 -2
  174. package/runtime/dist/src/memory-substrate/resource.js +514 -129
  175. package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
  176. package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
  177. package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
  178. package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
  179. package/runtime/dist/src/memory-substrate/source-state.js +8 -0
  180. package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
  181. package/runtime/dist/src/memory-substrate/store.js +125 -23
  182. package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
  183. package/runtime/dist/src/model/goal-writer.js +80 -0
  184. package/runtime/dist/src/model/jev-client.js +24 -13
  185. package/runtime/dist/src/model/model-adapters.js +2 -3
  186. package/runtime/dist/src/model/model-catalog.js +80 -0
  187. package/runtime/dist/src/model/model-gateway.js +47 -18
  188. package/runtime/dist/src/model/model-purpose.js +3 -4
  189. package/runtime/dist/src/model/personal-writer.js +536 -44
  190. package/runtime/dist/src/model/proactivity.js +50 -6
  191. package/runtime/dist/src/model/responses-model-gateway.js +59 -0
  192. package/runtime/dist/src/model/task-verifier.js +3 -3
  193. package/runtime/dist/src/model/timeline-anchors.js +77 -0
  194. package/runtime/dist/src/model/timeline-perspective.js +13 -0
  195. package/runtime/dist/src/model/timeline-selection.js +182 -0
  196. package/runtime/dist/src/model/understanding-writer.js +27 -0
  197. package/runtime/dist/src/model/vision-capability.js +3 -1
  198. package/runtime/dist/src/model/workbench-writer.js +96 -0
  199. package/runtime/dist/src/news/feeds.js +6 -10
  200. package/runtime/dist/src/news/interests.js +23 -0
  201. package/runtime/dist/src/news/service.js +87 -31
  202. package/runtime/dist/src/news/sources.json +116 -0
  203. package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
  204. package/runtime/dist/src/notifications/content.js +41 -0
  205. package/runtime/dist/src/notifications/contracts.js +4 -2
  206. package/runtime/dist/src/notifications/feed.js +6 -2
  207. package/runtime/dist/src/notifications/service.js +27 -14
  208. package/runtime/dist/src/notifications/store.js +3 -1
  209. package/runtime/dist/src/personal-agent/app-context.js +39 -4
  210. package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
  211. package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
  212. package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
  213. package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
  214. package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
  215. package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
  216. package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
  217. package/runtime/dist/src/personal-agent/contracts.js +24 -4
  218. package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
  219. package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
  220. package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
  221. package/runtime/dist/src/personal-agent/conversations.js +71 -15
  222. package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
  223. package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
  224. package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
  225. package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
  226. package/runtime/dist/src/personal-agent/host.js +2379 -223
  227. package/runtime/dist/src/personal-agent/identity-context.js +33 -0
  228. package/runtime/dist/src/personal-agent/life.js +129 -11
  229. package/runtime/dist/src/personal-agent/local-shell.js +181 -0
  230. package/runtime/dist/src/personal-agent/local-tools.js +234 -0
  231. package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
  232. package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
  233. package/runtime/dist/src/personal-agent/project-digests.js +7 -3
  234. package/runtime/dist/src/personal-agent/project-history.js +36 -0
  235. package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
  236. package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
  237. package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
  238. package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
  239. package/runtime/dist/src/personal-agent/sources.js +9 -1
  240. package/runtime/dist/src/personal-agent/store.js +124 -14
  241. package/runtime/dist/src/personal-agent/task-loop.js +3 -0
  242. package/runtime/dist/src/personal-agent/tasks.js +16 -4
  243. package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
  244. package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
  245. package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
  246. package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
  247. package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
  248. package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
  249. package/runtime/dist/src/personal-agent/understanding.js +7 -22
  250. package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
  251. package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
  252. package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
  253. package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
  254. package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
  255. package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
  256. package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
  257. package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
  258. package/runtime/dist/src/projects/project-native-resource.js +10 -8
  259. package/runtime/dist/src/projects/project-store.js +36 -4
  260. package/runtime/dist/src/realtime/bridge.js +77 -8
  261. package/runtime/dist/src/realtime/capabilities.js +19 -0
  262. package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
  263. package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
  264. package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
  265. package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
  266. package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
  267. package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
  268. package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
  269. package/runtime/dist/src/realtime/evidence.js +1 -1
  270. package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
  271. package/runtime/dist/src/realtime/gemini.js +14 -3
  272. package/runtime/dist/src/realtime/host-delivery.js +37 -4
  273. package/runtime/dist/src/realtime/protocol.js +18 -3
  274. package/runtime/dist/src/realtime/provider-projection.js +4 -1
  275. package/runtime/dist/src/realtime/provider-session.js +73 -16
  276. package/runtime/dist/src/realtime/qwen-transport.js +35 -4
  277. package/runtime/dist/src/realtime/qwen.js +144 -9
  278. package/runtime/dist/src/realtime/service-state.js +0 -1
  279. package/runtime/dist/src/realtime/service.js +93 -7
  280. package/runtime/dist/src/realtime/session.js +39 -32
  281. package/runtime/dist/src/realtime/sglang-native.js +214 -0
  282. package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
  283. package/runtime/dist/src/realtime/telemetry.js +6 -3
  284. package/runtime/dist/src/realtime/tool-continuations.js +84 -7
  285. package/runtime/dist/src/realtime/transport.js +17 -0
  286. package/runtime/dist/src/realtime/usage.js +33 -17
  287. package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
  288. package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
  289. package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
  290. package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
  291. package/runtime/dist/src/server/aoq-chat-server.js +1 -1
  292. package/runtime/dist/src/server/client-server.js +21 -0
  293. package/runtime/dist/src/server-entry.js +3 -0
  294. package/runtime/dist/src/space-host/admin-socket.js +115 -0
  295. package/runtime/dist/src/space-host/audio-owner.js +44 -0
  296. package/runtime/dist/src/space-host/cli.js +195 -0
  297. package/runtime/dist/src/space-host/config.js +247 -0
  298. package/runtime/dist/src/space-host/context-input.js +12 -0
  299. package/runtime/dist/src/space-host/contracts.js +10 -0
  300. package/runtime/dist/src/space-host/host-admin.js +114 -0
  301. package/runtime/dist/src/space-host/key-delivery.js +28 -0
  302. package/runtime/dist/src/space-host/mobile-tools.js +9 -0
  303. package/runtime/dist/src/space-host/model-settings.js +213 -0
  304. package/runtime/dist/src/space-host/projection.js +37 -0
  305. package/runtime/dist/src/space-host/push.js +137 -0
  306. package/runtime/dist/src/space-host/relay-transport.js +55 -0
  307. package/runtime/dist/src/space-host/service.js +841 -0
  308. package/runtime/dist/src/space-host/voice-crypto.js +240 -0
  309. package/runtime/dist/src/space-host/voice.js +600 -0
  310. package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
  311. package/runtime/dist/src/storage/private-database.js +7 -10
  312. package/runtime/dist/src/text/unicode-normalize.js +5 -1
  313. package/runtime/dist/src/understanding/candidates.js +8 -10
  314. package/runtime/dist/src/understanding/fixture.js +1 -1
  315. package/runtime/dist/src/understanding/pipeline.js +4 -4
  316. package/runtime/dist/src/usage/context.js +23 -0
  317. package/runtime/dist/src/usage/index.js +4 -0
  318. package/runtime/dist/src/usage/ledger-worker.js +90 -0
  319. package/runtime/dist/src/usage/ledger.js +74 -0
  320. package/runtime/dist/src/usage/model-call.js +63 -0
  321. package/runtime/dist/src/usage/pricing.js +68 -0
  322. package/runtime/dist/src/usage/summary.js +69 -0
  323. package/runtime/dist/src/voicemem/store-client.js +104 -21
  324. package/runtime/dist/src/voicemem/store-worker.js +5 -8
  325. package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
  326. package/src/command.mjs +8 -1
  327. package/runtime/dist/src/executors/autoglm.js +0 -376
@@ -1,6 +1,4 @@
1
- function isPlainObject(value) {
2
- return typeof value === 'object' && value !== null && !Array.isArray(value);
3
- }
1
+ import { isRecord } from '../../core/guards.js';
4
2
  /** A separate ephemeral turn; its id must never replace the user's persistent thread binding. */
5
3
  export async function generateSessionTitle(objective, rpc) {
6
4
  let threadId = null;
@@ -10,10 +8,10 @@ export async function generateSessionTitle(objective, rpc) {
10
8
  const unsubscribe = rpc.subscribe((method, params) => {
11
9
  if (threadId === null || params.threadId !== threadId)
12
10
  return;
13
- if (method === 'item/completed' && isPlainObject(params.item)
11
+ if (method === 'item/completed' && isRecord(params.item)
14
12
  && params.item.type === 'agentMessage' && typeof params.item.text === 'string')
15
13
  text = params.item.text;
16
- if (method === 'turn/completed' && isPlainObject(params.turn))
14
+ if (method === 'turn/completed' && isRecord(params.turn))
17
15
  complete(params.turn.status === 'completed');
18
16
  if (method === 'error')
19
17
  complete(false);
@@ -25,13 +23,13 @@ export async function generateSessionTitle(objective, rpc) {
25
23
  abandon();
26
24
  try {
27
25
  const response = await rpc.request('thread/start', {
28
- model: 'gpt-5.6-luna', ephemeral: true, permissions: ':read-only', approvalPolicy: 'never',
26
+ ...(rpc.model === null ? {} : { model: rpc.model ?? 'gpt-5.6-luna' }), ephemeral: true, permissions: ':read-only', approvalPolicy: 'never',
29
27
  config: { model_reasoning_effort: 'low', web_search: 'disabled',
30
28
  mcp_servers: Object.fromEntries((rpc.mcpServers ?? []).map(name => [name, { enabled: false }])),
31
29
  'features.apps': false, 'features.plugins': false, 'features.multi_agent': false, 'features.hooks': false },
32
30
  baseInstructions: 'Generate a concise task title in the user language. Do not execute the task or call tools.',
33
31
  });
34
- if (!isPlainObject(response) || !isPlainObject(response.thread) || typeof response.thread.id !== 'string')
32
+ if (!isRecord(response) || !isRecord(response.thread) || typeof response.thread.id !== 'string')
35
33
  return null;
36
34
  threadId = response.thread.id;
37
35
  await rpc.request('turn/start', {
@@ -42,7 +40,7 @@ export async function generateSessionTitle(objective, rpc) {
42
40
  if (!await done)
43
41
  return null;
44
42
  const result = JSON.parse(text);
45
- if (!isPlainObject(result) || typeof result.title !== 'string')
43
+ if (!isRecord(result) || typeof result.title !== 'string')
46
44
  return null;
47
45
  const title = result.title.replace(/\s+/gu, ' ').trim();
48
46
  return title.length > 0 && [...title].length <= 36 ? title : null;
@@ -3,6 +3,17 @@ import { snapshotJsonRecord } from './safe-json.js';
3
3
  export const NOVA_API_PROVIDER = 'nova_api_key';
4
4
  export const NOVA_API_KEY_ENV = 'NOVA_CODEX_API_KEY';
5
5
  const endpoint = 'https://api.openai.com/v1';
6
+ export const NOVA_RESPONSES_PROXY_ENV = 'NOVA_CODEX_RESPONSES_PROXY';
7
+ export function codexProviderEndpoint(value) {
8
+ if (value === undefined)
9
+ return endpoint;
10
+ if (!/^http:\/\/127\.0\.0\.1:[0-9]{1,5}\/v1$/u.test(value))
11
+ throw new CodexCredentialError();
12
+ const url = new URL(value);
13
+ if (!url.port || Number(url.port) < 1)
14
+ throw new CodexCredentialError();
15
+ return value;
16
+ }
6
17
  const ENVIRONMENT_ALLOWLIST = new Set([
7
18
  'PATH',
8
19
  'HOME',
@@ -81,14 +92,18 @@ export function createCodexEnvironment(source, home, apiKey, managedEnvironment,
81
92
  }
82
93
  result.CODEX_HOME = home;
83
94
  result.CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED = '1';
84
- if (validateApiKey(apiKey) !== null)
95
+ if (validateApiKey(apiKey) !== null) {
85
96
  result[NOVA_API_KEY_ENV] = apiKey;
97
+ const proxy = environmentValue(source, NOVA_RESPONSES_PROXY_ENV, platform);
98
+ if (proxy !== undefined)
99
+ result[NOVA_RESPONSES_PROXY_ENV] = codexProviderEndpoint(proxy);
100
+ }
86
101
  if (Object.keys(managedEnvironment).some(key => CHILD_ENVIRONMENT_KEYS.has(key)))
87
102
  throw new CodexCredentialError();
88
103
  return validateCodexEnvironment({ ...result, ...managedEnvironment }, home, managedEnvironment);
89
104
  }
90
105
  const CHILD_ENVIRONMENT_KEYS = new Set([...ENVIRONMENT_ALLOWLIST, 'CODEX_HOME',
91
- 'CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED', NOVA_API_KEY_ENV]);
106
+ 'CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED', NOVA_API_KEY_ENV, NOVA_RESPONSES_PROXY_ENV]);
92
107
  export function validateCodexEnvironment(value, expectedCodexHome, managedEnvironment) {
93
108
  const prototype = Object.getPrototypeOf(value);
94
109
  if (prototype !== Object.prototype && prototype !== null)
@@ -116,6 +131,9 @@ export function validateCodexEnvironment(value, expectedCodexHome, managedEnviro
116
131
  || result.CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED !== '1'
117
132
  || result[NOVA_API_KEY_ENV] === '')
118
133
  throw new CodexCredentialError();
134
+ codexProviderEndpoint(result[NOVA_RESPONSES_PROXY_ENV]);
135
+ if (result[NOVA_RESPONSES_PROXY_ENV] !== undefined && !result[NOVA_API_KEY_ENV])
136
+ throw new CodexCredentialError();
119
137
  return Object.freeze(result);
120
138
  }
121
139
  function defineString(target, key, value) {
@@ -127,21 +145,24 @@ function defineString(target, key, value) {
127
145
  });
128
146
  }
129
147
  /** CLI tables merge with user config; verify the effective table before using it. */
130
- export function apiKeyProviderOverrides() {
148
+ export function apiKeyProviderOverrides(proxy) {
149
+ const baseUrl = codexProviderEndpoint(proxy);
131
150
  return [
132
151
  `model_provider="${NOVA_API_PROVIDER}"`,
133
152
  `model_providers.${NOVA_API_PROVIDER}.name="Nova API key"`,
134
- `model_providers.${NOVA_API_PROVIDER}.base_url="${endpoint}"`,
153
+ `model_providers.${NOVA_API_PROVIDER}.base_url="${baseUrl}"`,
135
154
  `model_providers.${NOVA_API_PROVIDER}.env_key="${NOVA_API_KEY_ENV}"`,
136
155
  `model_providers.${NOVA_API_PROVIDER}.wire_api="responses"`,
137
156
  `model_providers.${NOVA_API_PROVIDER}.requires_openai_auth=false`,
157
+ ...(proxy === undefined ? [] : [`model_providers.${NOVA_API_PROVIDER}.supports_websockets=false`]),
138
158
  ].flatMap(value => ['-c', value]);
139
159
  }
140
- export function assertApiKeyProvider(response) {
160
+ export function assertApiKeyProvider(response, proxy) {
141
161
  const config = snapshotJsonRecord(snapshotJsonRecord(response).config);
142
162
  const provider = snapshotJsonRecord(snapshotJsonRecord(config.model_providers)[NOVA_API_PROVIDER]);
143
163
  if (config.model_provider !== NOVA_API_PROVIDER
144
- || provider.base_url !== endpoint || provider.env_key !== NOVA_API_KEY_ENV
164
+ || provider.base_url !== codexProviderEndpoint(proxy)
165
+ || proxy !== undefined && provider.supports_websockets !== false || provider.env_key !== NOVA_API_KEY_ENV
145
166
  || provider.wire_api !== 'responses' || provider.requires_openai_auth !== false) {
146
167
  throw new TypeError('API key provider configuration mismatch');
147
168
  }
@@ -4,6 +4,7 @@ import { snapshotJsonRecord } from './safe-json.js';
4
4
  import { validProgressSummary } from '../../core/events.js';
5
5
  import { isPythonSpace } from '../../text/python-text.js';
6
6
  import { CodexProtocolError, MAX_FINAL_TEXT_INPUT, MAX_INTERNAL_ACTIVITY, MAX_STDOUT, SUMMARY_PROSE_LIMIT, WORKING_INTERVAL, } from './protocol.js';
7
+ import { isPlainRecord } from '../../core/guards.js';
7
8
  const observationSensitivity = new SensitiveContentPolicy();
8
9
  const artifactPathSensitivity = new SensitivePathPolicy();
9
10
  const EAGER_ACTIVITY_INTERVAL_SECONDS = 60;
@@ -165,7 +166,7 @@ export class AppServerTurnProjection {
165
166
  return this.#turnCompleted(snapshot);
166
167
  }
167
168
  #turnStarted(params) {
168
- if (params.threadId !== this.#threadId || !isPlainObject(params.turn))
169
+ if (params.threadId !== this.#threadId || !isPlainRecord(params.turn))
169
170
  return;
170
171
  const turnId = params.turn.id;
171
172
  if (typeof turnId !== 'string' || turnId === '' || this.#notificationTurnId !== null)
@@ -282,15 +283,15 @@ export class AppServerTurnProjection {
282
283
  if (stage === 'completed' && item.type === 'commandExecution')
283
284
  text = JSON.stringify({ type: item.type, status, command: publicField(item.command), output: publicField(item.aggregatedOutput), exit_code: Number.isSafeInteger(item.exitCode) ? item.exitCode : null });
284
285
  if (stage === 'completed' && item.type === 'mcpToolCall') {
285
- const result = isPlainObject(item.result) && Array.isArray(item.result.content) ? item.result.content : [];
286
- const readback = result.filter((part) => isPlainObject(part) && part.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n');
287
- text = JSON.stringify({ type: item.type, server: publicField(item.server), tool: publicField(item.tool), status, is_error: isPlainObject(item.result) && typeof item.result.isError === 'boolean' ? item.result.isError : null, readback: publicField(readback) });
286
+ const result = isPlainRecord(item.result) && Array.isArray(item.result.content) ? item.result.content : [];
287
+ const readback = result.filter((part) => isPlainRecord(part) && part.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n');
288
+ text = JSON.stringify({ type: item.type, server: publicField(item.server), tool: publicField(item.tool), status, is_error: isPlainRecord(item.result) && typeof item.result.isError === 'boolean' ? item.result.isError : null, readback: publicField(readback) });
288
289
  }
289
290
  this.#publicStages.add(key);
290
291
  const refs = [];
291
292
  if (item.type === 'fileChange' && Array.isArray(item.changes) && this.#workspace)
292
293
  for (const change of item.changes) {
293
- if (!isPlainObject(change) || typeof change.path !== 'string')
294
+ if (!isPlainRecord(change) || typeof change.path !== 'string')
294
295
  continue;
295
296
  const absolutePath = resolve(this.#workspace, change.path);
296
297
  const path = relative(this.#workspace, absolutePath);
@@ -331,12 +332,12 @@ export class AppServerTurnProjection {
331
332
  && this.#activeTurnId !== null
332
333
  && params.threadId === this.#threadId
333
334
  && params.turnId === this.#activeTurnId
334
- && isPlainObject(params.item);
335
+ && isPlainRecord(params.item);
335
336
  }
336
337
  #turnCompleted(params) {
337
338
  if (params.threadId !== this.#threadId)
338
339
  return null;
339
- if (!isPlainObject(params.turn))
340
+ if (!isPlainRecord(params.turn))
340
341
  return null;
341
342
  const turn = params.turn;
342
343
  if (turn.id !== this.#activeTurnId)
@@ -346,9 +347,9 @@ export class AppServerTurnProjection {
346
347
  throw new CodexProtocolError('unsupported_protocol');
347
348
  let finalText = null;
348
349
  for (const candidate of turn.items) {
349
- if (isPlainObject(candidate))
350
+ if (isPlainRecord(candidate))
350
351
  this.#publicItem(candidate, 'completed');
351
- if (isPlainObject(candidate)
352
+ if (isPlainRecord(candidate)
352
353
  && candidate.type === 'agentMessage'
353
354
  && typeof candidate.text === 'string')
354
355
  finalText = clipCodePoints(candidate.text, MAX_FINAL_TEXT_INPUT);
@@ -417,19 +418,13 @@ function requireNonemptyString(value) {
417
418
  return value;
418
419
  }
419
420
  function requireObject(value) {
420
- if (!isPlainObject(value))
421
+ if (!isPlainRecord(value))
421
422
  throw new TypeError('object');
422
423
  return value;
423
424
  }
424
425
  function safeTurnErrorCode(value) {
425
- if (!isPlainObject(value))
426
+ if (!isPlainRecord(value))
426
427
  return null;
427
428
  return value.codexErrorInfo === 'usageLimitExceeded' ? 'usage_limit_exceeded' : null;
428
429
  }
429
- function isPlainObject(value) {
430
- if (typeof value !== 'object' || value === null || Array.isArray(value))
431
- return false;
432
- const prototype = Object.getPrototypeOf(value);
433
- return prototype === Object.prototype || prototype === null;
434
- }
435
430
  //# sourceMappingURL=turn-projection.js.map
@@ -4,6 +4,7 @@ import { closeSync, openSync, readSync, realpathSync, statSync } from 'node:fs';
4
4
  import { isAbsolute, resolve } from 'node:path';
5
5
  import { snapshotJsonRecord } from './safe-json.js';
6
6
  import { CodexProcessOwnerError, } from './process-owner.js';
7
+ import { exactKeys } from '../../core/guards.js';
7
8
  export const WINDOWS_GUARDIAN_FRAME_LIMIT = 4096;
8
9
  export const WINDOWS_GUARDIAN_READY_TIMEOUT_MS = 5000;
9
10
  const WINDOWS_GUARDIAN_ID = 'windows_job_guardian';
@@ -189,7 +190,7 @@ export class WindowsGuardianCodexProcessOwnerFactory {
189
190
  || !this.#validateHelper())
190
191
  throw new CodexProcessOwnerError('spawn_failed');
191
192
  const details = (spec);
192
- const guardian = this.#spawnGuardian(details.binary, details.argv, details.cwd, details.environment);
193
+ const guardian = this.#spawnGuardian(details.binary, details.argv, details.cwd, details.environment, details.terminateDescendantsOnExit === true);
193
194
  const remaining = Math.min(WINDOWS_GUARDIAN_READY_TIMEOUT_MS, Math.max(0, control.expiresAtMs - Date.now()));
194
195
  const abort = () => { guardian.abandon(); };
195
196
  control.signal.addEventListener('abort', abort, { once: true });
@@ -292,13 +293,14 @@ export class WindowsGuardianCodexProcessOwnerFactory {
292
293
  throw new CodexProcessOwnerError('spawn_failed');
293
294
  }
294
295
  }
295
- #spawnGuardian(target, argv, cwd, environment) {
296
+ #spawnGuardian(target, argv, cwd, environment, terminateDescendantsOnExit = false) {
296
297
  const helperPath = windowsGuardianHelperPath(this.#helper);
297
298
  let child;
298
299
  try {
299
300
  child = this.#launch(helperPath, Object.freeze([
300
301
  '--target', target,
301
302
  '--cwd', cwd,
303
+ ...(terminateDescendantsOnExit ? ['--terminate-on-leader-exit'] : []),
302
304
  '--', target,
303
305
  ...argv,
304
306
  ]), Object.freeze({
@@ -678,10 +680,6 @@ function validatePortableExecutable(path, architecture) {
678
680
  if (!executableCodeSection)
679
681
  throw new CodexWindowsGuardianError();
680
682
  }
681
- function exactKeys(value, expected) {
682
- const keys = Object.keys(value);
683
- return keys.length === expected.length && expected.every(key => Object.hasOwn(value, key));
684
- }
685
683
  function topLevelColonCount(raw) {
686
684
  let inString = false;
687
685
  let escaped = false;
@@ -67,7 +67,8 @@ function evidenceOccurs(evidence, project, utterances, roster) {
67
67
  return named.length === 1 && named[0] === normalize(project);
68
68
  }
69
69
  // ponytail: recognize explicit directive clauses only; uncertain paraphrases retain confirmation.
70
- const directiveText = (text) => text.replace(/"[^"]*"|“[^”]*”|‘[^’]*’|「[^」]*」|`[^`]*`|(?<![\p{L}\p{N}])'[^']*'(?![\p{L}\p{N}])/gu, '');
70
+ const quotedText = /"[^"]*"|“[^”]*”|‘[^’]*’|「[^」]*」|`[^`]*`|(?<![\p{L}\p{N}])'[^']*'(?![\p{L}\p{N}])/gu;
71
+ const directiveText = (text) => text.replace(quotedText, '');
71
72
  const directStartRequested = (text) => {
72
73
  const plain = directiveText(text);
73
74
  if (/[??]|先(?:问|确认)|不允许|不准|禁止|\b(?:before|forbidden|not allowed)\b/iu.test(plain))
@@ -86,7 +87,9 @@ const latestSessionDirective = (texts) => {
86
87
  };
87
88
  const continuationIntent = (texts) => {
88
89
  const plain = latestSessionDirective(texts);
89
- if (/(?:不要|别|不再|不是|不)(?:再)?继续|(?:新开|重新开|另开).{0,6}会话|新会话|\b(?:new|fresh) (?:session|thread)\b|\b(?:do not|don't) (?:continue|resume)\b/iu.test(plain))
90
+ const newSession = [...plain.matchAll(/(?:新开|重新开|另开).{0,6}会话|新会话|\b(?:new|fresh) (?:session|thread)\b/giu)]
91
+ .some(match => !/(?:不要|别|不允许|不准|禁止|无需|不用)(?:再)?\s*$|\b(?:no|not|never|don't|do not)(?:\s+(?:open|start|create))?\s*$/iu.test(plain.slice(0, match.index)));
92
+ if (newSession || /(?:不要|别|不再|不是|不)(?:再)?继续|\b(?:do not|don't) (?:continue|resume)\b/iu.test(plain))
90
93
  return 'new';
91
94
  if (/继续|接着|先(?:问|确认)|不确定|\b(?:continue|resume)\b/iu.test(plain)) {
92
95
  return !/[??]|之前|先(?:问|确认)|不允许|不确定|是否/iu.test(plain)
@@ -586,7 +589,9 @@ export class IntakeController {
586
589
  if (!title)
587
590
  return false;
588
591
  const roster = this.#options.roster();
589
- const evidence = [current.opening, ...current.turns.map(turn => turn.answer)].map(directiveText);
592
+ // Preserve an exact named title as data, without treating other quoted text as an instruction.
593
+ const evidence = [current.opening, ...current.turns.map(turn => turn.answer)]
594
+ .map(text => directiveText(text.replace(quotedText, quote => quote.slice(1, -1) === title ? title : quote)));
590
595
  const namedProject = evidence.some(text => text.includes(project));
591
596
  if (!namedProject && roster.filter(entry => entry.sessions?.includes(title)).length !== 1)
592
597
  return false;
@@ -597,7 +602,9 @@ export class IntakeController {
597
602
  return false;
598
603
  const before = text.slice(0, index).trimEnd(), after = text.slice(index + title.length).trimStart();
599
604
  return /(?:继续|接着|\bcontinue|\bresume)\s*$/iu.test(before)
600
- || (/(?:在|用|使用|切换到|\bin(?: the)?)\s*$/iu.test(before) && /^(?:(?:这个)?会话|session\b)/iu.test(after));
605
+ || (/(?:在|用|使用|切换到|\bin(?: the)?)\s*$/iu.test(before) && /^(?:(?:这个)?会话|session\b)/iu.test(after))
606
+ || (/(?:会话|session|thread)(?:名称|名)?\s*(?:是|为|[::])\s*$/iu.test(before)
607
+ && /^(?:[,,。.!!;;\n]\s*)?(?:请|现在|那就)?(?:在|用|使用)(?:这(?:一)?个|该|上述|指定的)会话(?:里|中)?(?:继续|接着)/u.test(after));
601
608
  }
602
609
  async #plan(snapshot) {
603
610
  const abort = new AbortController();
@@ -764,9 +771,7 @@ export class IntakeController {
764
771
  finally {
765
772
  timeout.abort();
766
773
  const current = this.#live(snapshot.intake_id, snapshot.revision);
767
- const model = stage === 'assess' ? this.#options.settings.support_model
768
- : (this.#options.settings.planner_model ?? '') !== ''
769
- ? this.#options.settings.planner_model : this.#options.settings.fast_model;
774
+ const model = this.#options.settings.support_model;
770
775
  if (current !== null)
771
776
  this.#options.record(current, 'intake.timing', { stage, attempt,
772
777
  ...(model === undefined ? {} : { model }), input_chars: JSON.stringify(requestInput).length,
@@ -23,6 +23,8 @@ export async function startComputerBackend(displayId, signal, budgetMs = 30_000,
23
23
  const focusSchema = z.object({ focus: z.object({ pid: z.number().int().positive().max(2147483647), windowId: z.number().int().positive().max(4294967295), started: z.number().finite().positive() }), targetStarted: z.number().finite().positive() });
24
24
  let focusLease;
25
25
  let pointerReleaseNeeded = false, keyboardReleaseNeeded;
26
+ // The editor seen in the latest observation; the next Input/KeyboardPress must still target it.
27
+ let expectedEditor;
26
28
  const temporary = mkdtempSync(join(tmpdir(), 'nova-gui-input-'));
27
29
  const environment = { TMPDIR: temporary, TEMP: temporary, TMP: temporary, ELECTRON_RUN_AS_NODE: '1' };
28
30
  // Only driver dependencies; no model credentials or inherited NODE_OPTIONS.
@@ -67,7 +69,11 @@ export async function startComputerBackend(displayId, signal, budgetMs = 30_000,
67
69
  if (result.ok === true)
68
70
  entry.resolve(result.value);
69
71
  else {
70
- entry.reject(new Error(entry.write ? 'cleanup_unknown' : 'action_failed'));
72
+ const detail = typeof result.detail === 'string' && /^native_gui:[a-z_]{1,80}$/u.test(result.detail) ? result.detail : undefined;
73
+ // The helper raises editor_unavailable only before sending input; the model must observe again.
74
+ // Keep the worker's own message for diagnosis; it never changes the classification.
75
+ const workerError = typeof result.error === 'string' && result.error ? new Error(`worker:${result.error.slice(0, 300)}`) : undefined;
76
+ entry.reject(new Error(entry.write ? detail === 'native_gui:editor_unavailable' ? 'screen_changed' : 'cleanup_unknown' : 'action_failed', { cause: detail ? new Error(detail, { cause: workerError }) : workerError }));
71
77
  stop();
72
78
  }
73
79
  };
@@ -112,7 +118,7 @@ export async function startComputerBackend(displayId, signal, budgetMs = 30_000,
112
118
  return false;
113
119
  if (focusLease && focusReader && macWindow) {
114
120
  try {
115
- const restored = await focusReader.request({ ...macWindow, op: 'focusRestore', releasePointer: true, ...focusLease }, AbortSignal.timeout(2000));
121
+ const restored = await focusReader.request({ ...macWindow, op: 'focusRestore', ...focusLease }, AbortSignal.timeout(2000));
116
122
  if (restored.restored !== true)
117
123
  return false;
118
124
  focusLease = undefined;
@@ -142,7 +148,7 @@ export async function startComputerBackend(displayId, signal, budgetMs = 30_000,
142
148
  return true;
143
149
  };
144
150
  const descriptions = { Tap: 'Click once at the point.', Input: 'Append text to the already focused field; Tap it first.', Scroll: 'Scroll once by a bounded distance.', KeyboardPress: 'Press a shortcut in the current focus; use Command on macOS, Control on Windows.' };
145
- const schemas = { Tap: actionTapParamSchema, Input: z.object({ value: z.string().min(1).max(macWindow ? 200 : 4000) }).strict(), Scroll: actionScrollParamSchema, KeyboardPress: actionKeyboardPressParamSchema };
151
+ const schemas = { Tap: actionTapParamSchema, Input: z.object({ value: z.string().min(1).max(macWindow ? 200 : 4000), mode: z.enum(['append', 'replace']).default('append') }).strict(), Scroll: actionScrollParamSchema, KeyboardPress: actionKeyboardPressParamSchema };
146
152
  const device = { interfaceType: 'computer',
147
153
  size: async () => {
148
154
  const value = await request('size');
@@ -156,13 +162,15 @@ export async function startComputerBackend(displayId, signal, budgetMs = 30_000,
156
162
  return value;
157
163
  }, actionSpace: () => Object.entries(schemas).map(([name, paramSchema]) => ({ name, description: descriptions[name] ?? name, paramSchema,
158
164
  call: async (params) => {
159
- if (name === 'Tap' && focusReader && macWindow) {
160
- const lease = { ...focusSchema.parse(await focusReader.request({ ...macWindow, op: 'focusSnapshot' }, signal)), clickGroup: randomInt(1, 2147483647) };
165
+ if (['Tap', 'Input', 'KeyboardPress'].includes(name) && focusReader && macWindow) {
166
+ const lease = { ...focusSchema.parse(await focusReader.request({ ...macWindow, op: 'focusSnapshot' }, signal)), clickGroup: randomInt(1, 2147483647), releasePointer: name === 'Tap', ...(name === 'KeyboardPress' ? { releaseKey: actionKeyboardPressParamSchema.parse(params).keyName } : name === 'Input' ? { releaseKey: 'unicode' } : {}) };
161
167
  if (closed || signal.aborted)
162
168
  throw Error('cancelled');
163
- focusLease = lease; // Host survives worker teardown and restores before releasing ownership.
164
- const receipt = await request(name, { ...params, focusLease: lease }, true);
165
- if (receipt?.restored !== true) {
169
+ focusLease = lease; // Host survives worker teardown and releases targeted input before ownership.
170
+ const expected = name === 'Tap' ? undefined : expectedEditor;
171
+ expectedEditor = undefined;
172
+ const receipt = await request(name, { ...params, focusLease: lease, ...(expected ? { expectedEditor: expected } : {}) }, true);
173
+ if (name === 'Tap' && receipt?.restored !== true) {
166
174
  stop();
167
175
  throw Error('cleanup_unknown');
168
176
  }
@@ -180,9 +188,9 @@ export async function startComputerBackend(displayId, signal, budgetMs = 30_000,
180
188
  keyboardReleaseNeeded = undefined;
181
189
  }
182
190
  } })) };
183
- return { device, pid: child.pid, releaseInput: async (pointer, keyName) => { await request('releaseInput', { pointer, ...(keyName ? { keyName } : {}) }, true); }, windowTarget: async () => z.object({ target: z.string().min(1), width: z.number().positive(), height: z.number().positive() }).parse(await request('target')), connect: async () => { await request('connect', undefined, true); }, listDisplays: async () => {
191
+ return { device, pid: child.pid, expectEditor: (editor) => { expectedEditor = editor && { role: editor.role, value: editor.value }; }, releaseInput: async (pointer, keyName) => { await request('releaseInput', { pointer, ...(keyName ? { keyName } : {}) }, true); }, windowTarget: async () => z.object({ target: z.string().min(1), width: z.number().positive(), height: z.number().positive() }).parse(await request('target')), connect: async () => { await request('connect', undefined, true); }, listDisplays: async () => {
184
192
  const value = await request('listDisplays');
185
- return z.array(z.object({ id: z.string() })).parse(value);
193
+ return z.array(z.object({ id: z.string(), primary: z.boolean().optional() })).parse(value);
186
194
  }, close };
187
195
  }
188
196
  //# sourceMappingURL=computer-backend.js.map
@@ -0,0 +1,32 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { resolveDataRoot } from '../config/data-root.js';
4
+ import { validGuiConfig } from './gui-runner.js';
5
+ import { validComputerDisplayId } from './computer-device.js';
6
+ export function loadComputerDeviceConfig(env) {
7
+ const displayId = env.COMPUTER_DISPLAY_ID?.trim() ?? '';
8
+ const config = { ...(env.CODEX_RESOURCES_PATH ? { resourcesPath: env.CODEX_RESOURCES_PATH } : {}), displayId: displayId.length ? displayId : 'primary', maxSteps: Number(env.EXECUTOR_MAX_STEPS ?? 30),
9
+ budgetMs: Number(env.EXECUTOR_TIMEOUT_SECONDS ?? 600) * 1000, settleMs: Number(env.EXECUTOR_SETTLE_MS ?? 4000), clickHoldMs: Number(env.COMPUTER_CLICK_HOLD_MS ?? 100),
10
+ lockRoot: join(resolveDataRoot(homedir()).root, 'gui-devices') };
11
+ const windowPid = env.COMPUTER_MAC_WINDOW_PID === '' ? undefined : env.COMPUTER_MAC_WINDOW_PID, windowId = env.COMPUTER_MAC_WINDOW_ID === '' ? undefined : env.COMPUTER_MAC_WINDOW_ID;
12
+ let macWindow;
13
+ if (windowPid !== undefined || windowId !== undefined) {
14
+ if (process.platform !== 'darwin' || !/^[1-9]\d{0,9}$/u.test(windowPid ?? '') || !/^[1-9]\d{0,9}$/u.test(windowId ?? '')
15
+ || Number(windowPid) > 2147483647 || Number(windowId) > 4294967295)
16
+ throw Error('invalid_computer_configuration');
17
+ macWindow = { pid: Number(windowPid), windowId: Number(windowId) };
18
+ }
19
+ if (!Number.isSafeInteger(config.clickHoldMs) || config.clickHoldMs < 10 || config.clickHoldMs > 1000 || !validComputerDisplayId(config.displayId)
20
+ || !Number.isSafeInteger(config.maxSteps) || config.maxSteps < 1 || config.maxSteps > 100
21
+ || !Number.isSafeInteger(config.budgetMs) || config.budgetMs < 1 || config.budgetMs > 1_800_000
22
+ || !Number.isSafeInteger(config.settleMs) || config.settleMs < 0 || config.settleMs > 30_000)
23
+ throw new Error('invalid_computer_configuration');
24
+ return { ...config, ...(macWindow ? { macWindow } : {}) };
25
+ }
26
+ export function loadComputerConfig(env) {
27
+ const config = { ...loadComputerDeviceConfig(env), baseUrl: env.EXECUTOR_BASE_URL ?? '', model: env.EXECUTOR_MODEL ?? '', modelFamily: env.EXECUTOR_MODEL_FAMILY ?? '', apiKey: env.EXECUTOR_API_KEY ?? '' };
28
+ if (!validGuiConfig(config, 'validate'))
29
+ throw Error('invalid_computer_configuration');
30
+ return config;
31
+ }
32
+ //# sourceMappingURL=computer-config.js.map
@@ -37,8 +37,11 @@ export async function computerWrite(action, budgetMs) {
37
37
  timer = setTimeout(() => reject(new Error('cleanup_unknown')), Math.min(budgetMs, 30_000));
38
38
  })]);
39
39
  }
40
- catch {
41
- throw new Error('cleanup_unknown');
40
+ catch (error) {
41
+ // Only the helper's proven pre-dispatch refusal stays recoverable.
42
+ if (error instanceof Error && error.message === 'screen_changed' && error.cause instanceof Error && error.cause.message === 'native_gui:editor_unavailable')
43
+ throw error;
44
+ throw new Error('cleanup_unknown', { cause: error });
42
45
  }
43
46
  finally {
44
47
  clearTimeout(timer);
@@ -79,7 +82,7 @@ export async function guardComputerDevice(raw, target, options) {
79
82
  validateCoordinates(params, baseline);
80
83
  const input = params;
81
84
  // Input/key actions use existing focus; SDK target autofocusing can emit extra clicks.
82
- if (action.name === 'Input' && (input.locate || (input.mode !== undefined && input.mode !== 'typeOnly') || typeof input.value !== 'string'
85
+ if (action.name === 'Input' && (input.locate || (input.mode !== undefined && (typeof input.mode !== 'string' || !['typeOnly', 'append', 'replace'].includes(input.mode))) || typeof input.value !== 'string'
83
86
  || !input.value || input.value.length > 4000))
84
87
  throw new Error('needs_user_action');
85
88
  if (action.name === 'KeyboardPress' && (input.locate || typeof input.keyName !== 'string'
@@ -89,6 +92,9 @@ export async function guardComputerDevice(raw, target, options) {
89
92
  && (typeof input.distance !== 'number' || !Number.isFinite(input.distance) || input.distance <= 0
90
93
  || input.distance > Math.max(baseline.width, baseline.height)))))
91
94
  throw new Error('needs_user_action');
95
+ // Keys and text go to the focused window; never into one the model cannot see on the captured display.
96
+ if ((action.name === 'Input' || action.name === 'KeyboardPress') && baseline.visible === false)
97
+ throw new Error('needs_user_action', { cause: new Error('worker:focused window is outside the primary display; click the target on the primary display first') });
92
98
  await fresh(baseline);
93
99
  options.progress({ phase: 'action_pending', steps, actionName: action.name });
94
100
  if (!await guiApproval(options.approve(action.name, params), options.signal))
@@ -101,14 +107,14 @@ export async function guardComputerDevice(raw, target, options) {
101
107
  planned = undefined;
102
108
  options.progress({ phase: 'action_returned', steps, actionName: action.name });
103
109
  check();
104
- // Observation is retained in memory; model Finished alone is never verification.
105
- const observed = await device.screenshotBase64();
106
- options.capture?.(observed, steps);
110
+ // Build takes a fresh observation explicitly, which may now be in a different window.
111
+ if (options.capture)
112
+ options.capture(await device.screenshotBase64(), steps);
107
113
  }
108
114
  catch (error) {
109
115
  const reason = error instanceof Error ? error.message : '';
110
116
  failure ??= ['cleanup_unknown', 'cancelled', 'step_limit', 'screen_changed', 'needs_user_action', 'declined'].includes(reason) ? reason : 'action_failed';
111
- throw new Error(failure);
117
+ throw new Error(failure, { cause: error });
112
118
  }
113
119
  } }));
114
120
  const device = { interfaceType: raw.interfaceType, size: async () => {
@@ -129,10 +135,14 @@ const pid = Number(app.processIdentifier);
129
135
  const windows = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(17, 0)));
130
136
  const window = windows.find(w => w.kCGWindowOwnerPID === pid && w.kCGWindowLayer === 0);
131
137
  if (!window) throw new Error('no foreground window');
132
- if (Number($.NSScreen.screens.count) !== 1) throw new Error('multiple displays');
133
- const frame = $.NSScreen.mainScreen.frame;
138
+ // screens[0] is the primary display (menu bar, origin 0,0); mainScreen follows keyboard focus.
139
+ const frame = $.NSScreen.screens.objectAtIndex(0).frame;
140
+ const b = window.kCGWindowBounds;
141
+ // The window counts as visible when its centre lies on the primary display.
142
+ const cx = b.X + b.Width / 2, cy = b.Y + b.Height / 2;
143
+ const visible = cx >= 0 && cx < frame.size.width && cy >= 0 && cy < frame.size.height;
134
144
  JSON.stringify({target: [pid, ObjC.unwrap(app.bundleIdentifier), window.kCGWindowNumber, window.kCGWindowBounds],
135
- width: frame.size.width, height: frame.size.height});`;
145
+ width: frame.size.width, height: frame.size.height, visible});`;
136
146
  export async function macForeground(signal) {
137
147
  const { stdout } = await exec('/usr/bin/osascript', ['-l', 'JavaScript', '-e', foregroundScript], { signal, timeout: 5000, maxBuffer: 16_384 });
138
148
  const value = JSON.parse(stdout.trim());
@@ -141,9 +151,11 @@ export async function macForeground(signal) {
141
151
  || typeof identity[1] !== 'string' || typeof identity[2] !== 'number' || !identity[3]
142
152
  || typeof value.width !== 'number' || typeof value.height !== 'number')
143
153
  throw new Error('invalid_configuration');
144
- return { target: JSON.stringify(identity), width: value.width, height: value.height };
154
+ return { target: JSON.stringify(identity), width: value.width, height: value.height, ...(typeof value.visible === 'boolean' ? { visible: value.visible } : {}) };
145
155
  }
146
156
  export function validComputerDisplayId(value, platform = process.platform) {
157
+ if (value === 'primary')
158
+ return true;
147
159
  return platform === 'win32' ? /^\\\\\.\\DISPLAY[1-9]\d{0,2}$/u.test(value) : /^\d{1,10}$/u.test(value);
148
160
  }
149
161
  // Win32 identity and physical geometry only; no UIA tree or control semantics.
@@ -160,16 +172,16 @@ public static class NovaWindow {
160
172
  '@
161
173
  if ([NovaWindow]::SetThreadDpiAwarenessContext([IntPtr](-4)) -eq [IntPtr]::Zero) {throw 'dpi_unavailable'}
162
174
  Add-Type -AssemblyName System.Windows.Forms
163
- $screens = [System.Windows.Forms.Screen]::AllScreens
164
- if ($screens.Count -ne 1) {throw 'screen_changed'}
165
- $bounds = $screens[0].Bounds
175
+ $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
166
176
  if ($bounds.X -ne 0 -or $bounds.Y -ne 0) {throw 'screen_changed'}
167
177
  $window = [NovaWindow]::GetForegroundWindow()
168
178
  $processId = [uint32]0
169
179
  $rect = New-Object NovaWindow+Rect
170
180
  [void][NovaWindow]::GetWindowThreadProcessId($window, [ref]$processId)
171
181
  if ($window -eq [IntPtr]::Zero -or ![NovaWindow]::GetWindowRect($window, [ref]$rect)) {throw 'window_unavailable'}
172
- @{target = @($processId, $window.ToInt64(), @($rect.Left, $rect.Top, $rect.Right, $rect.Bottom)); width=$bounds.Width; height=$bounds.Height} | ConvertTo-Json -Compress -Depth 4`;
182
+ $cx = ($rect.Left + $rect.Right) / 2; $cy = ($rect.Top + $rect.Bottom) / 2
183
+ $visible = ($cx -ge 0) -and ($cx -lt $bounds.Width) -and ($cy -ge 0) -and ($cy -lt $bounds.Height)
184
+ @{target = @($processId, $window.ToInt64(), @($rect.Left, $rect.Top, $rect.Right, $rect.Bottom)); width=$bounds.Width; height=$bounds.Height; visible=$visible} | ConvertTo-Json -Compress -Depth 4`;
173
185
  export async function computerForeground(signal) {
174
186
  if (process.platform === 'darwin')
175
187
  return macForeground(signal);
@@ -182,6 +194,46 @@ export async function computerForeground(signal) {
182
194
  || typeof value.width !== 'number' || !Number.isFinite(value.width) || value.width <= 0
183
195
  || typeof value.height !== 'number' || !Number.isFinite(value.height) || value.height <= 0)
184
196
  throw Error('invalid_configuration');
185
- return { target: JSON.stringify(value.target), width: value.width, height: value.height };
197
+ return { target: JSON.stringify(value.target), width: value.width, height: value.height, ...(typeof value.visible === 'boolean' ? { visible: value.visible } : {}) };
198
+ }
199
+ /** Both planners share connection consent and target checks; callers retain their resource lease. */
200
+ export async function connectComputerDevice(backend, config, options) {
201
+ const target = async () => {
202
+ options.signal.throwIfAborted();
203
+ if (config.macWindow)
204
+ return { displayId: config.displayId, ...await backend.windowTarget() };
205
+ // With several displays Nova sees and drives only the primary one (or the configured display).
206
+ const displays = await backend.listDisplays();
207
+ // Worker taps use global coordinates without a display offset, so a configured secondary display is only safe alone.
208
+ const display = config.displayId === 'primary' ? displays.find(item => item.primary) ?? displays[0] : displays.length === 1 ? displays.find(item => item.id === config.displayId) : undefined;
209
+ if (!display)
210
+ throw Error('screen_changed');
211
+ return { displayId: display.id, ...await (options.foreground ?? computerForeground)(options.signal) };
212
+ };
213
+ const baseline = await target();
214
+ if (!await guiApproval(options.approve('Connect', config.macWindow
215
+ ? { window: config.macWindow, ...(config.macApplication ? { application: config.macApplication } : {}), mode: 'background', healthCheck: 'window identity only', pointerInput: 'window-bound AX actions or targeted events; no foreground activation' }
216
+ : { displayId: config.displayId, mode: 'activated', healthCheck: 'moves and restores pointer' }), options.signal))
217
+ throw Error('declined');
218
+ const approved = await target();
219
+ // Whole-screen consent binds the display; the first screenshot binds the input target.
220
+ if (approved.displayId !== baseline.displayId || approved.width !== baseline.width || approved.height !== baseline.height
221
+ || (config.macWindow && approved.target !== baseline.target))
222
+ throw Error('screen_changed');
223
+ options.signal.throwIfAborted();
224
+ options.beforeConnect?.();
225
+ await backend.connect();
226
+ const size = await backend.device.size();
227
+ if (size.width !== baseline.width || size.height !== baseline.height)
228
+ throw Error('screen_changed');
229
+ return guardComputerDevice(backend.device, target, { ...options, displayId: baseline.displayId,
230
+ maxSteps: config.maxSteps, budgetMs: config.budgetMs });
231
+ }
232
+ /** Midscene already maps screenshot centers to size() logical space; never scale them twice. */
233
+ export function computerSessionDevice(session, initial) {
234
+ let observation = initial;
235
+ return { interfaceType: 'computer', size: () => Promise.resolve({ width: observation.space.logical_width, height: observation.space.logical_height }),
236
+ screenshotBase64: async () => { observation = await session.observe(); return `data:${observation.image.media_type};base64,${observation.image.data_base64}`; },
237
+ actionSpace: () => session.actions().map(action => ({ ...action, call: async (params, context) => { await session.deviceAction(observation.id, action.name, params, context); } })) };
186
238
  }
187
239
  //# sourceMappingURL=computer-device.js.map
@@ -21,7 +21,8 @@ if (macWindow && (process.platform !== 'darwin' || !process.argv[5]))
21
21
  throw Error('invalid_configuration');
22
22
  const native = macWindow ? new MacNativeReader(process.argv[5], 'macos_gui') : undefined;
23
23
  let binding;
24
- const device = macWindow ? undefined : new ComputerDevice({ displayId, inputStrategy: 'sequential' });
24
+ let editorPoint;
25
+ const device = macWindow ? undefined : new ComputerDevice({ ...(displayId === 'primary' ? {} : { displayId }), inputStrategy: 'sequential', ...(process.platform === 'darwin' ? { keyboardDriver: 'libnut' } : {}) });
25
26
  const mouse = macWindow ? undefined : new (createRequire(import.meta.url)('@computer-use/libnut').DefaultMouseAction)();
26
27
  let queue = Promise.resolve();
27
28
  const input = createInterface({ input: process.stdin });
@@ -39,8 +40,14 @@ input.on('line', (line) => {
39
40
  const body = { ...macWindow, op: request.op, target: binding };
40
41
  if (request.op === 'Tap')
41
42
  Object.assign(body, { x: point?.[0], y: point?.[1], holdMs: clickHoldMs, focus: params?.focusLease?.focus, targetStarted: params?.focusLease?.targetStarted, clickGroup: params?.focusLease?.clickGroup });
42
- if (request.op === 'Input')
43
+ if (['Input', 'KeyboardPress'].includes(request.op) && editorPoint)
44
+ body.editorPoint = editorPoint;
45
+ if (['Input', 'KeyboardPress'].includes(request.op) && params?.expectedEditor)
46
+ body.expectedEditor = z.object({ role: z.string().max(100), value: z.string().max(400) }).strict().parse(params.expectedEditor);
47
+ if (request.op === 'Input') {
43
48
  body.value = params?.value;
49
+ body.mode = params?.mode === 'replace' ? 'replace' : 'append';
50
+ }
44
51
  if (request.op === 'KeyboardPress')
45
52
  body.keyName = params?.keyName;
46
53
  if (request.op === 'Scroll') {
@@ -55,9 +62,14 @@ input.on('line', (line) => {
55
62
  if (request.op === 'listDisplays')
56
63
  value = [{ id: displayId }];
57
64
  else {
65
+ if (request.op === 'Tap')
66
+ editorPoint = undefined;
58
67
  const result = await native.request(body);
68
+ if (request.op === 'Tap' && result.editor === true)
69
+ editorPoint = z.tuple([z.number().finite(), z.number().finite()]).parse(point);
59
70
  if (request.op === 'target' || request.op === 'connect') {
60
- if (result.keyWindowMatches !== true || typeof result.target !== 'string' || (binding !== undefined && result.target !== binding))
71
+ // Observation can bind a visible background window; native writes still require its AX key window.
72
+ if (typeof result.keyWindowMatches !== 'boolean' || typeof result.target !== 'string' || (binding !== undefined && result.target !== binding))
61
73
  throw Error('screen_changed');
62
74
  binding = result.target;
63
75
  }
@@ -112,12 +124,12 @@ input.on('line', (line) => {
112
124
  const action = device.actionSpace().find(item => item.name === request.op);
113
125
  if (!action || !['Input', 'Scroll', 'KeyboardPress'].includes(request.op))
114
126
  throw new Error('invalid action');
115
- await action.call(request.op === 'Input' ? { ...request.params, mode: 'typeOnly' } : request.params);
127
+ await action.call(request.op === 'Input' ? { ...request.params, mode: request.params.mode === 'replace' ? 'replace' : 'typeOnly' } : request.params);
116
128
  }
117
129
  process.stdout.write(JSON.stringify({ id: request.id, ok: true, value }) + '\n');
118
130
  }
119
- catch {
120
- process.stdout.write(JSON.stringify({ id: request.id, ok: false }) + '\n');
131
+ catch (error) {
132
+ process.stdout.write(JSON.stringify({ id: request.id, ok: false, ...(error instanceof Error && /^native_gui:[a-z_]{1,80}$/u.test(error.message) ? { detail: error.message } : {}), ...(error instanceof Error ? { error: error.message.replace(/\s+/gu, ' ').slice(0, 300) } : {}) }) + '\n');
121
133
  }
122
134
  }).catch(() => { process.exitCode = 1; process.exit(1); });
123
135
  });