@ensocode/server 0.3.3 → 0.3.4

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 (377) hide show
  1. package/README.md +10 -0
  2. package/out/node_modules/@earendil-works/pi-coding-agent/CHANGELOG.md +117 -0
  3. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/anthropic-messages-MGNURJ72.js +6 -0
  4. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{azure-openai-responses-FSC6BAW3.js → azure-openai-responses-4WDOP7MF.js} +1 -1
  5. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/bedrock-converse-stream.js +3 -3
  6. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-4KSTFUIK.js +19 -0
  7. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-4UNPP53I.js +55 -0
  8. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-CCYGJPSU.js +2 -0
  9. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-4EYXVSA5.js → chunk-FF6XOTWB.js} +9 -9
  10. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-FMPAMX2W.js +82 -0
  11. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
  12. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-C2WU32PX.js → chunk-H4W2F2IO.js} +1 -1
  13. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
  14. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-EOO47QGR.js → chunk-JLFZH7C6.js} +1 -1
  15. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-LCB5FO32.js +4 -0
  16. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-GN3QYODH.js → chunk-LQUBM7HF.js} +1 -1
  17. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-MABPTPMF.js +30 -0
  18. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-MPEFJ3RP.js +2 -0
  19. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-EBFHJFEE.js → chunk-PYBKJQVF.js} +1 -1
  20. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-VKJQ6CME.js +8 -0
  21. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-B46VJEHW.js → chunk-VUPOM3AH.js} +1 -1
  22. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-3TGLJEWK.js → chunk-WL4TUXY7.js} +1 -1
  23. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-V6KH5QG4.js → chunk-XM4MQFQV.js} +1 -1
  24. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-YZKQS34S.js → chunk-Y55SJART.js} +5 -1
  25. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
  26. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-ZKNSXGL5.js +1243 -0
  27. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{cli-MCOUW5WS.js → cli-35W4A75E.js} +7 -7
  28. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{cloudflare-workers-ai-system-one-WLAFJSP6.js → cloudflare-workers-ai-system-one-WKRH5HZA.js} +1 -1
  29. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/codemode-worker.js +2 -0
  30. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{easter-egg-3d-WMBNSJ4M.js → easter-egg-3d-GEVPKQF6.js} +1 -1
  31. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{execute-4CEBORGZ.js → execute-L2EEDV3L.js} +5 -3
  32. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/github-copilot.js +1 -1
  33. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-generative-ai-INGKNW72.js → google-generative-ai-VSMFCHJU.js} +1 -1
  34. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-vertex-IBTX6MBF.js → google-vertex-35UTLZJN.js} +1 -1
  35. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{llama-cpp-classify-V5U3QKXI.js → llama-cpp-classify-Z3SS4FP4.js} +1 -1
  36. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{mistral-conversations-S4OWXIXQ.js → mistral-conversations-LWJTUFIM.js} +1 -1
  37. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-codex-responses-YYIXDJWF.js +10 -0
  38. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-completions-EJNYB6IX.js → openai-completions-X2I4TQ2L.js} +3 -3
  39. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-decisions-IXI34BYG.js → openai-decisions-GG3FBAIF.js} +1 -1
  40. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-responses-5CX3GG6R.js +4 -0
  41. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openrouter-images-PISKSFMS.js → openrouter-images-WHNK2UQG.js} +1 -1
  42. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{pi-messages-NORUKF4E.js → pi-messages-5CXWY5I7.js} +1 -1
  43. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{runtime-FQB7RU7U.js → runtime-J5ZSBGTX.js} +1 -1
  44. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{typesafe-system-one-CHVC2UUI.js → typesafe-system-one-KA2SBSSD.js} +1 -1
  45. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/virtual-modules-7ZY53V4K.js +2 -0
  46. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli-runtime.js +1 -1
  47. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/index.js +1 -1
  48. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/rpc-entry.js +1 -1
  49. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/args.js +1 -1
  50. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-command.js +26 -2
  51. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-login.d.ts +15 -0
  52. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-login.js +232 -0
  53. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-logout.d.ts +14 -0
  54. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-logout.js +57 -0
  55. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-terminal.d.ts +17 -0
  56. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-terminal.js +63 -0
  57. package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/config-selector.js +3 -1
  58. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session-runtime.d.ts +5 -0
  59. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session-runtime.js +7 -0
  60. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.d.ts +25 -6
  61. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js +139 -50
  62. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/auth-storage.js +3 -2
  63. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/bash-executor.js +3 -1
  64. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/cache-warmer.d.ts +4 -37
  65. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/cache-warmer.js +11 -89
  66. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/utils.js +2 -1
  67. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/index.d.ts +1 -1
  68. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/loader.js +10 -5
  69. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.d.ts +1 -0
  70. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.js +9 -1
  71. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/types.d.ts +28 -6
  72. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/keybindings.d.ts +2 -2
  73. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/keybindings.js +1 -1
  74. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/mcp-servers.d.ts +12 -37
  75. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/mcp-servers.js +42 -121
  76. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-config.d.ts +52 -0
  77. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-resolver.js +20 -19
  78. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-runtime.d.ts +5 -0
  79. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-runtime.js +11 -4
  80. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/package-manager.d.ts +10 -1
  81. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/package-manager.js +50 -5
  82. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/pi-ai-schemas.d.ts +4 -0
  83. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/preferred-providers.d.ts +17 -0
  84. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/preferred-providers.js +24 -0
  85. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/prompt-templates.js +18 -2
  86. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/provider-composer.js +3 -1
  87. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/provider-matching.d.ts +6 -0
  88. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/provider-matching.js +8 -0
  89. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/radius-mcp.d.ts +13 -0
  90. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/radius-mcp.js +29 -0
  91. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/remote-catalog-provider.js +2 -0
  92. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/runtime-credentials.d.ts +8 -0
  93. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/runtime-credentials.js +15 -1
  94. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-defaults.d.ts +1 -1
  95. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-defaults.js +1 -1
  96. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/bash.js +35 -5
  97. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/edit-diff.d.ts +23 -14
  98. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/edit-diff.js +182 -41
  99. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/edit.js +8 -7
  100. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/find.js +82 -36
  101. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/grep.d.ts +5 -3
  102. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/grep.js +87 -75
  103. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/ls.js +2 -1
  104. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/powershell.js +15 -2
  105. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/read.d.ts +8 -0
  106. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/read.js +141 -25
  107. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/truncate.d.ts +4 -14
  108. package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/truncate.js +23 -29
  109. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/execute.js +4 -4
  110. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/tool.js +34 -12
  111. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.d.ts +2 -0
  112. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.js +23 -2
  113. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/ui.js +15 -3
  114. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/cli.d.ts +2 -0
  115. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/cli.js +49 -14
  116. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/config.js +4 -7
  117. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/index.js +4 -3
  118. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/oauth.d.ts +11 -49
  119. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/oauth.js +56 -319
  120. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/resources.d.ts +1 -1
  121. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/resources.js +4 -3
  122. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/runtime.d.ts +4 -3
  123. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/runtime.js +7 -5
  124. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/tools.d.ts +2 -23
  125. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/tools.js +6 -58
  126. package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/tool-search/tool.js +18 -6
  127. package/out/node_modules/@earendil-works/pi-coding-agent/dist/index.d.ts +1 -1
  128. package/out/node_modules/@earendil-works/pi-coding-agent/dist/main.js +46 -0
  129. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
  130. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/branch-summary-message.js +12 -4
  131. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/compaction-summary-message.d.ts +5 -1
  132. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/compaction-summary-message.js +12 -4
  133. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/custom-message.d.ts +5 -2
  134. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/custom-message.js +10 -3
  135. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/diff.js +11 -5
  136. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/extension-selector.js +9 -1
  137. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/login-dialog.js +1 -18
  138. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/mermaid.d.ts +2 -1
  139. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/mermaid.js +25 -20
  140. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/model-selector.js +14 -6
  141. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/oauth-selector.d.ts +10 -3
  142. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/oauth-selector.js +32 -5
  143. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/provider-brand.d.ts +14 -0
  144. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/provider-brand.js +66 -0
  145. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/radius-login-selector.d.ts +1 -2
  146. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/radius-login-selector.js +6 -37
  147. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
  148. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/skill-invocation-message.js +12 -4
  149. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tree-selector.d.ts +1 -0
  150. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tree-selector.js +19 -10
  151. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.d.ts +11 -1
  152. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.js +110 -63
  153. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js +4 -0
  154. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/print-mode.js +19 -10
  155. package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.js +53 -23
  156. package/out/node_modules/@earendil-works/pi-coding-agent/dist/package-manager-cli.js +39 -8
  157. package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/changelog.d.ts +2 -2
  158. package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/changelog.js +12 -6
  159. package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/image-resize.js +3 -1
  160. package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/terminal-question.d.ts +8 -0
  161. package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/terminal-question.js +24 -0
  162. package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/web-url.d.ts +12 -0
  163. package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/web-url.js +20 -0
  164. package/out/node_modules/@earendil-works/pi-coding-agent/docs/cli.md +14 -1
  165. package/out/node_modules/@earendil-works/pi-coding-agent/docs/extensions.md +27 -7
  166. package/out/node_modules/@earendil-works/pi-coding-agent/docs/keybindings.md +1 -1
  167. package/out/node_modules/@earendil-works/pi-coding-agent/docs/llama-cpp.md +4 -7
  168. package/out/node_modules/@earendil-works/pi-coding-agent/docs/models-configuration.md +6 -1
  169. package/out/node_modules/@earendil-works/pi-coding-agent/docs/models.md +2 -1
  170. package/out/node_modules/@earendil-works/pi-coding-agent/docs/prompt-templates.md +1 -1
  171. package/out/node_modules/@earendil-works/pi-coding-agent/docs/providers.md +1 -1
  172. package/out/node_modules/@earendil-works/pi-coding-agent/docs/rpc.md +4 -2
  173. package/out/node_modules/@earendil-works/pi-coding-agent/docs/settings.md +1 -1
  174. package/out/node_modules/@earendil-works/pi-coding-agent/docs/tui.md +1 -1
  175. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  176. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-anthropic/package.json +1 -1
  177. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  178. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/gondolin/package-lock.json +2 -2
  179. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/gondolin/package.json +1 -1
  180. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/plan-mode/index.ts +23 -13
  181. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/plan-mode/utils.ts +42 -16
  182. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/subagent/README.md +14 -11
  183. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/subagent/index.ts +392 -171
  184. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/with-deps/package-lock.json +2 -2
  185. package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/with-deps/package.json +1 -1
  186. package/out/node_modules/@earendil-works/pi-coding-agent/examples/tsconfig.json +63 -35
  187. package/out/node_modules/@earendil-works/pi-coding-agent/package.json +7 -7
  188. package/out/node_modules/@earendil-works/pi-coding-agent/schemas/models.schema.json +29 -0
  189. package/out/node_modules/@earendil-works/pi-coding-agent/schemas/settings.schema.json +1 -1
  190. package/out/phone/assets/{abnfDiagram-VCTEODGH-CLgfII9z.js → abnfDiagram-VCTEODGH-6JYofuK8.js} +1 -1
  191. package/out/phone/assets/architecture-7GRP2DOG-D7mwyuxS.js +1 -0
  192. package/out/phone/assets/{architectureDiagram-5GKGNRK7-I2RDn32D.js → architectureDiagram-5GKGNRK7-BeLeAQB1.js} +1 -1
  193. package/out/phone/assets/{blockDiagram-I7D4REHJ-D5xNQZkS.js → blockDiagram-I7D4REHJ-uXn3vhT2.js} +1 -1
  194. package/out/phone/assets/{c4Diagram-7LVT6UL2-CRKpzdlA.js → c4Diagram-7LVT6UL2-CjzMFRll.js} +1 -1
  195. package/out/phone/assets/channel-BsGN1oT0.js +1 -0
  196. package/out/phone/assets/{chunk-4HAMMTFA-CcezrqKz.js → chunk-4HAMMTFA-BA8HaYy2.js} +1 -1
  197. package/out/phone/assets/{chunk-75Z2AOVW-DDCXp4y1.js → chunk-75Z2AOVW-BhIfO9es.js} +1 -1
  198. package/out/phone/assets/{chunk-DU6HZSFF-CjWveEkB.js → chunk-DU6HZSFF-BTLBHwj-.js} +1 -1
  199. package/out/phone/assets/{chunk-F27PBJKO-Bgl_xI02.js → chunk-F27PBJKO-CUw8NZk8.js} +1 -1
  200. package/out/phone/assets/{chunk-GMAD6QVW-EmL8nOme.js → chunk-GMAD6QVW-bZOKnRyM.js} +1 -1
  201. package/out/phone/assets/{chunk-GVQU2GXP-Dox_nphF.js → chunk-GVQU2GXP-B0WIm1dS.js} +1 -1
  202. package/out/phone/assets/{chunk-IMKFNOWR-BapGpI4S.js → chunk-IMKFNOWR-DWND4rEr.js} +1 -1
  203. package/out/phone/assets/{chunk-L3NEJ4N5-Cq_UZI8A.js → chunk-L3NEJ4N5-DgMknY3k.js} +1 -1
  204. package/out/phone/assets/{chunk-OSK3NFVY-2VVlErAd.js → chunk-OSK3NFVY-C5aEouov.js} +1 -1
  205. package/out/phone/assets/{chunk-P2QGCYS3-Cci-G-p1.js → chunk-P2QGCYS3-D2ID3RxV.js} +1 -1
  206. package/out/phone/assets/{chunk-POPQ4Y6H-CJ47EOfE.js → chunk-POPQ4Y6H-C1lOuNpV.js} +1 -1
  207. package/out/phone/assets/{chunk-PWAF6VOD-D9dLdFqC.js → chunk-PWAF6VOD-CfqWQZRE.js} +1 -1
  208. package/out/phone/assets/{chunk-SHT3W25Y-BlGSiWZn.js → chunk-SHT3W25Y-p37Dlvn4.js} +1 -1
  209. package/out/phone/assets/{chunk-SVP7TREG-C0zdsa_A.js → chunk-SVP7TREG-CSSqW-zb.js} +1 -1
  210. package/out/phone/assets/{chunk-TICWLB2K-DAQW8nQU.js → chunk-TICWLB2K-Bse5ne4b.js} +1 -1
  211. package/out/phone/assets/classDiagram-ZZMXUADV-a1PUvjC2.js +1 -0
  212. package/out/phone/assets/classDiagram-v2-VYDZK3BY-a1PUvjC2.js +1 -0
  213. package/out/phone/assets/{cynefin-OW5HDTMX-_zsx5mdV.js → cynefin-OW5HDTMX-BGQqPhYk.js} +1 -1
  214. package/out/phone/assets/{cynefinDiagram-5FMLGOSQ-Cww-w0ex.js → cynefinDiagram-5FMLGOSQ-Cz3XWaxY.js} +1 -1
  215. package/out/phone/assets/{dagre-GXQ25YYZ-C0i7DPqX.js → dagre-GXQ25YYZ-CjAF6lSz.js} +1 -1
  216. package/out/phone/assets/desk-1McWacjU.js +2 -0
  217. package/out/phone/assets/{diagram-S7CK7UJ4-Bx-G5hYz.js → diagram-S7CK7UJ4-B135cp5a.js} +1 -1
  218. package/out/phone/assets/{diagram-UQ7AKVKN-DaTblkjV.js → diagram-UQ7AKVKN-C4pCe0fQ.js} +1 -1
  219. package/out/phone/assets/{diagram-VSXAHHWV-gmN2e1b4.js → diagram-VSXAHHWV-CYkCrin2.js} +1 -1
  220. package/out/phone/assets/{diagram-VX7I27RA-WYtRtOo8.js → diagram-VX7I27RA-CT_vufh_.js} +1 -1
  221. package/out/phone/assets/{diagram-Z3DM3KII-Cr6uUB5B.js → diagram-Z3DM3KII-XEkkXu3P.js} +1 -1
  222. package/out/phone/assets/{ebnfDiagram-PWID7BFC-BCicfvpA.js → ebnfDiagram-PWID7BFC-DfLyeXjw.js} +1 -1
  223. package/out/phone/assets/{erDiagram-RLTQ6QDP-B3QlJvfQ.js → erDiagram-RLTQ6QDP-pKNbKkAP.js} +1 -1
  224. package/out/phone/assets/eventmodeling-NTZA5JFV-DcUsfQiW.js +1 -0
  225. package/out/phone/assets/flowDiagram-HODETNUW-sUobw8zi.js +1 -0
  226. package/out/phone/assets/{ganttDiagram-EL5Y4UJY-LYy2mfCh.js → ganttDiagram-EL5Y4UJY-Df4E50Mj.js} +1 -1
  227. package/out/phone/assets/{gitGraph-4MIJSDKK-dT22Z2jG.js → gitGraph-4MIJSDKK-CkjzZeFD.js} +1 -1
  228. package/out/phone/assets/{gitGraphDiagram-WWUBYQGX-DHNdY57l.js → gitGraphDiagram-WWUBYQGX-CBxfRAfy.js} +1 -1
  229. package/out/phone/assets/{info-A6RAGUB7-nIu8NSOs.js → info-A6RAGUB7-CHFXa2pw.js} +1 -1
  230. package/out/phone/assets/{infoDiagram-27XIBGKW-DGkWZIMT.js → infoDiagram-27XIBGKW-K0DnZhi4.js} +1 -1
  231. package/out/phone/assets/{ishikawaDiagram-5VMMS53U-C8EPXru-.js → ishikawaDiagram-5VMMS53U-DTQF2ZuR.js} +1 -1
  232. package/out/phone/assets/{journeyDiagram-3NMN7TZE-Dyd9L3l3.js → journeyDiagram-3NMN7TZE-wBltkU2i.js} +1 -1
  233. package/out/phone/assets/{kanban-definition-UXKFOSKX-DehTYcsL.js → kanban-definition-UXKFOSKX-BZpcOajP.js} +1 -1
  234. package/out/phone/assets/{line-Db4SulF4.js → line-BflnZFgp.js} +1 -1
  235. package/out/phone/assets/main-CnA1zWP8.css +1 -0
  236. package/out/phone/assets/main-Crtf_g8h.js +1643 -0
  237. package/out/phone/assets/{mermaid-parser.core-D7h_8WV8.js → mermaid-parser.core-BiCTmcqa.js} +3 -3
  238. package/out/phone/assets/{mermaid.core-Dw_E5kj4.js → mermaid.core-D3TwYaLF.js} +4 -4
  239. package/out/phone/assets/{mindmap-definition-YA3MSWOX-_5Mxqxsy.js → mindmap-definition-YA3MSWOX-Cz0aS_6Y.js} +1 -1
  240. package/out/phone/assets/{packet-AYTQ26CC-_cgeMDdN.js → packet-AYTQ26CC-DW-djbhd.js} +1 -1
  241. package/out/phone/assets/{pegDiagram-XKGWAZYB-BhBwaNEr.js → pegDiagram-XKGWAZYB-CE0sZZAE.js} +1 -1
  242. package/out/phone/assets/{pie-WAS4IAKB-BepY80_0.js → pie-WAS4IAKB-CKGFlXok.js} +1 -1
  243. package/out/phone/assets/{pieDiagram-E7YTZNPT-CQQgqmI8.js → pieDiagram-E7YTZNPT-BrnQ32_6.js} +1 -1
  244. package/out/phone/assets/{quadrantDiagram-AXDQQJYC-DEEatC1J.js → quadrantDiagram-AXDQQJYC-BrxDAygB.js} +1 -1
  245. package/out/phone/assets/{radar-RG4KPBEZ-BqsiI_qQ.js → radar-RG4KPBEZ-Bo2f5QyA.js} +1 -1
  246. package/out/phone/assets/{railroad-74A4TZTK-C_2pEUjD.js → railroad-74A4TZTK-BZEmm0Ha.js} +1 -1
  247. package/out/phone/assets/railroad-abnf-HS5TGJTU-CGiIT1ZV.js +1 -0
  248. package/out/phone/assets/railroad-ebnf-LZEXJU2U-C85Q3c0J.js +1 -0
  249. package/out/phone/assets/railroad-peg-WCYAUIDC-8qPPCLgU.js +1 -0
  250. package/out/phone/assets/{railroadDiagram-O6MQD6OU-B7786u7W.js → railroadDiagram-O6MQD6OU-BvOyUNMC.js} +1 -1
  251. package/out/phone/assets/{requirementDiagram-BXWQKSXE-Ci3b5uwm.js → requirementDiagram-BXWQKSXE-T42N3TW5.js} +1 -1
  252. package/out/phone/assets/{sankeyDiagram-P5KCCOFB-PwT2gJjH.js → sankeyDiagram-P5KCCOFB-0us9ErVV.js} +1 -1
  253. package/out/phone/assets/{sequenceDiagram-WJ2MYXX4-H6sgB5RI.js → sequenceDiagram-WJ2MYXX4-BMcYh2ll.js} +1 -1
  254. package/out/phone/assets/{stateDiagram-D77RDMKH-BxyRe7OB.js → stateDiagram-D77RDMKH-CgP9dUc3.js} +1 -1
  255. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-WM4CNSf-.js +1 -0
  256. package/out/phone/assets/storage-CahQ0cyN.js +1 -0
  257. package/out/phone/assets/{swimlanes-42K2YHIH-DWT3f1Hk.js → swimlanes-42K2YHIH-VnE4ceCW.js} +1 -1
  258. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-65AiMWVp.js +8 -0
  259. package/out/phone/assets/{timeline-definition-24CTP7MA-D67esSVY.js → timeline-definition-24CTP7MA-tH3izgae.js} +1 -1
  260. package/out/phone/assets/{treeView-Q6P3EWNA-BTIfu3Qr.js → treeView-Q6P3EWNA-CVFDOC7i.js} +1 -1
  261. package/out/phone/assets/{treemap-WGGIJYW6-DkPf6LQc.js → treemap-WGGIJYW6-vmikHzt3.js} +1 -1
  262. package/out/phone/assets/{vennDiagram-4TSXK5OY-DRMRxJ4f.js → vennDiagram-4TSXK5OY-b8ttDCR-.js} +1 -1
  263. package/out/phone/assets/{wardley-WFR3VGLG-hOvC_8-W.js → wardley-WFR3VGLG-D32vKoC1.js} +1 -1
  264. package/out/phone/assets/{wardleyDiagram-VM6X3IG4-a5aYRgrw.js → wardleyDiagram-VM6X3IG4-CMkaIPVH.js} +1 -1
  265. package/out/phone/assets/{xychartDiagram-S5SC5T6Z-DXjoRFDL.js → xychartDiagram-S5SC5T6Z-pLYDcql3.js} +1 -1
  266. package/out/phone/desk.html +2 -2
  267. package/out/phone/index.html +3 -3
  268. package/out/renderer/assets/{abnfDiagram-VCTEODGH-DhskujJf.js → abnfDiagram-VCTEODGH-N6OiVFQx.js} +1 -1
  269. package/out/renderer/assets/{arc-BcW67t47.js → arc-CXVc3U0J.js} +1 -1
  270. package/out/renderer/assets/{architectureDiagram-5GKGNRK7-D-x057Ia.js → architectureDiagram-5GKGNRK7-BT5CXpcQ.js} +1 -1
  271. package/out/renderer/assets/{blockDiagram-I7D4REHJ-DR3sZkhW.js → blockDiagram-I7D4REHJ-C32Vqzip.js} +1 -1
  272. package/out/renderer/assets/{c4Diagram-7LVT6UL2-CQ4lScWs.js → c4Diagram-7LVT6UL2-qjwL2BP8.js} +1 -1
  273. package/out/renderer/assets/channel-B1Cv56hA.js +1 -0
  274. package/out/renderer/assets/{chunk-2Q5K7J3B-CtT0yqF3.js → chunk-2Q5K7J3B-YC6CQiyD.js} +1 -1
  275. package/out/renderer/assets/{chunk-5VM5RSS4-DlCfddrY.js → chunk-5VM5RSS4-E-kluPz3.js} +1 -1
  276. package/out/renderer/assets/{chunk-F27PBJKO-BAJ5dGzo.js → chunk-F27PBJKO-Bhx1_P75.js} +1 -1
  277. package/out/renderer/assets/{chunk-IMKFNOWR-Dlah_YbP.js → chunk-IMKFNOWR-Dgb_730B.js} +1 -1
  278. package/out/renderer/assets/{chunk-JWPE2WC7-BiXd3nUZ.js → chunk-JWPE2WC7-COQNHw4u.js} +1 -1
  279. package/out/renderer/assets/{chunk-POPQ4Y6H-Ch86i4EJ.js → chunk-POPQ4Y6H-CQz4hRgP.js} +1 -1
  280. package/out/renderer/assets/{chunk-SVP7TREG-z3inDV-H.js → chunk-SVP7TREG-DGp9XQFd.js} +1 -1
  281. package/out/renderer/assets/{chunk-TICWLB2K-B34A2AKD.js → chunk-TICWLB2K-CovR1uHr.js} +1 -1
  282. package/out/renderer/assets/{chunk-XXDRQBXY-Do_L0wRR.js → chunk-XXDRQBXY-gVmqSU5b.js} +1 -1
  283. package/out/renderer/assets/classDiagram-ZZMXUADV-CDWgELaf.js +1 -0
  284. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-CDWgELaf.js +1 -0
  285. package/out/renderer/assets/{cose-bilkent-JH36ORCC-BQraKmgl.js → cose-bilkent-JH36ORCC-DD4PEqt_.js} +1 -1
  286. package/out/renderer/assets/{cynefin-OW5HDTMX-BwixoR4r.js → cynefin-OW5HDTMX-DNsYCrBx.js} +1 -1
  287. package/out/renderer/assets/{cynefinDiagram-5FMLGOSQ-BLTBma3J.js → cynefinDiagram-5FMLGOSQ-CoSzqs25.js} +1 -1
  288. package/out/renderer/assets/{cytoscape-fcose-BRpJ5tyq.js → cytoscape-fcose-CV0MpCmk.js} +1 -1
  289. package/out/renderer/assets/{dagre-GXQ25YYZ-aWsjA_wn.js → dagre-GXQ25YYZ-BxpTPeHN.js} +1 -1
  290. package/out/renderer/assets/{diagram-S7CK7UJ4-Cur2zK4q.js → diagram-S7CK7UJ4-Df_OM1vW.js} +1 -1
  291. package/out/renderer/assets/{diagram-UQ7AKVKN-DlrY8YcD.js → diagram-UQ7AKVKN-iovjmny_.js} +1 -1
  292. package/out/renderer/assets/{diagram-VSXAHHWV-BBdjreqR.js → diagram-VSXAHHWV-BMrwlcQx.js} +1 -1
  293. package/out/renderer/assets/{diagram-VX7I27RA-XiWMdc8S.js → diagram-VX7I27RA-DqLh449X.js} +1 -1
  294. package/out/renderer/assets/{diagram-Z3DM3KII-CBB5leat.js → diagram-Z3DM3KII-CH_W77UO.js} +1 -1
  295. package/out/renderer/assets/{ebnfDiagram-PWID7BFC-nl8RPo8j.js → ebnfDiagram-PWID7BFC-yjzodXoL.js} +1 -1
  296. package/out/renderer/assets/{erDiagram-RLTQ6QDP-C_oaG80x.js → erDiagram-RLTQ6QDP-DXxhvHYS.js} +1 -1
  297. package/out/renderer/assets/{flowDiagram-HODETNUW-nDoVZFS7.js → flowDiagram-HODETNUW-b2AWCAaB.js} +1 -1
  298. package/out/renderer/assets/{ganttDiagram-EL5Y4UJY-DOrcuM3Q.js → ganttDiagram-EL5Y4UJY-COkyXL3K.js} +1 -1
  299. package/out/renderer/assets/{gitGraphDiagram-WWUBYQGX-D_DB3jro.js → gitGraphDiagram-WWUBYQGX-BYPqy5fh.js} +1 -1
  300. package/out/renderer/assets/globals-DX-8GWfJ.css +1 -0
  301. package/out/renderer/assets/{globals-D1ocHHQV.js → globals-y5_C1IiJ.js} +182 -176
  302. package/out/renderer/assets/index-CHJ6mVl2.js +117 -0
  303. package/out/renderer/assets/{infoDiagram-27XIBGKW-BbBrANxo.js → infoDiagram-27XIBGKW-DNg-VxlH.js} +1 -1
  304. package/out/renderer/assets/{ishikawaDiagram-5VMMS53U-7UlfWlWV.js → ishikawaDiagram-5VMMS53U-DProTI6a.js} +1 -1
  305. package/out/renderer/assets/{journeyDiagram-3NMN7TZE-CJP9bosH.js → journeyDiagram-3NMN7TZE-BWhC4n3f.js} +1 -1
  306. package/out/renderer/assets/{kanban-definition-UXKFOSKX-D772kW7T.js → kanban-definition-UXKFOSKX-CHJRR0qi.js} +1 -1
  307. package/out/renderer/assets/{layout-BzVfJEvx.js → layout-D8t6q8k0.js} +1 -1
  308. package/out/renderer/assets/{linear-DBjhr05m.js → linear-Cxb1p4iF.js} +1 -1
  309. package/out/renderer/assets/{mermaid.core-CJpNSowm.js → mermaid.core-CFNOEUmc.js} +5 -5
  310. package/out/renderer/assets/{mindmap-definition-YA3MSWOX-C2oqlH5E.js → mindmap-definition-YA3MSWOX-Ba78cyY4.js} +1 -1
  311. package/out/renderer/assets/{pegDiagram-XKGWAZYB-CcZ8Hae-.js → pegDiagram-XKGWAZYB-C7zqoWMk.js} +1 -1
  312. package/out/renderer/assets/{pieDiagram-E7YTZNPT-DTw-_k2D.js → pieDiagram-E7YTZNPT-g304yFeX.js} +1 -1
  313. package/out/renderer/assets/{quadrantDiagram-AXDQQJYC-D5eX0DO7.js → quadrantDiagram-AXDQQJYC-Bwn3gGTO.js} +1 -1
  314. package/out/renderer/assets/{railroadDiagram-O6MQD6OU-DzpBB_Re.js → railroadDiagram-O6MQD6OU-DRetS8pv.js} +1 -1
  315. package/out/renderer/assets/{requirementDiagram-BXWQKSXE-UbOUXLgl.js → requirementDiagram-BXWQKSXE-CHz0FVZ7.js} +1 -1
  316. package/out/renderer/assets/{sankeyDiagram-P5KCCOFB-jRbXLLsa.js → sankeyDiagram-P5KCCOFB-BYGRDIG9.js} +1 -1
  317. package/out/renderer/assets/{sequenceDiagram-WJ2MYXX4-s0WBQQPf.js → sequenceDiagram-WJ2MYXX4-B60RuFFk.js} +1 -1
  318. package/out/renderer/assets/settings-Cd128yRb.js +34 -0
  319. package/out/renderer/assets/{sizeCapture-INFHLROL-DvUs5rDx.js → sizeCapture-INFHLROL-CB-i3Fmz.js} +1 -1
  320. package/out/renderer/assets/{stateDiagram-D77RDMKH-C1_V497y.js → stateDiagram-D77RDMKH-CJOcikAJ.js} +1 -1
  321. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-BosPi5SR.js +1 -0
  322. package/out/renderer/assets/{swimlanes-42K2YHIH-BulPeZ6y.js → swimlanes-42K2YHIH-Buap2upT.js} +1 -1
  323. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-B7TQEEbL.js +8 -0
  324. package/out/renderer/assets/{timeline-definition-24CTP7MA-gQ5OygZn.js → timeline-definition-24CTP7MA-BdQta3QT.js} +1 -1
  325. package/out/renderer/assets/{vennDiagram-4TSXK5OY-A8QyA5Ix.js → vennDiagram-4TSXK5OY-BynM2l28.js} +1 -1
  326. package/out/renderer/assets/{wardleyDiagram-VM6X3IG4-CfP6E41T.js → wardleyDiagram-VM6X3IG4-FZjDO9FY.js} +1 -1
  327. package/out/renderer/assets/{xychartDiagram-S5SC5T6Z-DTG5UHh7.js → xychartDiagram-S5SC5T6Z-pJPSISxM.js} +1 -1
  328. package/out/renderer/index.html +3 -3
  329. package/out/renderer/plugin-view.html +39 -0
  330. package/out/renderer/settings.html +4 -4
  331. package/out/renderer/web-preload.js +1 -1
  332. package/out/server/agent.js +1502 -370
  333. package/out/server/chunks/{agent-BhQn6jGA.js → agent--Q7N17bY.js} +356 -165
  334. package/out/server/chunks/{gpuBackendInstall-CdExgjGi.js → gpuBackendInstall-P7COXJlD.js} +6 -5
  335. package/out/server/chunks/{loadProvider-BnkyjMSW.js → loadProvider-DvvFIF6F.js} +2 -2
  336. package/out/server/chunks/{manifest-2odvnxjZ.js → manifest-BvEa5QR3.js} +125 -5
  337. package/out/server/chunks/{workflowPresets-DqSsjOj6.js → workflowPresets-CuLnfQqa.js} +3444 -448
  338. package/out/server/index.js +2719 -308
  339. package/out/server/plugin-host.js +7 -3
  340. package/package.json +7 -7
  341. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/anthropic-messages-BWGCKOF4.js +0 -6
  342. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-44DLKSKE.js +0 -1234
  343. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-62VOPMLK.js +0 -65
  344. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-7O7QKK6A.js +0 -2
  345. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-CHWNPHIS.js +0 -82
  346. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-NL4X6LBY.js +0 -4
  347. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-NZY7EIPA.js +0 -4
  348. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-R2EGYMOO.js +0 -7
  349. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
  350. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
  351. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-VOLAXWGI.js +0 -2
  352. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-codex-responses-QAWLOQSN.js +0 -10
  353. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-responses-MD3562FB.js +0 -4
  354. package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/virtual-modules-O76XM3OB.js +0 -2
  355. package/out/phone/assets/architecture-7GRP2DOG-CQOPTv6S.js +0 -1
  356. package/out/phone/assets/channel-DdXebl9x.js +0 -1
  357. package/out/phone/assets/classDiagram-ZZMXUADV-BCctWEp1.js +0 -1
  358. package/out/phone/assets/classDiagram-v2-VYDZK3BY-BCctWEp1.js +0 -1
  359. package/out/phone/assets/desk-mfuEW2n4.js +0 -2
  360. package/out/phone/assets/eventmodeling-NTZA5JFV-BtfapP6M.js +0 -1
  361. package/out/phone/assets/flowDiagram-HODETNUW-BsyiyBtD.js +0 -1
  362. package/out/phone/assets/main-Dv9ve8mT.css +0 -1
  363. package/out/phone/assets/main-uMMbioCA.js +0 -1638
  364. package/out/phone/assets/railroad-abnf-HS5TGJTU-TmODpceI.js +0 -1
  365. package/out/phone/assets/railroad-ebnf-LZEXJU2U-BTCjNR9u.js +0 -1
  366. package/out/phone/assets/railroad-peg-WCYAUIDC-DjhKNo8j.js +0 -1
  367. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-Cncmf_cL.js +0 -1
  368. package/out/phone/assets/storage-D9RW_4__.js +0 -1
  369. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-DAahG4fH.js +0 -8
  370. package/out/renderer/assets/channel-CudRig7z.js +0 -1
  371. package/out/renderer/assets/classDiagram-ZZMXUADV-DL20WkD0.js +0 -1
  372. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-DL20WkD0.js +0 -1
  373. package/out/renderer/assets/globals-Bkw7iiQG.css +0 -1
  374. package/out/renderer/assets/index-Cm5iq85v.js +0 -117
  375. package/out/renderer/assets/settings-DxYo7s4h.js +0 -34
  376. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-C9dfLXR8.js +0 -1
  377. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-LXwy6qGO.js +0 -8
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import fs, { readFileSync, mkdirSync, existsSync, writeFileSync, chmodSync, realpathSync, statSync, renameSync, rmSync, copyFileSync, readdirSync, createReadStream, openSync, readSync, closeSync, appendFileSync, fstatSync, writeSync, lstatSync, unlinkSync, watch, rmdirSync, accessSync, constants as constants$2 } from "node:fs";
3
- import { isIP, createConnection, createServer as createServer$1 } from "node:net";
2
+ import fs, { readFileSync, mkdirSync, existsSync, writeFileSync, chmodSync, realpathSync, statSync, renameSync, rmSync, copyFileSync, readdirSync, mkdtempSync, createReadStream, openSync, readSync, closeSync, watch, appendFileSync, fstatSync, writeSync, lstatSync, unlinkSync, rmdirSync, accessSync, constants as constants$2 } from "node:fs";
3
+ import { createServer, isIP, createConnection } from "node:net";
4
4
  import path, { join, resolve, dirname, basename as basename$1, relative, isAbsolute, sep, extname } from "node:path";
5
5
  import { createInterface } from "node:readline";
6
6
  import { fork, execFile, execFileSync, spawn, spawnSync } from "node:child_process";
7
- import { createDecipheriv, randomBytes, createCipheriv, randomUUID, createHash, verify, createPublicKey } from "node:crypto";
7
+ import { createDecipheriv, randomBytes, createCipheriv, randomUUID, createHash, timingSafeEqual, verify, createPublicKey } from "node:crypto";
8
8
  import { EventEmitter } from "node:events";
9
9
  import os, { homedir, tmpdir, userInfo } from "node:os";
10
- import { K as APPROVAL_MODES$1, T as THINKING_LEVELS, L as ENSO_LOCKED_PROFILE_ID, n as isSameChildSessionIdentity, N as parseChildConversationMetadata, y as isClassifierOnlyProvider, z as isOauthAccountPool, O as eligibleOauthPoolAccountKeys, e as isCodexAccountKey, Q as isEditMode, R as normalizeSshTimeoutSeconds, B as resolveEditMode, U as CLAUDE_HOOK_EVENTS, V as isReservedAgentTypeName, W as BUILTIN_AGENT_TYPES, X as isPluginEntry, Y as PLUGIN_HOST_APIS, J as pluginToolName, Z as PLUGIN_INJECT_MAX_CHARS, _ as parsePluginInjectImages, $ as isHostPluginEvent, a0 as parsePluginToolName, a1 as initialInterceptState, h as isChildInterceptEvent, a2 as CHILD_INTERCEPT_TOTAL_TIMEOUT_MS, a3 as INTERCEPT_TOTAL_TIMEOUT_MS, a4 as CHILD_INTERCEPT_TIMEOUT_MS, a5 as INTERCEPT_TIMEOUT_MS, a6 as applyInterceptResult, a7 as failClosedResult, a8 as OBSERVE_TIMEOUT_MS, a9 as BEFORE_COMPACT_TIMEOUT_MS, aa as PLUGIN_PROGRESS_MAX_CHARS, ab as MCP_TRANSPORTS, ac as parsePrivacyMaskRecord, H as PRIVACY_MASK_ENTRY, ad as hasProviderCredentials, c as MODEL_REASONING_OVERRIDES, d as MODEL_THINKING_LEVEL_OVERRIDES, ae as buildAgentTypeRegistrySnapshot, af as visibleMemberAgentTypes, ag as ENSO_AGENT_TYPE_KEY, E as ENSO_LOCKED_PROFILE, p as parseApprovalAllowThreshold, ah as DEFAULT_APPROVAL_ALLOW_THRESHOLD, ai as resolveShellLimits, aj as parseWebSearchChain, ak as parseWindowsLocalShell, o as resolveCompactStrategy, al as parseSmartCompactMode, am as parseAgentWorkerEvent, an as DEFAULT_PRESET_ID, ao as normalizeMaxActiveCoworkers, ap as normalizeAutoRetryLimit, aq as parsePrivacyMaskSettings, ar as parseDisabledWorkflowPresets, as as resolveImageGenerationConfig, at as AGENT_WAIT_DEFAULT_MS, au as AGENT_WAIT_MAX_MS, g as isUuid, av as isDeliveryId, v as splitPlanPrefix, aw as parseChildSessionIdentity, ax as LOCAL_IMAGE_SCHEME, ay as REMOTE_FETCH_HOST, az as BOT_AVATAR_HOST, aA as PLUGIN_ASSET_HOST, aB as mediaExtension, aC as localImageUrlToPath, aD as isMediaPath, aE as isVideoPath, aF as IMAGE_EXTENSIONS$1, aG as withVersionSegment, aH as DEFAULT_BASE_URLS, aI as parseCapabilityAskResponse, aJ as parseCreateConversationAuthorityRequest, aK as parseConversationAuthorityRequest, aL as parseUpdateConversationSelectionRequest, aM as parseTitleSummaryInput, aN as parseParentSourceBindingRequest, aO as parseParentModelSelectionRequest, aP as parseAgentDispatchRequest, aQ as isApprovalDecision, I as parseAgentCommand, F as EMPTY_PLAN_STATE, aR as TITLE_SUMMARY_MAX_CANDIDATES, aS as parseCreateProjectAuthorityRequest, aT as parseSelectProjectAuthorityRequest, aU as parseRemoveProjectAuthorityRequest, aV as parseStartOauthWizardRequest, aW as parseOauthFlowPromptResponse, aX as parseOauthFlowControlRequest } from "./chunks/agent-BhQn6jGA.js";
11
- import { bp as isMediaId, bq as isVirtualRef, br as findVirtualModel, Y as takeSnapshotTail, bs as syncAccountProviders, bt as expandOauthCatalog, bu as supportsMultipleAccounts, b9 as ANTIGRAVITY_PROVIDER_ID, ba as antigravityProviderConfig, bb as DEVIN_PROVIDER_ID, bc as devinProviderConfig, bd as installCodexLinkedRefresh, aj as providerIdOfAccountKey, bv as ordinalOfAccountKey, bw as nextAccountKey, X as ensureAccountProvider, bx as sanitizeUpstreamBody, by as parseAntigravityApiKey, bz as fetchAntigravityUsage, bA as fetchDevinUsage, bB as sanitizeOauthLabel, bC as parseCodexAuthJson, bD as CODEX_PROVIDER_ID, bE as defaultCodexAuthPath, bF as DEFAULT_PERSONA_PROMPT, aW as WORKSPACE_WRITE_TOOL_ID, bG as resolveDisabledBuiltinTools, bH as projectDisabledBuiltinTools, bI as startOauthCallbackServer, Q as mcpOAuthFingerprint, N as MCP_OAUTH_REFRESH_SKEW_MS, F as parseModelDirectorySnapshot, bJ as persistedSettingsState, bK as childProfileToolIds, bg as ENSO_SYSTEM_PROMPT, a0 as childProfileShell, bL as directMemberRef, p as providerKeyFor, bM as materializeProviders, bN as classifierProviderFor, bO as classifierBaseUrlFor, bP as parseVirtualModels, V as VIRTUAL_PROVIDER_ID, bQ as mcpTimeoutsForSpawn, bR as pickModelCapabilityOverrides, bS as canBeVirtualMember, aM as parseJsonFromAssistant, aN as validateAgainstSchema, ap as HUMAN_REQUEST_TIMEOUT_MS, bT as UNIT_TYPES, bU as DEDUP_MIN_CHARS, bV as DEFAULT_IMPORTANCE, bW as DEFAULT_UNIT_TYPE, bX as isEvolvesRelation, bY as DEDUP_MAX, bZ as DEDUP_VECTOR, b_ as CRYSTAL_MIN_SOURCES, b$ as DISTILL_MAX_OUTPUT_TOKENS, c0 as DISTILL_MIN_IMPORTANCE, c1 as DISTILL_MAX_CHUNK_CHARS, c2 as DISTILL_SINGLE_EXTRACT_MAX_TOKENS, c3 as DISTILL_EXTRACT_MAX_TOKENS, c4 as DISTILL_CONSOLIDATE_MAX_TOKENS, c5 as isUnitType, c6 as DISTILL_MAX_ATTEMPTS, c7 as KG_MAX_LABEL_CHARS, c8 as KG_MAX_ENTITY_NAME_CHARS, c9 as KG_MAX_DESCRIPTION_CHARS, ca as KG_MAX_ENTITIES, cb as KG_MAX_RELATIONS, cc as KG_EXTRACT_MAX_TOKENS, cd as KG_DEFAULT_RELATION_TYPE, ce as KG_DEFAULT_ENTITY_TYPE, cf as KG_MAX_ATTEMPTS, cg as MIN_FLOOR, ch as IMP_MULT, ci as RECENCY_W, cj as FREQUENCY_W, ck as FREQUENCY_MAX_COUNT, cl as HALF_LIFE_DAYS, cm as RRF_K, cn as DECAY_WEIGHT, co as TEMPORAL_YEAR_BOOST, cp as CRYSTAL_BOOST, cq as MMR_LAMBDA, cr as parseMemorySearchRequest, cs as parseMemoryCaptureRequest, ct as parseMemoryCrystallizeRequest, cu as parseMemoryDeleteRequest, cv as effectiveDisabledBuiltinTools, cw as SNAPSHOT_TAIL_MESSAGES, b3 as splitUnattendedPrefix, cx as userTextWithoutSkills, cy as withPrivacyMask, cz as withUserEntryIds, W as projectMessage, cA as resolveSshTarget, cB as checkPassed, cC as checkFailureText, a9 as SEND_IMAGE_CAPTION_MAX, cD as parseVirtualClassifier, cE as VIRTUAL_CLASSIFIER_DEFAULT_TIMEOUT_MS, aR as buildInitialTitleUserText, aT as TITLE_SYSTEM_PROMPT, aL as buildTurnDigest, aS as ROLLING_TITLE_SYSTEM_PROMPT, aQ as buildRollingTitleUserText, b2 as titleSummaryTimeoutMs, aU as extractTitle, aV as titleRejectReason, ab as sendImageItems, a5 as CAPABILITY_CATALOG, cF as CAPABILITY_HANDLER_CONTRACT, cG as BUILTIN_TOOLS, cH as TERMINAL_SHELLS, cI as parseAccentColor, cJ as positiveFiniteNumber, T as isXaiChatModelId, cK as mergeFetchedOauthModels, G as findCatalogModelById, cL as supportedProjectThinkingLevels, cM as buildSshExecArgs, cN as buildRemoteCommand, bo as sshPasswordEnv, s as shellQuote, cO as effectiveSubagentAllowedModes, aZ as EnsoSafeJournal, ay as createComputerTool, aF as ComputerInvoker, cP as codemodeToolSnapshot, aB as createTaskTools, aw as createMemoryTools, aD as MemoryInvoker, a_ as createWebTools, au as createBrowserTools, as as createUnifiedSubagentTool, aC as BrowserInvoker, aH as createAskTool, aG as AskManager, b1 as createSubmitPlanTool, a$ as createTodoTool, f as estimateSkillTokens, g as estimateInstructionTokens, cQ as estimateToolsTotal, b8 as createProjectSettingsManager, b4 as resolveHarnessSkillRoots, M as assignMcpToolNames, aA as listWorkflowPresets, at as workflowPresetRoots, cR as listCustomWorkflowPresets, cS as listBuiltinWorkflowPresets, cT as readCustomWorkflowPreset, cU as parseWorkflowPresetDraft, cV as saveCustomWorkflowPreset, cW as deleteCustomWorkflowPreset, al as createSshExecutor, cX as resolveTerminalShellFile, cY as isHumanRequestTimeout, cZ as listProjectCodeSources, c_ as buildSshPtyArgs, bn as resolveSshControlPath, c$ as parseTerminalShell, E as version$1 } from "./chunks/workflowPresets-DqSsjOj6.js";
10
+ import { U as APPROVAL_MODES$1, V as THINKING_LEVELS, W as ENSO_LOCKED_PROFILE_ID, u as isSameChildSessionIdentity, X as parseChildConversationMetadata, J as isClassifierOnlyProvider, K as isOauthAccountPool, Y as eligibleOauthPoolAccountKeys, j as isCodexAccountKey, Z as isEditMode, _ as normalizeSshTimeoutSeconds, L as resolveEditMode, $ as CLAUDE_HOOK_EVENTS, a0 as isReservedAgentTypeName, a1 as BUILTIN_AGENT_TYPES, a2 as isPluginEntry, a3 as PLUGIN_HOST_APIS, T as pluginToolName, a4 as PLUGIN_INJECT_MAX_CHARS, a5 as parsePluginInjectImages, a6 as isHostPluginEvent, a7 as parsePluginToolName, a8 as initialInterceptState, m as isChildInterceptEvent, a9 as CHILD_INTERCEPT_TOTAL_TIMEOUT_MS, aa as INTERCEPT_TOTAL_TIMEOUT_MS, ab as CHILD_INTERCEPT_TIMEOUT_MS, ac as INTERCEPT_TIMEOUT_MS, ad as applyInterceptResult, ae as failClosedResult, af as OBSERVE_TIMEOUT_MS, ag as BEFORE_COMPACT_TIMEOUT_MS, ah as PLUGIN_PROGRESS_MAX_CHARS, ai as MCP_TRANSPORTS, aj as parsePrivacyMaskRecord, Q as PRIVACY_MASK_ENTRY, ak as hasProviderCredentials, g as MODEL_REASONING_OVERRIDES, h as MODEL_THINKING_LEVEL_OVERRIDES, al as buildAgentTypeRegistrySnapshot, am as visibleMemberAgentTypes, an as ENSO_AGENT_TYPE_KEY, F as ENSO_LOCKED_PROFILE, b as parseApprovalAllowThreshold, ao as DEFAULT_APPROVAL_ALLOW_THRESHOLD, ap as resolveShellLimits, aq as parseWebSearchChain, R as parseAgentCommand, ar as parseWindowsLocalShell, v as resolveCompactStrategy, as as parseSmartCompactMode, at as parseAgentWorkerEvent, e as parseProviderHeaders, au as DEFAULT_PRESET_ID, av as normalizeMaxActiveCoworkers, aw as normalizeAutoRetryLimit, ax as parsePrivacyMaskSettings, ay as parseDisabledWorkflowPresets, az as resolveImageGenerationConfig, aA as AGENT_WAIT_DEFAULT_MS, aB as AGENT_WAIT_MAX_MS, l as isUuid, aC as isDeliveryId, H as splitPlanPrefix, p as parseChildSessionIdentity, aD as LOCAL_IMAGE_SCHEME, aE as REMOTE_FETCH_HOST, aF as BOT_AVATAR_HOST, aG as PLUGIN_ASSET_HOST, aH as mediaExtension, aI as localImageUrlToPath, aJ as isMediaPath, aK as isVideoPath, aL as IMAGE_EXTENSIONS$1, aM as withVersionSegment, aN as DEFAULT_BASE_URLS, aO as parseCapabilityAskResponse, aP as parseCreateConversationAuthorityRequest, aQ as parseConversationAuthorityRequest, aR as parseUpdateConversationSelectionRequest, aS as parseTitleSummaryInput, aT as parseParentSourceBindingRequest, aU as parseParentModelSelectionRequest, aV as parseAgentDispatchRequest, aW as isApprovalDecision, aX as cleanToolBatchLabel, aY as toolBatchLabelPrompt, aZ as TOOL_BATCH_LABEL_SYSTEM_PROMPT, N as EMPTY_PLAN_STATE, a_ as TITLE_SUMMARY_MAX_CANDIDATES, a$ as parseCreateProjectAuthorityRequest, b0 as parseSelectProjectAuthorityRequest, b1 as parseRemoveProjectAuthorityRequest, b2 as parseStartOauthWizardRequest, b3 as parseOauthFlowPromptResponse, b4 as parseOauthFlowControlRequest, M as MODEL_API_KINDS } from "./chunks/agent--Q7N17bY.js";
11
+ import { bF as isMediaId, bG as isVirtualRef, bH as findVirtualModel, $ as takeSnapshotTail, bI as syncAccountProviders, bJ as expandOauthCatalog, bK as supportsMultipleAccounts, bi as ANTIGRAVITY_PROVIDER_ID, bj as antigravityProviderConfig, bk as DEVIN_PROVIDER_ID, bl as devinProviderConfig, bm as QODER_PROVIDER_ID, bn as qoderProviderConfig, bo as QODER_CN_PROVIDER_ID, bp as installCodexLinkedRefresh, as as providerIdOfAccountKey, bL as ordinalOfAccountKey, bM as nextAccountKey, _ as ensureAccountProvider, bN as sanitizeUpstreamBody, bO as parseAntigravityApiKey, bP as fetchAntigravityUsage, bQ as fetchDevinUsage, bR as sanitizeOauthLabel, bS as parseCodexAuthJson, bT as CODEX_PROVIDER_ID, bU as defaultCodexAuthPath, bV as DEFAULT_PERSONA_PROMPT, b3 as WORKSPACE_WRITE_TOOL_ID, bW as resolveDisabledBuiltinTools, bX as projectDisabledBuiltinTools, a9 as ELEVATE_TIMEOUT_MS, s as shellQuote, aa as ELEVATE_UNAVAILABLE_MARKER, a8 as ELEVATE_TIMED_OUT_MARKER, a7 as ELEVATE_DECLINED_MARKER, bY as elevatedCommandOf, bq as isHeadlessRun, bZ as startOauthCallbackServer, T as mcpOAuthFingerprint, S as MCP_OAUTH_REFRESH_SKEW_MS, E as readModelsDevCache, b_ as MODELS_DEV_CACHE_NAME, b$ as MODELS_DEV_URL, c0 as writeModelsDevCache, c1 as parseModelsDevPayload, c2 as modelsDevIsFresh, G as parseModelDirectorySnapshot, c3 as persistedSettingsState, c4 as withModelsDevOauthModels, c5 as childProfileToolIds, bt as ENSO_SYSTEM_PROMPT, a3 as childProfileShell, c6 as directMemberRef, p as providerKeyFor, a5 as ELEVATE_ASKPASS_ENV, c7 as materializeProviders, c8 as classifierProviderFor, c9 as classifierBaseUrlFor, ca as parseVirtualModels, V as VIRTUAL_PROVIDER_ID, cb as mcpTimeoutsForSpawn, cc as pickModelCapabilityOverrides, cd as canBeVirtualMember, aV as parseJsonFromAssistant, aW as validateAgainstSchema, ay as HUMAN_REQUEST_TIMEOUT_MS, ce as UNIT_TYPES, cf as DEDUP_MIN_CHARS, cg as DEFAULT_IMPORTANCE, ch as DEFAULT_UNIT_TYPE, ci as isEvolvesRelation, cj as DEDUP_MAX, ck as DEDUP_VECTOR, cl as CRYSTAL_MIN_SOURCES, cm as DISTILL_MAX_OUTPUT_TOKENS, cn as DISTILL_MIN_IMPORTANCE, co as DISTILL_MAX_CHUNK_CHARS, cp as DISTILL_SINGLE_EXTRACT_MAX_TOKENS, cq as DISTILL_EXTRACT_MAX_TOKENS, cr as DISTILL_CONSOLIDATE_MAX_TOKENS, cs as isUnitType, ct as DISTILL_MAX_ATTEMPTS, cu as KG_MAX_LABEL_CHARS, cv as KG_MAX_ENTITY_NAME_CHARS, cw as KG_MAX_DESCRIPTION_CHARS, cx as KG_MAX_ENTITIES, cy as KG_MAX_RELATIONS, cz as KG_EXTRACT_MAX_TOKENS, cA as KG_DEFAULT_RELATION_TYPE, cB as KG_DEFAULT_ENTITY_TYPE, cC as KG_MAX_ATTEMPTS, cD as MIN_FLOOR, cE as IMP_MULT, cF as RECENCY_W, cG as FREQUENCY_W, cH as FREQUENCY_MAX_COUNT, cI as HALF_LIFE_DAYS, cJ as RRF_K, cK as DECAY_WEIGHT, cL as TEMPORAL_YEAR_BOOST, cM as CRYSTAL_BOOST, cN as MMR_LAMBDA, cO as parseMemorySearchRequest, cP as parseMemoryCaptureRequest, cQ as parseMemoryCrystallizeRequest, cR as parseMemoryDeleteRequest, cS as effectiveDisabledBuiltinTools, cT as SNAPSHOT_TAIL_MESSAGES, bc as splitUnattendedPrefix, cU as userTextWithoutSkills, cV as withPrivacyMask, cW as withUserEntryIds, Z as projectMessage, cX as resolveSshTarget, cY as checkPassed, cZ as checkFailureText, ai as SEND_IMAGE_CAPTION_MAX, c_ as parseVirtualClassifier, c$ as VIRTUAL_CLASSIFIER_DEFAULT_TIMEOUT_MS, a_ as buildInitialTitleUserText, b0 as TITLE_SYSTEM_PROMPT, aU as buildTurnDigest, a$ as ROLLING_TITLE_SYSTEM_PROMPT, aZ as buildRollingTitleUserText, bb as titleSummaryTimeoutMs, b1 as extractTitle, b2 as titleRejectReason, ak as sendImageItems, ae as CAPABILITY_CATALOG, d0 as CAPABILITY_HANDLER_CONTRACT, d1 as BUILTIN_TOOLS, d2 as TERMINAL_SHELLS, d3 as parseAccentColor, d4 as positiveFiniteNumber, X as isXaiChatModelId, d5 as mergeFetchedOauthModels, J as mergeCatalogEntry, H as findCatalogModelById, I as findModelsDevModel, d6 as supportedProjectThinkingLevels, d7 as buildSshExecArgs, d8 as buildRemoteCommand, bD as sshPasswordEnv, d9 as effectiveSubagentAllowedModes, b6 as EnsoSafeJournal, aH as createComputerTool, aO as ComputerInvoker, da as codemodeToolSnapshot, aK as createTaskTools, aF as createMemoryTools, aM as MemoryInvoker, b7 as createWebTools, aD as createBrowserTools, aB as createUnifiedSubagentTool, aL as BrowserInvoker, aQ as createAskTool, aP as AskManager, ba as createSubmitPlanTool, b8 as createTodoTool, f as estimateSkillTokens, g as estimateInstructionTokens, db as estimateToolsTotal, bh as createProjectSettingsManager, bd as resolveHarnessSkillRoots, R as assignMcpToolNames, aJ as listWorkflowPresets, aC as workflowPresetRoots, dc as listCustomWorkflowPresets, dd as listBuiltinWorkflowPresets, de as readCustomWorkflowPreset, df as parseWorkflowPresetDraft, dg as saveCustomWorkflowPreset, dh as deleteCustomWorkflowPreset, au as createSshExecutor, di as resolveTerminalShellFile, dj as isHumanRequestTimeout, dk as listProjectCodeSources, dl as buildSshPtyArgs, bC as resolveSshControlPath, dm as parseTerminalShell, F as version$1, dn as ENSO_HEADLESS_RUN_ENV } from "./chunks/workflowPresets-CuLnfQqa.js";
12
12
  import { readFile, rm, open, writeFile, stat, realpath, lstat, mkdir, symlink, readdir, copyFile, readlink, appendFile, rename, mkdtemp, rmdir, statfs } from "node:fs/promises";
13
13
  import nacl from "tweetnacl";
14
14
  import { promisify, TextDecoder as TextDecoder$1 } from "node:util";
15
15
  import { parse as parse$2 } from "yaml";
16
- import { i as isPluginId, a as isNewerPluginVersion, b as isPluginRelativePath, e as enginesAllow, M as MAX_TOOL_TIMEOUT_MS, p as parseExtensionPluginManifest } from "./chunks/manifest-2odvnxjZ.js";
17
- import { inflateRawSync, gunzipSync, gzipSync } from "node:zlib";
16
+ import { i as isPluginId, a as isNewerPluginVersion, b as isPluginRelativePath, e as enginesAllow, M as MAX_TOOL_TIMEOUT_MS, p as parseStatusPatch, c as parseExtensionPluginManifest, m as mergeStatusItems } from "./chunks/manifest-BvEa5QR3.js";
17
+ import { inflateRawSync, gunzipSync, deflateRawSync, crc32, gzipSync } from "node:zlib";
18
18
  import { stepUpScope, authorizeMcp, discoverOAuthServerInfo, refreshAuthorization, selectResource, OAuthError } from "@earendil-works/pi-mcp/oauth";
19
19
  import { fileURLToPath, pathToFileURL } from "node:url";
20
20
  import { finished } from "node:stream/promises";
@@ -35,7 +35,7 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
35
35
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
36
36
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
37
37
  import { lookup as lookup$1 } from "node:dns";
38
- import http, { createServer } from "node:http";
38
+ import http, { createServer as createServer$1 } from "node:http";
39
39
  import https from "node:https";
40
40
  import { spawn as spawn$1 } from "node-pty";
41
41
  import { b as chromiumRole, A as AGENT_SERVICE_NAME, d as descendantPids, e as commandLabel, f as parseWinProcesses, g as parsePsArgs, h as parsePs, i as cpuPercent, j as isCleanableStorageCategory, k as parseSessionCleanRequest } from "./chunks/resources-DmaKIeBc.js";
@@ -53,11 +53,12 @@ import require$$3$1 from "net";
53
53
  import require$$4 from "tls";
54
54
  import require$$1$2 from "crypto";
55
55
  import require$$7 from "url";
56
+ import "@earendil-works/pi-ai";
57
+ import "node:string_decoder";
56
58
  import "node:buffer";
57
59
  import "@mozilla/readability";
58
60
  import "linkedom";
59
61
  import "turndown";
60
- import "@earendil-works/pi-ai";
61
62
  const IPC_CHANNELS = {
62
63
  // Settings persistence
63
64
  SETTINGS_READ: "settings:read",
@@ -90,6 +91,10 @@ const IPC_CHANNELS = {
90
91
  SETTINGS_DEEP_LINK: "settings:deep-link",
91
92
  SETTINGS_DEEP_LINK_CONSUME: "settings:deep-link-consume",
92
93
  WINDOW_POPUP_MENU: "window:popup-menu",
94
+ WINDOW_TAKE_OPEN_FOLDERS: "window:takeOpenFolders",
95
+ WINDOW_OPEN_FOLDER_REQUESTED: "window:openFolderRequested",
96
+ WINDOW_INSTALL_SHELL_INTEGRATION: "window:installShellIntegration",
97
+ WINDOW_SHELL_INTEGRATION_STATUS: "window:shellIntegrationStatus",
93
98
  APP_CLOSE_REQUEST: "app:close-request",
94
99
  APP_CLOSE_RESPONSE: "app:close-response",
95
100
  APP_FLUSH_PERSIST_REQUEST: "app:flush-persist-request",
@@ -101,6 +106,7 @@ const IPC_CHANNELS = {
101
106
  PROVIDERS_LIST_MODELS: "providers:list-models",
102
107
  PROVIDERS_TEST: "providers:test",
103
108
  PROVIDERS_MODEL_META: "providers:model-meta",
109
+ PROVIDERS_REFRESH_MODEL_CATALOG: "providers:refresh-model-catalog",
104
110
  PROVIDERS_CLASSIFIER_MODELS: "providers:classifier-models",
105
111
  /** Main 合成的统一模型目录快照(Renderer 订阅,不落 settings.json) */
106
112
  MODEL_DIRECTORY_GET: "modelDirectory:get",
@@ -109,6 +115,10 @@ const IPC_CHANNELS = {
109
115
  USAGE_SUMMARY: "usage:summary",
110
116
  // 隐私脱敏记录(只读,不含原值)
111
117
  PRIVACY_MASK_RECORDS: "privacy-mask:records",
118
+ // bash 提权口令:只对桌面主窗口与完整模式主界面开放
119
+ ELEVATION_PENDING: "elevation:pending",
120
+ ELEVATION_ANSWER: "elevation:answer",
121
+ ELEVATION_CHANGED: "elevation:changed",
112
122
  // Resource monitor
113
123
  RESOURCES_SAMPLE: "resources:sample",
114
124
  RESOURCES_STORAGE_SCAN: "resources:storage-scan",
@@ -215,6 +225,7 @@ const IPC_CHANNELS = {
215
225
  AGENT_SPAWN: "agent:spawn",
216
226
  AGENT_PROMPT: "agent:prompt",
217
227
  AGENT_STEER: "agent:steer",
228
+ AGENT_WITHDRAW_STEER: "agent:withdraw-steer",
218
229
  AGENT_ABORT: "agent:abort",
219
230
  AGENT_ABORT_RETRY: "agent:abort-retry",
220
231
  AGENT_RETRY: "agent:retry",
@@ -575,6 +586,7 @@ const IPC_CHANNELS = {
575
586
  EXTENSION_PLUGINS_DISCARD: "extension-plugins:discard",
576
587
  EXTENSION_PLUGINS_SET_ENABLED: "extension-plugins:set-enabled",
577
588
  EXTENSION_PLUGINS_SET_CROSS_SESSION_INJECT: "extension-plugins:set-cross-session-inject",
589
+ EXTENSION_PLUGINS_SET_DEV_WATCH: "extension-plugins:set-dev-watch",
578
590
  EXTENSION_PLUGINS_APPROVE_PENDING: "extension-plugins:approve-pending",
579
591
  EXTENSION_PLUGINS_REJECT_PENDING: "extension-plugins:reject-pending",
580
592
  EXTENSION_PLUGINS_UNINSTALL: "extension-plugins:uninstall",
@@ -650,10 +662,11 @@ const appRoot = path.resolve(
650
662
  process.env.ENSO_APP_ROOT?.trim() || path.join(import.meta.dirname, "../..")
651
663
  );
652
664
  const resourcesPath = path.join(appRoot, "resources");
653
- const userData = path.resolve(
654
- process.env.ENSO_DATA_DIR?.trim() || path.join(homedir(), ".enso-server")
655
- );
665
+ function dataDir() {
666
+ return path.resolve(process.env.ENSO_DATA_DIR?.trim() || path.join(homedir(), ".enso-server"));
667
+ }
656
668
  function ensureUserData() {
669
+ const userData = dataDir();
657
670
  mkdirSync(userData, { recursive: true });
658
671
  return userData;
659
672
  }
@@ -671,7 +684,7 @@ const app = {
671
684
  case "home":
672
685
  return homedir();
673
686
  case "appData":
674
- return path.dirname(userData);
687
+ return path.dirname(dataDir());
675
688
  case "logs":
676
689
  return path.join(ensureUserData(), "logs");
677
690
  case "downloads":
@@ -801,9 +814,17 @@ class ForkedWorker extends EventEmitter {
801
814
  this.child = child;
802
815
  child.on("spawn", () => this.emit("spawn"));
803
816
  child.on("message", (message2) => this.emit("message", message2));
804
- child.on("exit", (code) => this.emit("exit", code ?? 0));
817
+ child.on("error", (error) => {
818
+ process.stderr.write(
819
+ `[enso-server] worker: ${error instanceof Error ? error.message : String(error)}
820
+ `
821
+ );
822
+ this.finish(1);
823
+ });
824
+ child.on("exit", (code) => this.finish(code ?? 0));
805
825
  }
806
826
  child;
827
+ exited = false;
807
828
  get pid() {
808
829
  return this.child.pid;
809
830
  }
@@ -811,18 +832,41 @@ class ForkedWorker extends EventEmitter {
811
832
  this.child.send(message2);
812
833
  }
813
834
  kill() {
814
- return this.child.kill();
835
+ const ok = this.child.kill();
836
+ const pid = this.child.pid;
837
+ const timer2 = setTimeout(() => {
838
+ if (this.exited || pid === void 0) return;
839
+ try {
840
+ process.kill(pid, "SIGKILL");
841
+ } catch {
842
+ }
843
+ }, 2e3);
844
+ timer2.unref?.();
845
+ return ok;
846
+ }
847
+ finish(code) {
848
+ if (this.exited) return;
849
+ this.exited = true;
850
+ this.emit("exit", code);
815
851
  }
816
852
  }
817
853
  const utilityProcess = {
818
854
  fork(modulePath, args, options) {
819
- return new ForkedWorker(
820
- fork(modulePath, args, {
821
- env: options.env,
822
- serialization: "advanced",
823
- stdio: ["inherit", "inherit", "inherit", "ipc"]
824
- })
825
- );
855
+ const headless2 = process.env.ENSO_HEADLESS_RUN === "1";
856
+ const child = fork(modulePath, args, {
857
+ env: options.env,
858
+ serialization: "advanced",
859
+ stdio: headless2 ? ["ignore", "pipe", "pipe", "ipc"] : ["inherit", "inherit", "inherit", "ipc"]
860
+ });
861
+ if (headless2) {
862
+ child.stdout?.on("data", (chunk) => {
863
+ process.stderr.write(chunk);
864
+ });
865
+ child.stderr?.on("data", (chunk) => {
866
+ process.stderr.write(chunk);
867
+ });
868
+ }
869
+ return new ForkedWorker(child);
826
870
  }
827
871
  };
828
872
  const clipboard = { writeText: () => void 0, writeBuffer: () => void 0 };
@@ -3190,7 +3234,6 @@ const zhTranslations = {
3190
3234
  "Release notes": "更新日志",
3191
3235
  "What's new in {{version}}": "{{version}} 更新内容",
3192
3236
  "No release notes provided.": "此版本未提供更新日志。",
3193
- Later: "稍后",
3194
3237
  Restart: "重启",
3195
3238
  "Restart server": "重启服务端",
3196
3239
  "Restart server?": "重启服务端?",
@@ -3370,6 +3413,19 @@ const zhTranslations = {
3370
3413
  "Not installed": "未安装",
3371
3414
  Install: "安装",
3372
3415
  Uninstall: "卸载",
3416
+ OK: "好",
3417
+ Integrations: "集成",
3418
+ "Install 'enso' Command in PATH": "在 PATH 中安装 enso 命令",
3419
+ "Install Finder Quick Action": "安装访达快速操作",
3420
+ "'enso' terminal command": "enso 终端命令",
3421
+ "Finder Quick Action": "访达快速操作",
3422
+ "Couldn't install the 'enso' command": "无法安装 enso 命令",
3423
+ "Shell command 'enso' installed in {{dir}}.": "已在 {{dir}} 安装 enso 命令。",
3424
+ "Run `enso .` in a terminal to open the current folder in EnsoCode.": "在终端运行 `enso .` 即可用 EnsoCode 打开当前目录。",
3425
+ "Run `enso .` in a terminal to open the current folder in EnsoCode. Links the command into /usr/local/bin and may ask for your password.": "在终端运行 `enso .` 即可用 EnsoCode 打开当前目录。会把命令链接到 /usr/local/bin,可能需要输入密码。",
3426
+ "Couldn't install the Finder Quick Action": "无法安装访达快速操作",
3427
+ "Finder Quick Action installed.": "访达快速操作已安装。",
3428
+ "Right-click a folder in Finder and choose Services > Open with EnsoCode.": "在访达中右键文件夹,选择「服务」>「用 EnsoCode 打开」。",
3373
3429
  "Installing…": "安装中…",
3374
3430
  "Operation failed": "操作失败",
3375
3431
  "Install dcg": "安装 dcg",
@@ -3631,6 +3687,11 @@ const zhTranslations = {
3631
3687
  "{{enabled}}/{{total}} enabled": "已启用 {{enabled}}/{{total}}",
3632
3688
  "Fetch models": "拉取模型",
3633
3689
  "Fetch all models": "拉取全部模型",
3690
+ "Refresh model info": "刷新模型信息",
3691
+ "Refresh all models and info": "拉取全部模型与模型信息",
3692
+ "Model info updated": "模型信息已更新",
3693
+ "Model info refresh failed, using cache": "模型信息刷新失败,仍使用缓存",
3694
+ "Model info refresh failed": "模型信息刷新失败",
3634
3695
  "Fetched {{count}} providers": "已拉取 {{count}} 个模型服务",
3635
3696
  "Test connection": "测试连接",
3636
3697
  Authorize: "授权",
@@ -4110,6 +4171,9 @@ const zhTranslations = {
4110
4171
  "Unit prices": "单价",
4111
4172
  "Rates used for cost estimates ($/M tokens).": "费用估算用的单价($/百万 tokens)。",
4112
4173
  "Show all": "显示所有",
4174
+ "Show all {{count}} lines": "显示全部 {{count}} 行",
4175
+ "Raw text": "原文",
4176
+ "Search table": "搜索表格",
4113
4177
  "No matching models": "没有匹配的模型",
4114
4178
  "Model id": "模型 id",
4115
4179
  "Enter a model id and non-negative rates.": "请填写模型 id 和非负单价。",
@@ -4236,6 +4300,16 @@ const zhTranslations = {
4236
4300
  "No answer in time; the default was selected": "超时未回答,已自动选择默认项",
4237
4301
  Selected: "已选",
4238
4302
  "Type an answer…": "输入回答…",
4303
+ Later: "稍后",
4304
+ Recommended: "推荐",
4305
+ "Files read": "读入的文件",
4306
+ "Tool results": "工具输出",
4307
+ "About {{tokens}} left": "大约还剩 {{tokens}}",
4308
+ "{{count}} more": "其余 {{count}} 项",
4309
+ "Earlier {{count}} turns": "更早的 {{count}} 轮",
4310
+ "Turn {{count}}": "第 {{count}} 轮",
4311
+ "Compacted summary": "压缩摘要",
4312
+ "System reminders": "系统提醒",
4239
4313
  "Message will queue until this round finishes…": "消息将排队,本轮结束后发送…",
4240
4314
  "Press {{key}} to steer the next queued message into this round…": "按 {{key}} 将下一条排队消息插入本轮…",
4241
4315
  Queued: "排队",
@@ -4545,6 +4619,7 @@ const zhTranslations = {
4545
4619
  "This project ships pi extension code that runs with your permissions. It was not loaded. Trust it only if you trust this repository.": "此项目带有 pi 扩展代码,会以你的权限运行,已阻止加载。只有信任这个仓库时才加载。",
4546
4620
  "Trust and load": "信任并加载",
4547
4621
  Plugins: "插件",
4622
+ Plugin: "插件",
4548
4623
  "Enso plugins": "Enso 插件",
4549
4624
  "Claude Code plugins": "Claude Code 插件",
4550
4625
  "No Enso plugins installed": "还没有安装 Enso 插件",
@@ -4637,6 +4712,9 @@ const zhTranslations = {
4637
4712
  "Loading…": "加载中…",
4638
4713
  "(no log available)": "(暂无日志)",
4639
4714
  "Context compacted": "上下文已压缩",
4715
+ "Waiting for first token": "等首字",
4716
+ "Think time": "思考",
4717
+ "{{kind}} · {{before}} → {{after}} · freed {{percent}}%": "{{kind}} · {{before}} → {{after}} · 释放 {{percent}}%",
4640
4718
  "Context compacted ({{tokens}} tokens before)": "上下文已压缩(压缩前 {{tokens}} tokens)",
4641
4719
  "Verified context compacted": "验证式压缩完成",
4642
4720
  "Verified context compacted ({{tokens}} tokens before)": "验证式压缩完成(压缩前 {{tokens}} tokens)",
@@ -4795,6 +4873,11 @@ const zhTranslations = {
4795
4873
  "(no output yet)": "(暂无输出)",
4796
4874
  Deny: "拒绝",
4797
4875
  Allow: "允许",
4876
+ "Run as administrator": "以管理员权限运行",
4877
+ "Login password": "本机登录密码",
4878
+ "A command is waiting for the administrator password": "有命令在等待管理员密码",
4879
+ "Incorrect password. Try again.": "密码不正确,请重试。",
4880
+ "Applies to this command only. The password is never shown to the AI.": "仅对这一条命令生效,密码不会交给 AI。",
4798
4881
  Adjust: "调整",
4799
4882
  "Send back for a safer command": "打回去,让模型换一个更安全的命令",
4800
4883
  "Assistant review": "代审",
@@ -4825,6 +4908,7 @@ const zhTranslations = {
4825
4908
  "Beginning of conversation": "已到对话开头",
4826
4909
  "Retry resume": "重新恢复",
4827
4910
  Todos: "任务清单",
4911
+ "Todo list cleared": "已清空",
4828
4912
  "{{count}} tool calls": "{{count}} 个工具调用",
4829
4913
  "ran {{count}} commands": "跑了 {{count}} 条命令",
4830
4914
  "total {{duration}}": "总计 {{duration}}",
@@ -4845,6 +4929,7 @@ const zhTranslations = {
4845
4929
  "{{speed}} tok/s": "{{speed}} tok/s",
4846
4930
  "Search models": "搜索模型",
4847
4931
  "Virtual models": "虚拟模型",
4932
+ "Starred & virtual": "星标与虚拟",
4848
4933
  "Enable virtual model": "启用虚拟模型",
4849
4934
  "Primary model": "主模型",
4850
4935
  "Default for each new turn": "每轮默认使用",
@@ -4922,6 +5007,9 @@ const zhTranslations = {
4922
5007
  "Refusal retry": "拒答补发",
4923
5008
  "Refusal retry prompt": "拒答补发正文",
4924
5009
  Advanced: "高级",
5010
+ "Request headers": "请求头",
5011
+ "Add header": "添加请求头",
5012
+ "Remove header": "移除请求头",
4925
5013
  "Rewrites the role paragraph or appends text to the system prompt.": "改写角色段落,或往系统提示词末尾追加内容。",
4926
5014
  "Import URL": "从 URL 导入",
4927
5015
  "https://example.com/preset.json": "https://example.com/preset.json",
@@ -4932,6 +5020,8 @@ const zhTranslations = {
4932
5020
  "Let the agent auto-discover skills under .agents/skills and .pi/skills": "让 agent 自动发现 .agents/skills、.pi/skills 下的 skill",
4933
5021
  "Explore fold": "探后折叠",
4934
5022
  "Explore mark": "开始探索",
5023
+ "Turn discard": "丢弃本轮",
5024
+ "Turn recall": "取回已丢弃",
4935
5025
  Goal: "目标",
4936
5026
  "Show process": "展开过程",
4937
5027
  "Hide process": "收起过程",
@@ -5090,6 +5180,10 @@ const zhTranslations = {
5090
5180
  "The remote desktop has no projects yet": "对方桌面还没有项目",
5091
5181
  "Select a conversation on the left, or create one": "从左侧选择会话,或新建一个",
5092
5182
  "New remote conversation": "新建远程会话",
5183
+ "Add a directory on the remote computer as a project.": "把对方电脑上的目录添加为项目。",
5184
+ "The remote desktop did not respond. It may need to be updated.": "对方桌面没有响应,可能需要升级。",
5185
+ "Directory not found.": "目录不存在。",
5186
+ "Project path is not a directory.": "项目路径不是目录。",
5093
5187
  "Node settings": "节点设置",
5094
5188
  "The conversation runs on the remote computer with its projects, models and keys.": "会话在对方电脑上运行,用的是对方的项目、模型与密钥。",
5095
5189
  "On the other computer open Settings → Devices, generate a pairing code and copy the link. Paste it here.": "在对方电脑打开「设置 → 设备」,生成配对码并复制链接,粘到这里。",
@@ -5106,6 +5200,20 @@ const zhTranslations = {
5106
5200
  "Waiting for device": "等待设备",
5107
5201
  "Direct link": "直连",
5108
5202
  "Via relay": "中继",
5203
+ Connected: "已连接",
5204
+ "Desktop is offline": "桌面端离线",
5205
+ "Pairing expired": "配对已失效",
5206
+ "Reconnecting…": "重连中…",
5207
+ "Turn on notifications": "开启推送通知",
5208
+ "Turn off notifications": "关闭推送通知",
5209
+ "Push notifications": "推送通知",
5210
+ "Turning on notifications…": "正在开启推送…",
5211
+ "Notifications need a newer desktop app.": "需先升级桌面端才能开启推送。",
5212
+ "Add this app to the Home Screen before notifications can be turned on.": "iOS 需先用分享菜单「添加到主屏幕」,从主屏幕打开后才能开启。",
5213
+ "This browser cannot show notifications.": "当前浏览器不支持推送。",
5214
+ "Notification permission was denied. Allow notifications for this site and try again.": "通知权限被拒绝,请在浏览器站点设置中允许后重试。",
5215
+ "Cannot reach the push service. Check the network or proxy and try again.": "无法连接推送服务,请检查网络或代理后重试。",
5216
+ "Could not turn on notifications.": "无法开启推送。",
5109
5217
  "View only": "只读",
5110
5218
  "Can operate": "可操作",
5111
5219
  "Click to switch: view-only devices cannot send, approve or stop.": "点击切换:只读设备不能发送、审批或停止。",
@@ -5871,7 +5979,14 @@ const zhTranslations = {
5871
5979
  Unnamed: "未命名",
5872
5980
  "Group settings and member personas only. Memory, sessions, timeline, tasks, routines, models, skills and MCP are not included.": "只含群配置和成员人设,不含记忆、会话、时间线、看板、例行任务、模型、技能和 MCP。",
5873
5981
  "Interface is zoomed to {{percent}}% · {{shortcut}}": "界面已缩放至 {{percent}}% · {{shortcut}}",
5874
- "Restore 100%": "恢复 100%"
5982
+ "Restore 100%": "恢复 100%",
5983
+ "Uninstall 'enso' Command from PATH": "卸载 enso 命令",
5984
+ "Uninstall Finder Quick Action": "卸载访达快速操作",
5985
+ "Couldn't uninstall the 'enso' command": "无法卸载 enso 命令",
5986
+ "Shell command 'enso' uninstalled.": "已卸载 enso 命令。",
5987
+ "Couldn't uninstall the Finder Quick Action": "无法卸载访达快速操作",
5988
+ "Finder Quick Action uninstalled.": "访达快速操作已卸载。",
5989
+ "In progress…": "处理中…"
5875
5990
  };
5876
5991
  function normalizeLocale(input) {
5877
5992
  if (!input) return "en";
@@ -5913,6 +6028,8 @@ const appDesktopNoop = {
5913
6028
  throw new Error("Updater is not available on this host");
5914
6029
  },
5915
6030
  syncTrayToggleShortcut() {
6031
+ },
6032
+ syncAppLanguage() {
5916
6033
  }
5917
6034
  };
5918
6035
  const sessionDesktopNoop = {
@@ -7989,9 +8106,9 @@ class RemoteSender extends EventEmitter {
7989
8106
  const sessions2 = event.sessions.filter((session2) => {
7990
8107
  const key = sessionKey(session2);
7991
8108
  if (!key) return true;
7992
- const tail = this.resumeTails.get(key);
8109
+ const tail2 = this.resumeTails.get(key);
7993
8110
  this.resumeTails.delete(key);
7994
- return tail !== signature$1(session2);
8111
+ return tail2 !== signature$1(session2);
7995
8112
  });
7996
8113
  if (sessions2.length === 0) return null;
7997
8114
  return sessions2.length === event.sessions.length ? event : { ...event, sessions: sessions2 };
@@ -8088,12 +8205,12 @@ function trimSnapshot(event) {
8088
8205
  return {
8089
8206
  ...event,
8090
8207
  sessions: event.sessions.map((session2) => {
8091
- const tail = takeSnapshotTail(session2.messages, session2.messages.length);
8092
- if (tail.baseIndex === 0) return session2;
8208
+ const tail2 = takeSnapshotTail(session2.messages, session2.messages.length);
8209
+ if (tail2.baseIndex === 0) return session2;
8093
8210
  return {
8094
8211
  ...session2,
8095
- messages: tail.messages,
8096
- baseIndex: (session2.baseIndex ?? 0) + tail.baseIndex
8212
+ messages: tail2.messages,
8213
+ baseIndex: (session2.baseIndex ?? 0) + tail2.baseIndex
8097
8214
  };
8098
8215
  })
8099
8216
  };
@@ -8185,7 +8302,12 @@ function getOauthQuotaCoordinator() {
8185
8302
  function invalidateOauthQuota(accountKey) {
8186
8303
  if (isCodexAccountKey(accountKey)) getOauthQuotaCoordinator().invalidate(accountKey);
8187
8304
  }
8188
- const onlineCatalogProviderIds = /* @__PURE__ */ new Set([ANTIGRAVITY_PROVIDER_ID, DEVIN_PROVIDER_ID]);
8305
+ const onlineCatalogProviderIds = /* @__PURE__ */ new Set([
8306
+ ANTIGRAVITY_PROVIDER_ID,
8307
+ DEVIN_PROVIDER_ID,
8308
+ QODER_PROVIDER_ID,
8309
+ QODER_CN_PROVIDER_ID
8310
+ ]);
8189
8311
  const ONLINE_CATALOG_TTL_MS = 6 * 60 * 60 * 1e3;
8190
8312
  const onlineCatalogRefreshes = /* @__PURE__ */ new Map();
8191
8313
  function getRuntime() {
@@ -8199,13 +8321,17 @@ function getRuntime() {
8199
8321
  });
8200
8322
  runtime.registerProvider(ANTIGRAVITY_PROVIDER_ID, antigravityProviderConfig());
8201
8323
  runtime.registerProvider(DEVIN_PROVIDER_ID, devinProviderConfig());
8202
- const { CURSOR_PROVIDER_ID, loadCursorProvider } = await import("./chunks/loadProvider-BnkyjMSW.js").then((n) => n.d);
8324
+ runtime.registerProvider(QODER_PROVIDER_ID, qoderProviderConfig("global"));
8325
+ runtime.registerProvider(QODER_CN_PROVIDER_ID, qoderProviderConfig("cn"));
8326
+ const { CURSOR_PROVIDER_ID, loadCursorProvider } = await import("./chunks/loadProvider-DvvFIF6F.js").then((n) => n.d);
8203
8327
  onlineCatalogProviderIds.add(CURSOR_PROVIDER_ID);
8204
8328
  await loadCursorProvider(runtime);
8205
8329
  installCodexLinkedRefresh(runtime);
8206
8330
  await syncAccountProviders(runtime);
8207
8331
  void ensureProviderModelsRefreshed(runtime, ANTIGRAVITY_PROVIDER_ID);
8208
8332
  void ensureProviderModelsRefreshed(runtime, DEVIN_PROVIDER_ID);
8333
+ void ensureProviderModelsRefreshed(runtime, QODER_PROVIDER_ID);
8334
+ void ensureProviderModelsRefreshed(runtime, QODER_CN_PROVIDER_ID);
8209
8335
  void ensureProviderModelsRefreshed(runtime, CURSOR_PROVIDER_ID);
8210
8336
  return runtime;
8211
8337
  })();
@@ -9169,6 +9295,9 @@ function applyConversationsPatch(target, patch) {
9169
9295
  function localMainContents() {
9170
9296
  return null;
9171
9297
  }
9298
+ function isMainRendererAlive() {
9299
+ return hasRemoteMain();
9300
+ }
9172
9301
  function isMainRenderer(webContentsId) {
9173
9302
  if (isRemoteMainSender(webContentsId)) return true;
9174
9303
  return localMainContents()?.id === webContentsId;
@@ -9329,6 +9458,7 @@ const SETTINGS_STATE_FIELDS = [
9329
9458
  "collapseLiveActivity",
9330
9459
  "liveActivityFoldDelaySec",
9331
9460
  "pinUnfinishedTodos",
9461
+ "pinnedModels",
9332
9462
  "chatWide",
9333
9463
  "navRailSide",
9334
9464
  "chatTypography",
@@ -9420,6 +9550,7 @@ const SETTINGS_STATE_FIELDS = [
9420
9550
  ];
9421
9551
  const CONFIG_SYNC_EXCLUDED_STATE_FIELDS = /* @__PURE__ */ new Set([
9422
9552
  "hashlineEditEnabled",
9553
+ "pinnedModels",
9423
9554
  "approvalAutoManage",
9424
9555
  "approvalAllowThreshold",
9425
9556
  "privacyMasking",
@@ -9497,6 +9628,9 @@ function notifyMemoryEmbeddingSettings(settings) {
9497
9628
  function notifyTrayToggleShortcut(settings) {
9498
9629
  settingsStateOf(settings).keybindings;
9499
9630
  }
9631
+ function notifyAppLanguage(previous, next) {
9632
+ if (settingsStateOf(previous).language !== settingsStateOf(next).language) ;
9633
+ }
9500
9634
  function notifySpeechSettings(settings) {
9501
9635
  const state = settingsStateOf(settings);
9502
9636
  void Promise.resolve().then(() => service$1).then(({ syncSpeechFromSettings: syncSpeechFromSettings2 }) => syncSpeechFromSettings2(state)).catch(() => {
@@ -9628,6 +9762,7 @@ function scheduleWrite(data, sender2, broadcast2 = "exclude-sender", patchedRemo
9628
9762
  notifyMemoryEmbeddingSettings(data);
9629
9763
  notifyTrayToggleShortcut(data);
9630
9764
  notifySpeechSettings(data);
9765
+ notifyAppLanguage(previous, data);
9631
9766
  if (settingsStateOf(previous).botModeEnabled !== settingsStateOf(data).botModeEnabled || settingsStateOf(previous).botMaxRunningTurns !== settingsStateOf(data).botMaxRunningTurns) {
9632
9767
  void Promise.resolve().then(() => bots).then(({ syncBotModeServices: syncBotModeServices2 }) => syncBotModeServices2()).catch(() => {
9633
9768
  });
@@ -10097,6 +10232,272 @@ async function installDcg(opts) {
10097
10232
  async function uninstallDcg(root) {
10098
10233
  await fs.promises.rm(baseDir(root), { recursive: true, force: true });
10099
10234
  }
10235
+ class ElevationBroker {
10236
+ constructor(deps) {
10237
+ this.deps = deps;
10238
+ }
10239
+ deps;
10240
+ pending = /* @__PURE__ */ new Map();
10241
+ /** sudo pid → 上次交出口令的时刻;同一 sudo 再来要说明口令错了 */
10242
+ answered = /* @__PURE__ */ new Map();
10243
+ get timeoutMs() {
10244
+ return this.deps.timeoutMs ?? ELEVATE_TIMEOUT_MS;
10245
+ }
10246
+ now() {
10247
+ return this.deps.now?.() ?? Date.now();
10248
+ }
10249
+ request(input) {
10250
+ const clash = [...this.pending.values()].find(
10251
+ (entry) => entry.sudoPid === input.sudoPid || entry.helperPid === input.helperPid
10252
+ );
10253
+ if (clash) {
10254
+ clash.settle({ kind: "declined" });
10255
+ return { id: null, outcome: Promise.resolve({ kind: "declined" }) };
10256
+ }
10257
+ if (!this.deps.canPresent()) {
10258
+ return { id: null, outcome: Promise.resolve({ kind: "unavailable" }) };
10259
+ }
10260
+ const now = this.now();
10261
+ for (const [pid, at] of this.answered) {
10262
+ if (now - at > this.timeoutMs) this.answered.delete(pid);
10263
+ }
10264
+ const id = randomUUID();
10265
+ const view = {
10266
+ id,
10267
+ command: input.command,
10268
+ retry: this.answered.has(input.sudoPid),
10269
+ expiresAt: now + this.timeoutMs
10270
+ };
10271
+ const outcome2 = new Promise((resolve2) => {
10272
+ const timer2 = setTimeout(() => entry.settle({ kind: "timeout" }), this.timeoutMs);
10273
+ const entry = {
10274
+ view,
10275
+ sudoPid: input.sudoPid,
10276
+ helperPid: input.helperPid,
10277
+ settle: (result) => {
10278
+ if (this.pending.get(id) !== entry) return;
10279
+ clearTimeout(timer2);
10280
+ this.pending.delete(id);
10281
+ if (result.kind === "password") this.answered.set(input.sudoPid, this.now());
10282
+ resolve2(result);
10283
+ this.deps.changed(this.list());
10284
+ }
10285
+ };
10286
+ this.pending.set(id, entry);
10287
+ });
10288
+ this.deps.changed(this.list());
10289
+ return { id, outcome: outcome2 };
10290
+ }
10291
+ /** password 为 null 表示拒绝;请求已不在(超时/被别处应答)返回 false */
10292
+ answer(id, password) {
10293
+ const entry = this.pending.get(id);
10294
+ if (!entry) return false;
10295
+ entry.settle(password === null ? { kind: "declined" } : { kind: "password", password });
10296
+ return true;
10297
+ }
10298
+ /** sudo 已退出(命令被中止) */
10299
+ cancel(id) {
10300
+ this.pending.get(id)?.settle({ kind: "declined" });
10301
+ }
10302
+ declineAll() {
10303
+ for (const entry of [...this.pending.values()]) entry.settle({ kind: "declined" });
10304
+ }
10305
+ list() {
10306
+ return [...this.pending.values()].map((entry) => entry.view);
10307
+ }
10308
+ }
10309
+ const MAX_REQUEST = 4096;
10310
+ function psField(pid, field) {
10311
+ return new Promise((resolve2) => {
10312
+ execFile(
10313
+ "ps",
10314
+ ["-ww", "-o", `${field}=`, "-p", String(pid)],
10315
+ (error, stdout) => resolve2(error ? null : stdout.replace(/\n+$/, ""))
10316
+ );
10317
+ });
10318
+ }
10319
+ const inspectProcess = async (pid) => {
10320
+ const [ppid, comm, args] = await Promise.all([
10321
+ psField(pid, "ppid"),
10322
+ psField(pid, "comm"),
10323
+ psField(pid, "args")
10324
+ ]);
10325
+ if (ppid === null || comm === null || args === null) return null;
10326
+ return { ppid: Number(ppid.trim()), comm: comm.trim(), args };
10327
+ };
10328
+ function helperSource(socketPath2, token) {
10329
+ const marks = {
10330
+ declined: ELEVATE_DECLINED_MARKER,
10331
+ timeout: ELEVATE_TIMED_OUT_MARKER,
10332
+ unavailable: ELEVATE_UNAVAILABLE_MARKER
10333
+ };
10334
+ return `'use strict';
10335
+ // EnsoCode sudo askpass:向 Main 要口令,只经 stdout 交给 sudo
10336
+ const load = require;
10337
+ const net = load('node:net');
10338
+ const MARKS = ${JSON.stringify(marks)};
10339
+ let done = false;
10340
+ const fail = (kind) => {
10341
+ if (done) return;
10342
+ done = true;
10343
+ process.stderr.write((MARKS[kind] || MARKS.declined) + '\\n');
10344
+ process.exit(1);
10345
+ };
10346
+ const socket = net.connect(${JSON.stringify(socketPath2)}, () =>
10347
+ socket.write(JSON.stringify({ token: ${JSON.stringify(token)}, pid: process.pid }) + '\\n')
10348
+ );
10349
+ let buf = '';
10350
+ socket.setEncoding('utf8');
10351
+ socket.on('data', (chunk) => { buf += chunk; });
10352
+ socket.on('end', () => {
10353
+ let reply = null;
10354
+ try { reply = JSON.parse(buf); } catch {}
10355
+ if (reply && reply.kind === 'password' && typeof reply.password === 'string') {
10356
+ done = true;
10357
+ process.stdout.write(reply.password + '\\n', () => process.exit(0));
10358
+ return;
10359
+ }
10360
+ fail(reply && reply.kind);
10361
+ });
10362
+ socket.on('error', () => fail('unavailable'));
10363
+ `;
10364
+ }
10365
+ function startElevationServer(options) {
10366
+ const { dir, broker } = options;
10367
+ const inspect = options.inspect ?? inspectProcess;
10368
+ mkdirSync(dir, { recursive: true, mode: 448 });
10369
+ chmodSync(dir, 448);
10370
+ const socketPath2 = path.join(dir, "s.sock");
10371
+ const cjsPath = path.join(dir, "askpass.cjs");
10372
+ const askpassPath = path.join(dir, "askpass");
10373
+ const token = randomBytes(32).toString("hex");
10374
+ const tokenBytes = Buffer.from(token);
10375
+ rmSync(socketPath2, { force: true });
10376
+ writeFileSync(cjsPath, helperSource(socketPath2, token), { mode: 384 });
10377
+ writeFileSync(
10378
+ askpassPath,
10379
+ `#!/bin/sh
10380
+ ELECTRON_RUN_AS_NODE=1 exec ${shellQuote(options.execPath)} ${shellQuote(cjsPath)} "$@"
10381
+ `,
10382
+ { mode: 448 }
10383
+ );
10384
+ chmodSync(cjsPath, 384);
10385
+ chmodSync(askpassPath, 448);
10386
+ const tokenOk = (value) => {
10387
+ if (typeof value !== "string") return false;
10388
+ const bytes = Buffer.from(value);
10389
+ return bytes.length === tokenBytes.length && timingSafeEqual(bytes, tokenBytes);
10390
+ };
10391
+ const serve2 = async (line2, socket) => {
10392
+ const declined = { kind: "declined" };
10393
+ let message2;
10394
+ try {
10395
+ message2 = JSON.parse(line2);
10396
+ } catch {
10397
+ return declined;
10398
+ }
10399
+ if (!tokenOk(message2?.token)) return declined;
10400
+ const helperPid = message2.pid;
10401
+ if (typeof helperPid !== "number" || !Number.isInteger(helperPid) || helperPid <= 1) {
10402
+ return declined;
10403
+ }
10404
+ const helper = await inspect(helperPid);
10405
+ if (!helper?.args.includes(cjsPath) || helper.ppid <= 1) return declined;
10406
+ const sudo = await inspect(helper.ppid);
10407
+ if (!sudo || path.basename(sudo.comm) !== "sudo") return declined;
10408
+ const command = elevatedCommandOf(sudo.args);
10409
+ if (command === null) return declined;
10410
+ if (socket.destroyed) return declined;
10411
+ const { id, outcome: outcome2 } = broker.request({ command, sudoPid: helper.ppid, helperPid });
10412
+ if (id) socket.once("close", () => broker.cancel(id));
10413
+ return outcome2;
10414
+ };
10415
+ const server2 = createServer((socket) => {
10416
+ let buf = "";
10417
+ let started = false;
10418
+ socket.setEncoding("utf8");
10419
+ socket.on("error", () => {
10420
+ });
10421
+ socket.on("data", (chunk) => {
10422
+ if (started) return;
10423
+ buf += chunk;
10424
+ if (buf.length > MAX_REQUEST) {
10425
+ socket.destroy();
10426
+ return;
10427
+ }
10428
+ const newline = buf.indexOf("\n");
10429
+ if (newline < 0) return;
10430
+ started = true;
10431
+ const reply = (outcome2) => {
10432
+ if (!socket.destroyed) socket.end(`${JSON.stringify(outcome2)}
10433
+ `);
10434
+ };
10435
+ serve2(buf.slice(0, newline), socket).then(reply, () => reply({ kind: "declined" }));
10436
+ });
10437
+ });
10438
+ const ready = new Promise((resolve2, reject) => {
10439
+ server2.once("error", reject);
10440
+ server2.listen(socketPath2, () => {
10441
+ server2.off("error", reject);
10442
+ chmodSync(socketPath2, 384);
10443
+ resolve2();
10444
+ });
10445
+ });
10446
+ return {
10447
+ askpassPath,
10448
+ ready,
10449
+ close: () => {
10450
+ broker.declineAll();
10451
+ server2.close();
10452
+ rmSync(dir, { recursive: true, force: true });
10453
+ }
10454
+ };
10455
+ }
10456
+ let shown = 0;
10457
+ const elevationBroker = new ElevationBroker({
10458
+ canPresent: isMainRendererAlive,
10459
+ changed: (views) => {
10460
+ sendToLocalMain(IPC_CHANNELS.ELEVATION_CHANGED, views);
10461
+ for (const sender2 of remoteSenders()) {
10462
+ if (sender2.kind === "main") sender2.send(IPC_CHANNELS.ELEVATION_CHANGED, views);
10463
+ }
10464
+ if (views.length > shown && true) {
10465
+ notification.show({
10466
+ title: "EnsoCode",
10467
+ body: translate(readLocale(), "A command is waiting for the administrator password")
10468
+ });
10469
+ }
10470
+ shown = views.length;
10471
+ }
10472
+ });
10473
+ const canAnswerElevation = isMainRenderer;
10474
+ let server$1;
10475
+ function ensureElevationServer() {
10476
+ if (server$1 !== void 0) return server$1?.askpassPath ?? null;
10477
+ server$1 = null;
10478
+ if (process.platform === "win32") return null;
10479
+ try {
10480
+ const started = startElevationServer({
10481
+ dir: mkdtempSync(path.join(tmpdir(), "enso-elev-")),
10482
+ broker: elevationBroker,
10483
+ execPath: process.execPath
10484
+ });
10485
+ started.ready.catch(
10486
+ (error) => console.warn(
10487
+ "[elevation] askpass server failed",
10488
+ error instanceof Error ? error.message : error
10489
+ )
10490
+ );
10491
+ process.once("exit", () => started.close());
10492
+ server$1 = started;
10493
+ } catch (error) {
10494
+ console.warn(
10495
+ "[elevation] askpass server failed",
10496
+ error instanceof Error ? error.message : error
10497
+ );
10498
+ }
10499
+ return server$1?.askpassPath ?? null;
10500
+ }
10100
10501
  const DEFAULT_CLAUDE_PLUGINS_DIR = path.join(os.homedir(), ".claude", "plugins");
10101
10502
  const MAX_FILE_BYTES$2 = 256 * 1024;
10102
10503
  const READONLY_TOOLS = /* @__PURE__ */ new Set([
@@ -10120,7 +10521,7 @@ function expandPluginVars(input, vars) {
10120
10521
  return value === void 0 || value === "" ? fallback ?? "" : value;
10121
10522
  });
10122
10523
  }
10123
- function readJson$4(file2) {
10524
+ function readJson$5(file2) {
10124
10525
  try {
10125
10526
  const stat2 = fs.statSync(file2);
10126
10527
  if (!stat2.isFile() || stat2.size > MAX_FILE_BYTES$2) return void 0;
@@ -10178,7 +10579,7 @@ function pluginDataDir(pluginsDir, key) {
10178
10579
  return path.join(pluginsDir, "data", key.replace(/[^a-zA-Z0-9_-]/g, "-"));
10179
10580
  }
10180
10581
  function listInstalledPlugins(pluginsDir = DEFAULT_CLAUDE_PLUGINS_DIR) {
10181
- const file2 = readJson$4(path.join(pluginsDir, "installed_plugins.json"));
10582
+ const file2 = readJson$5(path.join(pluginsDir, "installed_plugins.json"));
10182
10583
  const plugins = isRecord$b(file2) && isRecord$b(file2.plugins) ? file2.plugins : {};
10183
10584
  const result = [];
10184
10585
  for (const [key, installs] of Object.entries(plugins)) {
@@ -10201,15 +10602,15 @@ function listInstalledPlugins(pluginsDir = DEFAULT_CLAUDE_PLUGINS_DIR) {
10201
10602
  return result;
10202
10603
  }
10203
10604
  function marketplaceEntry(pluginsDir, plugin) {
10204
- const file2 = readJson$4(
10605
+ const file2 = readJson$5(
10205
10606
  path.join(pluginsDir, "marketplaces", plugin.marketplace, ".claude-plugin", "marketplace.json")
10206
10607
  );
10207
10608
  const entries = isRecord$b(file2) && Array.isArray(file2.plugins) ? file2.plugins : [];
10208
10609
  const entry = entries.find((item) => isRecord$b(item) && item.name === plugin.name);
10209
10610
  return isRecord$b(entry) ? entry : {};
10210
10611
  }
10211
- function readManifest(pluginsDir, plugin) {
10212
- const own = readJson$4(path.join(plugin.root, ".claude-plugin", "plugin.json")) ?? readJson$4(path.join(plugin.root, ".codex-plugin", "plugin.json"));
10612
+ function readManifest$1(pluginsDir, plugin) {
10613
+ const own = readJson$5(path.join(plugin.root, ".claude-plugin", "plugin.json")) ?? readJson$5(path.join(plugin.root, ".codex-plugin", "plugin.json"));
10213
10614
  const market = plugin.marketplace ? marketplaceEntry(pluginsDir, plugin) : {};
10214
10615
  const base = market.strict === false ? market : { description: market.description };
10215
10616
  return { ...base, ...isRecord$b(own) ? own : {} };
@@ -10278,7 +10679,7 @@ function mcpSources(root, manifest) {
10278
10679
  const declared = manifest.mcpServers;
10279
10680
  if (isRecord$b(declared)) return [declared];
10280
10681
  const files = declared === void 0 ? [path.join(root, ".mcp.json")] : manifestPaths(root, declared, ".mcp.json");
10281
- return files.map(readJson$4).filter(isRecord$b);
10682
+ return files.map(readJson$5).filter(isRecord$b);
10282
10683
  }
10283
10684
  function readMcpServers(root, manifest, pluginKey, vars) {
10284
10685
  const servers = [];
@@ -10310,13 +10711,13 @@ function readMcpServers(root, manifest, pluginKey, vars) {
10310
10711
  }
10311
10712
  return servers;
10312
10713
  }
10313
- function readHooks(root, manifest, pluginName, dataDir, unsupported) {
10714
+ function readHooks(root, manifest, pluginName, dataDir2, unsupported) {
10314
10715
  const declared = manifest.hooks;
10315
- const sources = [readJson$4(path.join(root, "hooks", "hooks.json"))];
10716
+ const sources = [readJson$5(path.join(root, "hooks", "hooks.json"))];
10316
10717
  if (isRecord$b(declared)) sources.push(declared);
10317
10718
  else if (declared !== void 0) {
10318
10719
  for (const file2 of manifestPaths(root, declared, "hooks/hooks.json")) {
10319
- if (file2 !== path.join(root, "hooks", "hooks.json")) sources.push(readJson$4(file2));
10720
+ if (file2 !== path.join(root, "hooks", "hooks.json")) sources.push(readJson$5(file2));
10320
10721
  }
10321
10722
  }
10322
10723
  const hooks2 = [];
@@ -10344,7 +10745,7 @@ function readHooks(root, manifest, pluginName, dataDir, unsupported) {
10344
10745
  hooks2.push({
10345
10746
  plugin: pluginName,
10346
10747
  root,
10347
- dataDir,
10748
+ dataDir: dataDir2,
10348
10749
  event,
10349
10750
  ...matcher ? { matcher } : {},
10350
10751
  command,
@@ -10363,10 +10764,10 @@ const UNSUPPORTED_KEYS = [
10363
10764
  ["userConfig", ""]
10364
10765
  ];
10365
10766
  function readPluginComponents(plugin, options) {
10366
- const manifest = readManifest(options.pluginsDir, plugin);
10767
+ const manifest = readManifest$1(options.pluginsDir, plugin);
10367
10768
  const pluginName = text$4(manifest.name) || plugin.name;
10368
- const dataDir = pluginDataDir(options.pluginsDir, plugin.key);
10369
- const vars = { root: plugin.root, data: dataDir, env: options.env };
10769
+ const dataDir2 = pluginDataDir(options.pluginsDir, plugin.key);
10770
+ const vars = { root: plugin.root, data: dataDir2, env: options.env };
10370
10771
  const unsupported = /* @__PURE__ */ new Set();
10371
10772
  const skills = readSkills(plugin.root, manifest);
10372
10773
  const components = {
@@ -10375,7 +10776,7 @@ function readPluginComponents(plugin, options) {
10375
10776
  commands: readCommands(plugin.root, manifest, pluginName, vars),
10376
10777
  agents: readAgents(plugin.root, manifest, pluginName, skills, vars),
10377
10778
  mcpServers: readMcpServers(plugin.root, manifest, plugin.key, vars),
10378
- hooks: readHooks(plugin.root, manifest, pluginName, dataDir, unsupported),
10779
+ hooks: readHooks(plugin.root, manifest, pluginName, dataDir2, unsupported),
10379
10780
  unsupported: []
10380
10781
  };
10381
10782
  for (const [key, file2] of UNSUPPORTED_KEYS) {
@@ -10938,11 +11339,32 @@ async function downloadPluginArchive(url, dest, options) {
10938
11339
  function isArchiveError(message2) {
10939
11340
  return message2 === "插件过大" || message2 === "重定向过多" || message2 === "重定向地址不合法" || message2 === "下载没有内容" || message2.startsWith("下载失败(HTTP ");
10940
11341
  }
11342
+ const MARKET_CATEGORIES = [
11343
+ "themes",
11344
+ "agent",
11345
+ "productivity",
11346
+ "integrations",
11347
+ "insights",
11348
+ "writing",
11349
+ "fun"
11350
+ ];
11351
+ const isMarketCategory = (value) => MARKET_CATEGORIES.includes(value);
11352
+ const MAX_MARKET_SCREENSHOTS = 6;
10941
11353
  const isRecord$8 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
10942
11354
  const str$9 = (v, max) => typeof v === "string" && v.trim().length > 0 && v.length <= max;
10943
11355
  const strings = (v, max) => Array.isArray(v) ? v.filter((s) => str$9(s, max)) : [];
10944
11356
  const optStr = (v, max) => str$9(v, max) ? v : void 0;
10945
11357
  const README_MAX_BYTES$1 = 256 * 1024;
11358
+ function parseScreenshots(raw) {
11359
+ if (!Array.isArray(raw)) return void 0;
11360
+ const shots = [];
11361
+ for (const item of raw) {
11362
+ if (shots.length >= MAX_MARKET_SCREENSHOTS) break;
11363
+ if (!isRecord$8(item) || !str$9(item.url, 1e3) || !item.url.startsWith("https://")) continue;
11364
+ shots.push({ url: item.url, alt: typeof item.alt === "string" ? item.alt.slice(0, 200) : "" });
11365
+ }
11366
+ return shots.length > 0 ? shots : void 0;
11367
+ }
10946
11368
  function parseReadme(raw) {
10947
11369
  if (!isRecord$8(raw)) return void 0;
10948
11370
  if (!isPluginRelativePath(raw.path) || !/^[A-Za-z0-9._/-]+$/.test(raw.path)) return void 0;
@@ -10976,6 +11398,7 @@ function parsePlugin(raw, hostVersion) {
10976
11398
  if (versions.length === 0) return null;
10977
11399
  const latest = versions.reduce((a, b) => isNewerPluginVersion(b.version, a.version) ? b : a);
10978
11400
  const readme = parseReadme(raw.readme);
11401
+ const screenshots = parseScreenshots(raw.screenshots);
10979
11402
  return {
10980
11403
  id: raw.id,
10981
11404
  name: raw.name,
@@ -10984,6 +11407,8 @@ function parsePlugin(raw, hostVersion) {
10984
11407
  tags: strings(raw.tags, 32),
10985
11408
  homepage: optStr(raw.homepage, 500),
10986
11409
  icon: optStr(raw.icon, 500),
11410
+ ...isMarketCategory(raw.category) ? { category: raw.category } : {},
11411
+ ...screenshots ? { screenshots } : {},
10987
11412
  ...readme ? { readme } : {},
10988
11413
  latest: latest.version,
10989
11414
  versions
@@ -11272,7 +11697,7 @@ function grantExpands(previous, next) {
11272
11697
  if (next.styles && !previous.styles) return true;
11273
11698
  return next.renderer && !previous.renderer;
11274
11699
  }
11275
- const MAX_BYTES$3 = 50 * 1024 * 1024;
11700
+ const MAX_BYTES$4 = 50 * 1024 * 1024;
11276
11701
  const MAX_COUNT = 200;
11277
11702
  class ArtifactStore {
11278
11703
  constructor(root) {
@@ -11292,7 +11717,7 @@ class ArtifactStore {
11292
11717
  const mime2 = typeof input.mime === "string" && input.mime.length > 0 ? input.mime : fallback;
11293
11718
  if (mime2.length > 200 || /[\r\n\0]/.test(mime2))
11294
11719
  throw pluginError("INVALID_ARGS", "mime 不合法");
11295
- if (body.length > MAX_BYTES$3) throw pluginError("TOO_LARGE", "产出超过 50MB");
11720
+ if (body.length > MAX_BYTES$4) throw pluginError("TOO_LARGE", "产出超过 50MB");
11296
11721
  const list2 = this.entries(pluginId);
11297
11722
  const entry = {
11298
11723
  id: randomUUID(),
@@ -11590,7 +12015,7 @@ const within$2 = (parent, child) => {
11590
12015
  const covered = (path2, scopes) => scopes.some((s) => s === "." || path2 === s || path2.startsWith(`${s}/`));
11591
12016
  const utf8Bytes = (s) => Buffer.byteLength(s, "utf8");
11592
12017
  const posixRel = (root, real) => relative(root, real).split(sep).join("/");
11593
- const isEnoent = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
12018
+ const isEnoent$1 = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
11594
12019
  function dropSensitiveHeaders(headers) {
11595
12020
  for (const key of Object.keys(headers)) {
11596
12021
  if (SENSITIVE_REQUEST_HEADERS.has(key.toLowerCase())) delete headers[key];
@@ -11752,6 +12177,43 @@ class PluginHostGate {
11752
12177
  this.deps.viewEvent(pluginId, a.name, JSON.parse(encoded));
11753
12178
  return null;
11754
12179
  }
12180
+ case "ui.statusUpdate": {
12181
+ const { id, ...rest } = a;
12182
+ if (typeof id !== "string" || !manifest.contributes.statusItems.some((item) => item.id === id))
12183
+ throw pluginError("INVALID_ARGS", "id 未在清单 statusItems 中声明");
12184
+ const patch = parseStatusPatch(rest);
12185
+ if (!patch) throw pluginError("INVALID_ARGS", "状态项字段不合法");
12186
+ if (!this.deps.statusUpdate) throw pluginError("UNSUPPORTED", "当前环境不能更新状态项");
12187
+ this.admitViewEvent(pluginId);
12188
+ this.deps.statusUpdate(pluginId, id, patch);
12189
+ return null;
12190
+ }
12191
+ case "ui.viewOpen": {
12192
+ permit("ui.view");
12193
+ const inv = invocation();
12194
+ const current2 = sessionOf(inv);
12195
+ const views = manifest.contributes.views;
12196
+ const view = a.viewId === void 0 ? views[0] : typeof a.viewId === "string" ? views.find((v) => v.id === a.viewId) : void 0;
12197
+ if (!view) throw pluginError("INVALID_ARGS", "viewId 不合法或未在清单 views 中声明");
12198
+ let targetSessionId = current2.split("::")[0];
12199
+ if (a.sessionId !== void 0) {
12200
+ if (typeof a.sessionId !== "string" || a.sessionId.length === 0 || a.sessionId.length > 256)
12201
+ throw pluginError("INVALID_ARGS", "sessionId 不合法");
12202
+ const candidate = a.sessionId.split("::")[0];
12203
+ if (candidate !== targetSessionId) {
12204
+ const visible = this.deps.sessions?.list(current2) ?? [];
12205
+ if (!visible.some((s) => s.id === candidate))
12206
+ throw pluginError("NOT_FOUND", "会话不存在或不在本项目");
12207
+ targetSessionId = candidate;
12208
+ }
12209
+ }
12210
+ await sessionUi()(
12211
+ { sessionId: targetSessionId, origin: inv.origin ?? null },
12212
+ "openPluginView",
12213
+ { pluginId, viewId: view.id, title: view.title }
12214
+ );
12215
+ return null;
12216
+ }
11755
12217
  case "composer.readDraft":
11756
12218
  case "composer.insertText":
11757
12219
  case "composer.replaceDraft": {
@@ -12053,7 +12515,7 @@ class PluginHostGate {
12053
12515
  /** 写入目标不存在时,对最近一个已存在的父目录做 realpath,再拼回缺失部分 */
12054
12516
  async locateForWrite(target) {
12055
12517
  const existing = await lstat(target).catch((error) => {
12056
- if (isEnoent(error)) return null;
12518
+ if (isEnoent$1(error)) return null;
12057
12519
  throw error;
12058
12520
  });
12059
12521
  if (existing?.isSymbolicLink()) throw pluginError("PERMISSION_DENIED", "不能写入符号链接");
@@ -12069,7 +12531,7 @@ class PluginHostGate {
12069
12531
  try {
12070
12532
  st = await lstat(dir);
12071
12533
  } catch (error) {
12072
- if (isEnoent(error)) continue;
12534
+ if (isEnoent$1(error)) continue;
12073
12535
  throw error;
12074
12536
  }
12075
12537
  if (!st.isDirectory() && !st.isSymbolicLink()) throw pluginError("NOT_FOUND", "父目录不存在");
@@ -12416,8 +12878,8 @@ function errorCode(err) {
12416
12878
  }
12417
12879
  const MANIFEST_FILE = "enso-plugin.json";
12418
12880
  const MAX_FILES$3 = 5e3;
12419
- const MAX_BYTES$2 = 200 * 1024 * 1024;
12420
- const ZIP_LIMITS = { maxEntries: MAX_FILES$3, maxEntryBytes: MAX_BYTES$2, maxTotalBytes: MAX_BYTES$2 };
12881
+ const MAX_BYTES$3 = 200 * 1024 * 1024;
12882
+ const ZIP_LIMITS = { maxEntries: MAX_FILES$3, maxEntryBytes: MAX_BYTES$3, maxTotalBytes: MAX_BYTES$3 };
12421
12883
  const MAX_MANIFEST_BYTES = 256 * 1024;
12422
12884
  const SKIPPED = /* @__PURE__ */ new Set([".git", ".DS_Store"]);
12423
12885
  const pluginPackagePath = (root, id, dir) => join(root, "packages", id, dir);
@@ -12443,7 +12905,7 @@ async function copyInside(src, dest, budget, sourceRoot, destRoot, realSourceRoo
12443
12905
  assertContainedLinkTarget(destRoot, to, linkTarget, label2);
12444
12906
  budget.files += 1;
12445
12907
  budget.bytes += info.size;
12446
- if (budget.files > MAX_FILES$3 || budget.bytes > MAX_BYTES$2) throw new Error("插件过大");
12908
+ if (budget.files > MAX_FILES$3 || budget.bytes > MAX_BYTES$3) throw new Error("插件过大");
12447
12909
  await symlink(linkTarget, to);
12448
12910
  continue;
12449
12911
  }
@@ -12454,7 +12916,7 @@ async function copyInside(src, dest, budget, sourceRoot, destRoot, realSourceRoo
12454
12916
  if (!info.isFile()) throw new Error(`插件目录包含不支持的文件类型:${name}`);
12455
12917
  budget.files += 1;
12456
12918
  budget.bytes += info.size;
12457
- if (budget.files > MAX_FILES$3 || budget.bytes > MAX_BYTES$2) throw new Error("插件过大");
12919
+ if (budget.files > MAX_FILES$3 || budget.bytes > MAX_BYTES$3) throw new Error("插件过大");
12458
12920
  await copyFile(from, to);
12459
12921
  }
12460
12922
  }
@@ -12525,7 +12987,8 @@ async function verifyReferences(pluginRoot, manifest) {
12525
12987
  manifest.renderer,
12526
12988
  manifest.icon,
12527
12989
  ...manifest.contributes.views.map((v) => v.entry),
12528
- ...manifest.contributes.themes.flatMap((theme2) => [theme2.path, theme2.css])
12990
+ ...manifest.contributes.themes.flatMap((theme2) => [theme2.path, theme2.css]),
12991
+ ...manifest.contributes.workflows
12529
12992
  ].filter((p) => typeof p === "string");
12530
12993
  for (const rel of files) {
12531
12994
  if (!await exists(resolve(pluginRoot, rel), "file"))
@@ -12578,7 +13041,7 @@ async function stagePlugin(root, source, hostVersion, deps = {}) {
12578
13041
  const tree = join(staging, "tree");
12579
13042
  await downloadPluginArchive(resolved.archive, zipPath, {
12580
13043
  fetch: deps.fetch ?? fetch,
12581
- maxBytes: MAX_BYTES$2,
13044
+ maxBytes: MAX_BYTES$3,
12582
13045
  ...deps.timeoutMs === void 0 ? {} : { timeoutMs: deps.timeoutMs }
12583
13046
  });
12584
13047
  await extractZip(zipPath, tree, ZIP_LIMITS);
@@ -12905,7 +13368,7 @@ function writeRegistry(root, file2) {
12905
13368
  writeFileSync(tmp, JSON.stringify(file2, null, 2), { mode: 384 });
12906
13369
  renameSync(tmp, target);
12907
13370
  }
12908
- const MAX_BYTES$1 = 1024 * 1024;
13371
+ const MAX_BYTES$2 = 1024 * 1024;
12909
13372
  const ID = /^[a-z][a-z0-9]*(\.[a-z0-9]+)+$/;
12910
13373
  class ViewStateStore {
12911
13374
  constructor(root) {
@@ -12936,7 +13399,7 @@ class ViewStateStore {
12936
13399
  else next[key] = value;
12937
13400
  }
12938
13401
  const text2 = JSON.stringify(next);
12939
- if (Buffer.byteLength(text2) > MAX_BYTES$1) return { ok: false, error: "侧栏状态超过 1MB" };
13402
+ if (Buffer.byteLength(text2) > MAX_BYTES$2) return { ok: false, error: "侧栏状态超过 1MB" };
12940
13403
  if (Object.keys(next).length === 0) {
12941
13404
  rmSync(this.path(pluginId), { force: true });
12942
13405
  return { ok: true };
@@ -12966,6 +13429,17 @@ const COMMAND_TIMEOUT_MS = 6e4;
12966
13429
  const SCHEDULE_TIMEOUT_MS = 6e4;
12967
13430
  const PREPARE_TIMEOUT_MS = 5e3;
12968
13431
  const CHANGE_DEBOUNCE_MS = 150;
13432
+ const DEV_RELOAD_DELAY_MS = 400;
13433
+ const DEV_IGNORED = /(^|[\\/])(\.[^\\/]*|node_modules)([\\/]|$)|\.zip$/;
13434
+ function watchPluginDir(dir, onChange) {
13435
+ const watcher = watch(dir, { recursive: true }, (_event, filename) => {
13436
+ if (filename && DEV_IGNORED.test(String(filename))) return;
13437
+ onChange();
13438
+ });
13439
+ watcher.on("error", () => {
13440
+ });
13441
+ return { close: () => watcher.close() };
13442
+ }
12969
13443
  const PLUGIN_ID_PATTERN = /^[a-z][a-z0-9]*(\.[a-z0-9]+)+$/;
12970
13444
  const INTERCEPT_BREAKER_FAILURES = 3;
12971
13445
  const INTERCEPT_BREAKER_MS = 3e4;
@@ -13016,6 +13490,13 @@ class ExtensionPluginService {
13016
13490
  manifest: (id) => this.gateManifests.get(id) ?? this.enabledManifest(id),
13017
13491
  config: (id) => this.pluginConfig(id),
13018
13492
  progress: (invocationId, text2) => this.progressTaps.get(invocationId)?.(text2),
13493
+ statusUpdate: (pluginId, id, patch) => {
13494
+ const current2 = this.statusState.get(pluginId) ?? {};
13495
+ const next = { ...current2[id], ...patch };
13496
+ if (JSON.stringify(next) === JSON.stringify(current2[id] ?? {})) return;
13497
+ this.statusState.set(pluginId, { ...current2, [id]: next });
13498
+ this.touch();
13499
+ },
13019
13500
  writeArtifact: (pluginId, input) => this.artifacts.write(pluginId, input),
13020
13501
  inject: (pluginId, input) => this.inject(pluginId, input),
13021
13502
  abort: (pluginId, sessionId) => {
@@ -13068,6 +13549,10 @@ class ExtensionPluginService {
13068
13549
  artifacts;
13069
13550
  viewState;
13070
13551
  dynamic = new DynamicContribs();
13552
+ /** 开发模式:目录来源插件的监听与去抖计时;只在内存里,重启后关闭 */
13553
+ devWatchers = /* @__PURE__ */ new Map();
13554
+ /** 运行期状态项补丁,重启应用后回到清单值 */
13555
+ statusState = /* @__PURE__ */ new Map();
13071
13556
  progressTaps = /* @__PURE__ */ new Map();
13072
13557
  gateManifests = /* @__PURE__ */ new Map();
13073
13558
  trialing = /* @__PURE__ */ new Set();
@@ -13110,6 +13595,11 @@ class ExtensionPluginService {
13110
13595
  })),
13111
13596
  commands: manifest.contributes.commands,
13112
13597
  views: manifest.contributes.views.map(({ id, title, entry }) => ({ id, title, entry })),
13598
+ fileViewers: manifest.contributes.fileViewers,
13599
+ statusItems: mergeStatusItems(
13600
+ manifest.contributes.statusItems,
13601
+ this.statusState.get(record2.id) ?? {}
13602
+ ),
13113
13603
  // css 只在用户同意过样式能力时下发,渲染层据此决定读不读
13114
13604
  themes: manifest.contributes.themes.map(
13115
13605
  ({ css, ...theme2 }) => css !== void 0 && record2.grant.styles ? { ...theme2, css } : theme2
@@ -13143,9 +13633,14 @@ class ExtensionPluginService {
13143
13633
  events: manifest.contributes.events.map(({ event, mode: mode2 }) => ({ event, mode: mode2 })),
13144
13634
  ...this.openInterceptBreakers(record2.id).length > 0 ? { interceptBreakers: this.openInterceptBreakers(record2.id) } : {},
13145
13635
  ...record2.grant.permissions.includes("agent.inject") ? { crossSessionInject: record2.crossSessionInject } : {},
13146
- ...record2.pending && pending2 ? { pendingVersion: record2.pending.version, pendingPermissions: pending2.permissions } : {},
13636
+ ...record2.pending && pending2 ? {
13637
+ pendingVersion: record2.pending.version,
13638
+ pendingPermissions: pending2.permissions,
13639
+ ...pending2.renderer !== void 0 && !record2.grant.renderer ? { pendingRenderer: true } : {}
13640
+ } : {},
13147
13641
  ...lastErrorField(record2.lastError ?? this.recentErrors.get(record2.id)),
13148
13642
  ...record2.source ? { source: sourceView(record2.source) } : {},
13643
+ ...record2.source?.kind === "dir" ? { devWatch: this.devWatchers.has(record2.id) } : {},
13149
13644
  ...updateFields(this.updates.get(record2.id))
13150
13645
  }
13151
13646
  ];
@@ -13242,6 +13737,10 @@ class ExtensionPluginService {
13242
13737
  }
13243
13738
  }
13244
13739
  const icon = marketIconUrl(p.icon);
13740
+ const screenshots = p.screenshots?.flatMap((shot) => {
13741
+ const url = marketIconUrl(shot.url);
13742
+ return url ? [{ url, alt: shot.alt }] : [];
13743
+ });
13245
13744
  return {
13246
13745
  id: p.id,
13247
13746
  name: p.name,
@@ -13250,6 +13749,8 @@ class ExtensionPluginService {
13250
13749
  tags: p.tags,
13251
13750
  ...p.homepage ? { homepage: p.homepage } : {},
13252
13751
  ...icon ? { icon } : {},
13752
+ ...p.category ? { category: p.category } : {},
13753
+ ...screenshots?.length ? { screenshots } : {},
13253
13754
  latest: p.latest,
13254
13755
  permissions: p.versions.find((v) => v.version === p.latest)?.permissions ?? [],
13255
13756
  ...installed2 ? { installedVersion: installed2 } : {},
@@ -13380,6 +13881,67 @@ class ExtensionPluginService {
13380
13881
  this.injectDeniedNotified.delete(id);
13381
13882
  return { ok: true };
13382
13883
  }
13884
+ /** 开发模式:目录来源的插件改动后自动重装;授权扩大时不自动同意,记一条错误 */
13885
+ setDevWatch(id, on) {
13886
+ const record2 = this.records.find((r) => r.id === id);
13887
+ if (!record2) return { ok: false, error: "插件未安装" };
13888
+ const source = record2.source;
13889
+ if (source?.kind !== "dir") return { ok: false, error: "只有从目录安装的插件能开开发模式" };
13890
+ if (!on) {
13891
+ if (this.devWatchers.has(id)) {
13892
+ this.closeDevWatch(id);
13893
+ this.touch();
13894
+ }
13895
+ return { ok: true };
13896
+ }
13897
+ if (this.devWatchers.has(id)) return { ok: true };
13898
+ const watch2 = this.options.devWatch ?? watchPluginDir;
13899
+ const entry = {
13900
+ close: () => {
13901
+ },
13902
+ timer: null
13903
+ };
13904
+ try {
13905
+ entry.close = watch2(source.path, () => {
13906
+ if (entry.timer) clearTimeout(entry.timer);
13907
+ entry.timer = setTimeout(() => {
13908
+ entry.timer = null;
13909
+ void this.devReloadNow(id);
13910
+ }, this.options.devReloadDelayMs ?? DEV_RELOAD_DELAY_MS);
13911
+ }).close;
13912
+ } catch (error) {
13913
+ return {
13914
+ ok: false,
13915
+ error: `监听目录失败:${error instanceof Error ? error.message : String(error)}`
13916
+ };
13917
+ }
13918
+ this.devWatchers.set(id, entry);
13919
+ this.touch();
13920
+ return { ok: true };
13921
+ }
13922
+ /** 立即按来源目录重装一次;授权没扩大才落盘 */
13923
+ async devReloadNow(id) {
13924
+ const fail2 = (message2) => {
13925
+ this.recordError(id, message2);
13926
+ this.touch();
13927
+ };
13928
+ const staged = await this.restage(id);
13929
+ if (!staged.ok) return fail2(`开发模式重装失败:${staged.error}`);
13930
+ if (staged.preview.expands) {
13931
+ this.discard(staged.preview.token);
13932
+ return fail2("开发模式:新清单授权扩大,需要手动从来源重新安装并同意");
13933
+ }
13934
+ const committed = await this.commit(staged.preview.token);
13935
+ if (!committed.ok) return fail2(`开发模式重装失败:${committed.error}`);
13936
+ this.recentErrors.delete(id);
13937
+ }
13938
+ closeDevWatch(id) {
13939
+ const entry = this.devWatchers.get(id);
13940
+ if (!entry) return;
13941
+ if (entry.timer) clearTimeout(entry.timer);
13942
+ entry.close();
13943
+ this.devWatchers.delete(id);
13944
+ }
13383
13945
  approvePending(id) {
13384
13946
  return this.withIdLock(id, async () => {
13385
13947
  const oldDir = this.records.find((r) => r.id === id)?.dir;
@@ -13420,6 +13982,8 @@ class ExtensionPluginService {
13420
13982
  rmSync(`${this.logPath(id)}.1`, { force: true });
13421
13983
  this.recentErrors.delete(id);
13422
13984
  this.prepareFailed.delete(id);
13985
+ this.statusState.delete(id);
13986
+ this.closeDevWatch(id);
13423
13987
  this.invalidatePackageCache(id);
13424
13988
  this.syncBackground();
13425
13989
  return { ok: true };
@@ -13680,6 +14244,19 @@ class ExtensionPluginService {
13680
14244
  return this.contributedSkills(id, manifest, activePresetId).map((rel) => resolve(root, rel));
13681
14245
  });
13682
14246
  }
14247
+ /** workflow 预设文件的绝对路径,与 skill 同口径按插件预设圈定 */
14248
+ workflowPathsForSpawn(activePresetId) {
14249
+ return this.enabled().flatMap(({ id, dir, manifest }) => {
14250
+ const root = pluginPackagePath(this.options.root, id, dir);
14251
+ const { scoped, selected: selected2 } = presetSelection(
14252
+ manifest,
14253
+ id,
14254
+ activePresetId,
14255
+ (preset) => preset.workflows ?? []
14256
+ );
14257
+ return manifest.contributes.workflows.filter((rel) => !scoped.has(rel) || selected2.has(rel)).map((rel) => resolve(root, rel));
14258
+ });
14259
+ }
13683
14260
  /**
13684
14261
  * 已启用插件声明的子代理类型;正文读不出的跳过并记日志。技能目录不受预设范围影响。
13685
14262
  * 传 scope 时按会话生效的插件预设过滤:被预设圈定的类型只在该预设下发;不传则列出全部(设置页、派发)
@@ -13763,26 +14340,26 @@ class ExtensionPluginService {
13763
14340
  if (!presetId) return void 0;
13764
14341
  const parsed = parsePluginPresetId(presetId);
13765
14342
  if (!parsed) return void 0;
13766
- const loaded = this.enabled().find((entry) => entry.id === parsed.pluginId);
13767
- const preset = loaded?.manifest.contributes.presets.find((item) => item.id === parsed.localId);
13768
- if (!loaded || !preset) return { ok: false, error: "插件预设不可用,请重新选择或恢复默认。" };
13769
- const root = pluginPackagePath(this.options.root, loaded.id, loaded.dir);
14343
+ const loaded2 = this.enabled().find((entry) => entry.id === parsed.pluginId);
14344
+ const preset = loaded2?.manifest.contributes.presets.find((item) => item.id === parsed.localId);
14345
+ if (!loaded2 || !preset) return { ok: false, error: "插件预设不可用,请重新选择或恢复默认。" };
14346
+ const root = pluginPackagePath(this.options.root, loaded2.id, loaded2.dir);
13770
14347
  const read = (rel) => {
13771
14348
  if (!rel) return void 0;
13772
- return this.readText(loaded.id, loaded.dir, rel);
14349
+ return this.readText(loaded2.id, loaded2.dir, rel);
13773
14350
  };
13774
14351
  const instruction = read(preset.instruction);
13775
14352
  const role = read(preset.systemPrompt);
13776
- const tail = read(preset.systemPromptTail);
14353
+ const tail2 = read(preset.systemPromptTail);
13777
14354
  const boost = read(preset.boostPrompt);
13778
14355
  const retry = read(preset.refusalRetryPrompt);
13779
- if (instruction?.ok === false || role?.ok === false || tail?.ok === false || boost?.ok === false || retry?.ok === false)
14356
+ if (instruction?.ok === false || role?.ok === false || tail2?.ok === false || boost?.ok === false || retry?.ok === false)
13780
14357
  return { ok: false, error: "插件预设的正文读取失败,请重新安装插件。" };
13781
14358
  return {
13782
14359
  ok: true,
13783
14360
  ...instruction?.ok ? { instruction: { path: join(root, preset.instruction), content: instruction.content } } : {},
13784
14361
  ...role?.ok ? { systemPrompt: role.content } : {},
13785
- ...tail?.ok ? { systemPromptAppend: tail.content } : {},
14362
+ ...tail2?.ok ? { systemPromptAppend: tail2.content } : {},
13786
14363
  ...boost?.ok ? { systemPromptBoost: boost.content } : {},
13787
14364
  ...preset.refusalRetry === true && retry?.ok ? { refusalRetryPrompt: retry.content } : {},
13788
14365
  ...preset.model ? { model: preset.model } : {},
@@ -14240,6 +14817,7 @@ class ExtensionPluginService {
14240
14817
  if (this.disposed) return this.disposed;
14241
14818
  this.isDisposed = true;
14242
14819
  this.background = false;
14820
+ for (const id of [...this.devWatchers.keys()]) this.closeDevWatch(id);
14243
14821
  if (this.changeTimer) clearTimeout(this.changeTimer);
14244
14822
  this.changeTimer = null;
14245
14823
  if (this.updateTimer) clearTimeout(this.updateTimer);
@@ -14306,8 +14884,8 @@ class ExtensionPluginService {
14306
14884
  return proc;
14307
14885
  }
14308
14886
  createProcess(manifest, dir, onExit) {
14309
- const dataDir = pluginDataPath(this.options.root, manifest.id);
14310
- mkdirSync(dataDir, { recursive: true });
14887
+ const dataDir2 = pluginDataPath(this.options.root, manifest.id);
14888
+ mkdirSync(dataDir2, { recursive: true });
14311
14889
  let proc;
14312
14890
  proc = new TrackedPluginProcess(
14313
14891
  {
@@ -14315,14 +14893,14 @@ class ExtensionPluginService {
14315
14893
  hostPath: this.options.hostPath,
14316
14894
  env: {
14317
14895
  ...pluginProcessEnv(this.options.env, this.options.sourceEnv, manifest.env),
14318
- ENSO_PLUGIN_DATA: dataDir
14896
+ ENSO_PLUGIN_DATA: dataDir2
14319
14897
  },
14320
14898
  resident: manifest.resident,
14321
14899
  init: {
14322
14900
  pluginId: manifest.id,
14323
14901
  pluginRoot: pluginPackagePath(this.options.root, manifest.id, dir),
14324
14902
  main: manifest.main ?? "",
14325
- dataDir
14903
+ dataDir: dataDir2
14326
14904
  },
14327
14905
  handleHostCall: (api, args, invocationId) => this.gate.handle(manifest.id, api, args, invocationId),
14328
14906
  onExit: ({ unexpected }) => {
@@ -14673,13 +15251,13 @@ class ExtensionPluginService {
14673
15251
  withIdLock(id, run2) {
14674
15252
  const prev = this.idTails.get(id) ?? Promise.resolve();
14675
15253
  const next = prev.then(run2, run2);
14676
- const tail = next.then(
15254
+ const tail2 = next.then(
14677
15255
  () => void 0,
14678
15256
  () => void 0
14679
15257
  );
14680
- this.idTails.set(id, tail);
14681
- void tail.finally(() => {
14682
- if (this.idTails.get(id) === tail) this.idTails.delete(id);
15258
+ this.idTails.set(id, tail2);
15259
+ void tail2.finally(() => {
15260
+ if (this.idTails.get(id) === tail2) this.idTails.delete(id);
14683
15261
  });
14684
15262
  return next;
14685
15263
  }
@@ -14981,13 +15559,16 @@ function getExtensionPlugins() {
14981
15559
  pendingApprovals: 0
14982
15560
  }
14983
15561
  },
14984
- sessionUi: (target, op, payload2) => getDraftBroker().request(
14985
- target.origin,
14986
- target.sessionId,
14987
- op,
14988
- payload2,
14989
- SESSION_UI_TIMEOUT_MS
14990
- ),
15562
+ sessionUi: (target, op, payload2) => {
15563
+ const origin = target.origin ?? (op === "openPluginView" ? remoteLeaderId() ?? null : null);
15564
+ return getDraftBroker().request(
15565
+ origin,
15566
+ target.sessionId,
15567
+ op,
15568
+ payload2,
15569
+ SESSION_UI_TIMEOUT_MS
15570
+ );
15571
+ },
14991
15572
  // 发起窗口一定活着(它刚调用了插件),优先交给它。后台投递没有发起窗口时退到主窗口,
14992
15573
  // 服务器模式下本机主窗口恒为 null,再退到远端主界面
14993
15574
  wakeSession: async (sessionId, origin) => {
@@ -15007,8 +15588,10 @@ function getExtensionPlugins() {
15007
15588
  ...capabilities.openExternal ? { openExternal: (url) => shell.openExternal(url) } : {}
15008
15589
  }
15009
15590
  });
15010
- service$2.startUpdateChecks();
15011
- service$2.startBackground();
15591
+ if (!isHeadlessRun()) {
15592
+ service$2.startUpdateChecks();
15593
+ service$2.startBackground();
15594
+ }
15012
15595
  setNativeAgentTypeSource(service$2.agentTypeSource());
15013
15596
  app.on("before-quit", () => service$2?.dispose());
15014
15597
  return service$2;
@@ -15587,6 +16170,126 @@ function getMcpToolCatalog() {
15587
16170
  );
15588
16171
  return singleton$1;
15589
16172
  }
16173
+ const FETCH_TIMEOUT_MS = 15e3;
16174
+ const MAX_BYTES$1 = 32 * 1024 * 1024;
16175
+ function refreshResult(cache2, ok, fromCache, error) {
16176
+ return {
16177
+ ok,
16178
+ modelCount: cache2?.models.length ?? 0,
16179
+ ...cache2 ? { fetchedAt: cache2.fetchedAt } : {},
16180
+ fromCache,
16181
+ ...error ? { error } : {}
16182
+ };
16183
+ }
16184
+ function failed$1(previous, error) {
16185
+ return { cache: previous, result: refreshResult(previous, false, previous !== void 0, error) };
16186
+ }
16187
+ async function runModelsDevRefresh(input) {
16188
+ const previous = input.previous;
16189
+ if (!input.force && modelsDevIsFresh(previous, input.now, input.ttlMs)) {
16190
+ return { cache: previous, result: refreshResult(previous, true, true) };
16191
+ }
16192
+ let response;
16193
+ try {
16194
+ response = await input.fetchCatalog({ url: MODELS_DEV_URL, etag: previous?.etag });
16195
+ } catch (error) {
16196
+ return failed$1(previous, error instanceof Error ? error.message : String(error));
16197
+ }
16198
+ if (response.status === 304 && previous) {
16199
+ const next2 = {
16200
+ ...previous,
16201
+ fetchedAt: input.now,
16202
+ ...response.etag ? { etag: response.etag } : {}
16203
+ };
16204
+ try {
16205
+ writeModelsDevCache(input.file, next2);
16206
+ } catch (error) {
16207
+ return failed$1(previous, error instanceof Error ? error.message : String(error));
16208
+ }
16209
+ return { cache: next2, result: refreshResult(next2, true, false) };
16210
+ }
16211
+ const maxBytes = input.maxBytes ?? MAX_BYTES$1;
16212
+ if (response.status !== 200 || typeof response.body !== "string" || response.body.length > maxBytes) {
16213
+ return failed$1(previous, `models.dev HTTP ${response.status}`);
16214
+ }
16215
+ let parsed;
16216
+ try {
16217
+ parsed = JSON.parse(response.body);
16218
+ } catch {
16219
+ return failed$1(previous, "models.dev payload is not JSON");
16220
+ }
16221
+ const next = parseModelsDevPayload(parsed, input.now);
16222
+ if (!next) return failed$1(previous, "models.dev payload has no chat models");
16223
+ if (response.etag) next.etag = response.etag;
16224
+ try {
16225
+ writeModelsDevCache(input.file, next);
16226
+ } catch (error) {
16227
+ return failed$1(previous, error instanceof Error ? error.message : String(error));
16228
+ }
16229
+ return { cache: next, result: refreshResult(next, true, false) };
16230
+ }
16231
+ let memory$1;
16232
+ let loaded = false;
16233
+ let tail = Promise.resolve();
16234
+ function cachePath$2() {
16235
+ return join(app.getPath("userData"), MODELS_DEV_CACHE_NAME);
16236
+ }
16237
+ function loadCache() {
16238
+ if (!loaded) {
16239
+ loaded = true;
16240
+ memory$1 = readModelsDevCache(cachePath$2());
16241
+ }
16242
+ return memory$1;
16243
+ }
16244
+ function getModelsDevModels() {
16245
+ return loadCache()?.models ?? [];
16246
+ }
16247
+ async function fetchCatalog(request2) {
16248
+ const { getProxyConfig: getProxyConfig2 } = await Promise.resolve().then(() => proxyConfig);
16249
+ await getProxyConfig2().whenReady();
16250
+ const controller = new AbortController();
16251
+ const timer2 = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
16252
+ try {
16253
+ const headers = { accept: "application/json" };
16254
+ if (request2.etag) headers["if-none-match"] = request2.etag;
16255
+ const response = await net.fetch(request2.url, { headers, signal: controller.signal });
16256
+ const etag = response.headers.get("etag") ?? void 0;
16257
+ if (response.status === 304) return { status: 304, etag };
16258
+ return { status: response.status, etag, body: await response.text() };
16259
+ } finally {
16260
+ clearTimeout(timer2);
16261
+ }
16262
+ }
16263
+ function ensureModelsDevCatalog(options) {
16264
+ const force = options?.force === true;
16265
+ let result = { ok: false, modelCount: 0, fromCache: false };
16266
+ const run2 = tail.then(async () => {
16267
+ const previous = loadCache();
16268
+ const outcome2 = await runModelsDevRefresh({
16269
+ file: cachePath$2(),
16270
+ previous,
16271
+ now: Date.now(),
16272
+ force,
16273
+ fetchCatalog
16274
+ });
16275
+ memory$1 = outcome2.cache;
16276
+ loaded = true;
16277
+ outcome2.result.ok ? 0 : Date.now();
16278
+ result = outcome2.result;
16279
+ if (outcome2.result.ok && !outcome2.result.fromCache) {
16280
+ void Promise.resolve().then(() => modelDirectory).then(({ refreshModelDirectory: refreshModelDirectory2 }) => refreshModelDirectory2()).catch(() => {
16281
+ });
16282
+ }
16283
+ });
16284
+ tail = run2.then(
16285
+ () => void 0,
16286
+ () => void 0
16287
+ );
16288
+ return run2.then(() => result);
16289
+ }
16290
+ async function refreshModelCatalogNow() {
16291
+ return ensureModelsDevCatalog({ force: true });
16292
+ }
15590
16293
  const CACHE_NAME = "model-directory-cache.json";
15591
16294
  const CACHE_DEBOUNCE_MS = 500;
15592
16295
  let snapshot;
@@ -15773,7 +16476,11 @@ async function loadLiveOAuthProviders() {
15773
16476
  for (const provider2 of runtime.getProviders()) {
15774
16477
  if (!provider2.auth?.oauth || provider2.id.includes("#")) continue;
15775
16478
  const oauthName = typeof provider2.auth.oauth === "object" ? provider2.auth.oauth.name : void 0;
15776
- const models = expandOauthCatalog(provider2.id, provider2.getModels()).map((model) => ({
16479
+ const models = withModelsDevOauthModels(
16480
+ provider2.id,
16481
+ expandOauthCatalog(provider2.id, provider2.getModels()),
16482
+ getModelsDevModels()
16483
+ ).map((model) => ({
15777
16484
  id: model.id,
15778
16485
  name: "name" in model && typeof model.name === "string" ? model.name : void 0
15779
16486
  }));
@@ -16003,7 +16710,7 @@ function bundledRtkPath(options) {
16003
16710
  filename
16004
16711
  );
16005
16712
  }
16006
- function pickSubagentModelRefs(entries, providers2) {
16713
+ function pickSubagentModelRefs(entries, providers2, virtualModels) {
16007
16714
  const refs = [];
16008
16715
  const named = /* @__PURE__ */ new Map();
16009
16716
  const seen = /* @__PURE__ */ new Set();
@@ -16014,14 +16721,27 @@ function pickSubagentModelRefs(entries, providers2) {
16014
16721
  if (entry.enabled === false) continue;
16015
16722
  const key = `${entry.providerId}\0${entry.modelId}`;
16016
16723
  if (seen.has(key)) continue;
16017
- const provider2 = providers2.find((candidate) => candidate.id === entry.providerId);
16018
- if (!provider2 || provider2.enabled === false || !hasProviderCredentials(provider2)) continue;
16019
- if (isClassifierOnlyProvider(provider2)) continue;
16020
- if (!Array.isArray(provider2.models)) continue;
16021
- const model = provider2.models.find((candidate) => candidate?.id === entry.modelId);
16022
- if (!model || model.enabled === false) continue;
16724
+ let base;
16725
+ let providerId;
16726
+ let modelId;
16727
+ if (isVirtualRef(entry)) {
16728
+ const virtual = virtualModels.find((item) => item.id === entry.modelId);
16729
+ if (!virtual?.enabled) continue;
16730
+ base = virtual.name;
16731
+ providerId = entry.providerId;
16732
+ modelId = virtual.id;
16733
+ } else {
16734
+ const provider2 = providers2.find((candidate) => candidate.id === entry.providerId);
16735
+ if (!provider2 || provider2.enabled === false || !hasProviderCredentials(provider2)) continue;
16736
+ if (isClassifierOnlyProvider(provider2)) continue;
16737
+ if (!Array.isArray(provider2.models)) continue;
16738
+ const model = provider2.models.find((candidate) => candidate?.id === entry.modelId);
16739
+ if (!model || model.enabled === false) continue;
16740
+ base = `${provider2.name}/${model.id}`;
16741
+ providerId = provider2.id;
16742
+ modelId = model.id;
16743
+ }
16023
16744
  seen.add(key);
16024
- const base = `${provider2.name}/${model.id}`;
16025
16745
  const count = (named.get(base) ?? 0) + 1;
16026
16746
  named.set(base, count);
16027
16747
  const description = typeof entry.description === "string" ? entry.description.trim() : "";
@@ -16031,8 +16751,8 @@ function pickSubagentModelRefs(entries, providers2) {
16031
16751
  ) ? entry.thinkingLevel : void 0;
16032
16752
  refs.push({
16033
16753
  name: count === 1 ? base : `${base}#${count}`,
16034
- providerId: provider2.id,
16035
- modelId: model.id,
16754
+ providerId,
16755
+ modelId,
16036
16756
  ...description ? { description } : {},
16037
16757
  ...reasoning ? { reasoning } : {},
16038
16758
  ...thinkingLevel ? { thinkingLevel } : {}
@@ -16205,12 +16925,15 @@ function customWorkflowPresetDir() {
16205
16925
  }
16206
16926
  function startAgentWorker() {
16207
16927
  if (worker) return;
16928
+ const askpass = ensureElevationServer();
16208
16929
  const child = utilityProcess.fork(agentWorkerPath, [], {
16209
16930
  serviceName: "enso-agent-worker",
16210
16931
  env: {
16211
16932
  ...process.env,
16933
+ ...askpass ? { [ELEVATE_ASKPASS_ENV]: askpass } : {},
16212
16934
  ENSO_AGENT_DATA_DIR: agentDataDir(),
16213
16935
  PI_CODING_AGENT_DIR: path.join(app.getPath("userData"), "agent", "pi-agent"),
16936
+ ENSO_MODELS_DEV_CACHE: path.join(app.getPath("userData"), "models-dev-cache.json"),
16214
16937
  ENSO_RTK_PATH: bundledRtkPath({
16215
16938
  packaged: app.isPackaged,
16216
16939
  resourcesPath,
@@ -16395,6 +17118,8 @@ function setWorkspaceBusyResolver(resolver) {
16395
17118
  workspaceBusy = resolver;
16396
17119
  }
16397
17120
  function sendAgentCommand(command) {
17121
+ if (!parseAgentCommand(command))
17122
+ return { ok: false, error: `invalid ${command.type} command: rejected by worker contract` };
16398
17123
  if (workspaceCommandBlocked(command, workspaceBusy))
16399
17124
  return { ok: false, error: "Workspace operation in progress." };
16400
17125
  const action = agentCommandDispatch({
@@ -16616,7 +17341,8 @@ function resolveAgentTypeSpawnConfig(typeKey, parentModel, authenticatedAccountK
16616
17341
  const resolved = resolveModelSelection(
16617
17342
  definition.providerId,
16618
17343
  definition.modelId,
16619
- authenticatedAccountKeys
17344
+ authenticatedAccountKeys,
17345
+ { allowVirtual: true }
16620
17346
  );
16621
17347
  if (!resolved.ok) return { ok: false, error: resolved.error };
16622
17348
  selectedModel = resolved.selection;
@@ -16714,6 +17440,7 @@ function spawnSession(identity, request2, authenticatedAccountKeys, remote, proj
16714
17440
  ...bot ? [] : plugins.skillPaths,
16715
17441
  ...extensionPlugins?.skillPathsForSpawn(activePluginPreset) ?? []
16716
17442
  ];
17443
+ const workflowPresetFiles = extensionPlugins?.workflowPathsForSpawn(activePluginPreset) ?? [];
16717
17444
  const mcpServers = enabledMcpServers(preset);
16718
17445
  const mcpNames = new Set(mcpServers.map((server2) => server2.name));
16719
17446
  for (const server2 of [
@@ -16806,6 +17533,7 @@ function spawnSession(identity, request2, authenticatedAccountKeys, remote, proj
16806
17533
  ...plugins.commands.length > 0 ? { pluginCommands: plugins.commands } : {},
16807
17534
  ...pluginHooks.length > 0 ? { pluginHooks } : {},
16808
17535
  ...pluginTools.length > 0 ? { pluginTools } : {},
17536
+ ...workflowPresetFiles.length > 0 ? { workflowPresetFiles } : {},
16809
17537
  ...pluginEvents ? { pluginEvents } : {},
16810
17538
  ...presetApplied.approvalMode ? { approvalMode: presetApplied.approvalMode } : {},
16811
17539
  ...request2.autoRejectApprovals === true ? { autoRejectApprovals: true } : {},
@@ -16862,10 +17590,13 @@ function pluginPresetInstruction(own, global) {
16862
17590
  return own ?? global();
16863
17591
  }
16864
17592
  function pluginSkillPathsForMenu(presetId, deps) {
16865
- const { pluginPresetId: pluginPresetId2 } = presetOverlay(presetId, deps.resolve);
16866
- const active = deps.extension?.presetForSpawn(pluginPresetId2)?.ok ? pluginPresetId2 : void 0;
17593
+ const active = activePluginPresetForMenu(presetId, deps.resolve, deps.extension);
16867
17594
  return [...deps.claude, ...deps.extension?.skillPathsForSpawn(active) ?? []];
16868
17595
  }
17596
+ function activePluginPresetForMenu(presetId, resolve2, extension2) {
17597
+ const { pluginPresetId: pluginPresetId2 } = presetOverlay(presetId, resolve2);
17598
+ return extension2?.presetForSpawn(pluginPresetId2)?.ok ? pluginPresetId2 : void 0;
17599
+ }
16869
17600
  function menuPluginSkillPaths(presetId) {
16870
17601
  return pluginSkillPathsForMenu(presetId, {
16871
17602
  resolve: resolvePreset,
@@ -16873,15 +17604,21 @@ function menuPluginSkillPaths(presetId) {
16873
17604
  extension: getExtensionPlugins()
16874
17605
  });
16875
17606
  }
17607
+ function menuPluginWorkflowPaths(presetId) {
17608
+ const extension2 = getExtensionPlugins();
17609
+ return extension2.workflowPathsForSpawn(
17610
+ activePluginPresetForMenu(presetId, resolvePreset, extension2)
17611
+ );
17612
+ }
16876
17613
  function mergePresetPromptKit(own, plugin) {
16877
17614
  const pick = (key) => {
16878
17615
  const value = plugin?.[key] || own[key];
16879
17616
  return value ? { [key]: value } : {};
16880
17617
  };
16881
- const tail = [own.systemPromptAppend, plugin?.systemPromptAppend].filter(Boolean).join("\n\n");
17618
+ const tail2 = [own.systemPromptAppend, plugin?.systemPromptAppend].filter(Boolean).join("\n\n");
16882
17619
  return {
16883
17620
  ...pick("systemPrompt"),
16884
- ...tail ? { systemPromptAppend: tail } : {},
17621
+ ...tail2 ? { systemPromptAppend: tail2 } : {},
16885
17622
  ...pick("systemPromptBoost"),
16886
17623
  ...pick("refusalRetryPrompt")
16887
17624
  };
@@ -16935,14 +17672,14 @@ function readPresetPrompt(id) {
16935
17672
  function resolvePresetPromptKit(preset) {
16936
17673
  if (!preset) return { ok: true };
16937
17674
  const role = readPresetPrompt(preset.systemPromptId);
16938
- const tail = readPresetPrompt(preset.systemPromptTailId);
17675
+ const tail2 = readPresetPrompt(preset.systemPromptTailId);
16939
17676
  const boost = readPresetPrompt(preset.boostPromptId);
16940
17677
  const retry = readPresetPrompt(preset.refusalRetryPromptId);
16941
- if (!role.ok || !tail.ok || !boost.ok || !retry.ok) return { ok: false };
17678
+ if (!role.ok || !tail2.ok || !boost.ok || !retry.ok) return { ok: false };
16942
17679
  return {
16943
17680
  ok: true,
16944
17681
  ...role.content ? { systemPrompt: role.content } : {},
16945
- ...tail.content ? { systemPromptAppend: tail.content } : {},
17682
+ ...tail2.content ? { systemPromptAppend: tail2.content } : {},
16946
17683
  ...boost.content ? { systemPromptBoost: boost.content } : {},
16947
17684
  ...preset.refusalRetry === true && retry.content ? { refusalRetryPrompt: retry.content } : {}
16948
17685
  };
@@ -17265,6 +18002,9 @@ function releaseParentSession(identity) {
17265
18002
  function abortRetrySession(identity) {
17266
18003
  return sendAgentCommand({ type: "abort-retry", identity });
17267
18004
  }
18005
+ function withdrawSteerSession(identity, deliveryId) {
18006
+ return sendAgentCommand({ type: "withdraw-steer", identity, deliveryId });
18007
+ }
17268
18008
  function retrySession(identity, unfinishedOnly = false) {
17269
18009
  return sendAgentCommand({
17270
18010
  type: "retry",
@@ -17368,7 +18108,9 @@ function configuredAgentTypes(authenticatedAccountKeys, hasSubagentModels = fals
17368
18108
  const resources = resolveAgentTypeResources(entry);
17369
18109
  const mode2 = entry.modelMode ?? (entry.providerId && entry.modelId ? "fixed" : "follow");
17370
18110
  const effectiveMode = mode2 === "agent_pick" && !hasSubagentModels ? "follow" : mode2;
17371
- const bound = effectiveMode === "fixed" && entry.providerId && entry.modelId ? resolveModelSelection(entry.providerId, entry.modelId, authenticatedAccountKeys) : null;
18111
+ const bound = effectiveMode === "fixed" && entry.providerId && entry.modelId ? resolveModelSelection(entry.providerId, entry.modelId, authenticatedAccountKeys, {
18112
+ allowVirtual: true
18113
+ }) : null;
17372
18114
  return {
17373
18115
  name: entry.name,
17374
18116
  description: entry.description,
@@ -17387,7 +18129,9 @@ function configuredAgentTypes(authenticatedAccountKeys, hasSubagentModels = fals
17387
18129
  const members = visibleMemberAgentTypes(memberAgentTypes(), custom).map(
17388
18130
  (entry) => {
17389
18131
  const resources = resolveAgentTypeResources(entry);
17390
- const bound = entry.providerId && entry.modelId ? resolveModelSelection(entry.providerId, entry.modelId, authenticatedAccountKeys) : null;
18132
+ const bound = entry.providerId && entry.modelId ? resolveModelSelection(entry.providerId, entry.modelId, authenticatedAccountKeys, {
18133
+ allowVirtual: true
18134
+ }) : null;
17391
18135
  return {
17392
18136
  name: entry.typeKey,
17393
18137
  description: memberSpawnDescription(entry),
@@ -17407,47 +18151,58 @@ function configuredAgentTypes(authenticatedAccountKeys, hasSubagentModels = fals
17407
18151
  );
17408
18152
  return [...builtins, ...customs, ...members];
17409
18153
  }
17410
- function configuredSubagentModels(authenticatedAccountKeys) {
18154
+ function resolveConfiguredSubagentSelection(ref, authenticatedAccountKeys) {
18155
+ const resolved = resolveModelSelection(
18156
+ ref.providerId,
18157
+ ref.modelId,
18158
+ authenticatedAccountKeys,
18159
+ isVirtualRef(ref) ? { allowVirtual: true } : void 0
18160
+ );
18161
+ if (!resolved.ok) return void 0;
18162
+ return {
18163
+ ...resolved.selection,
18164
+ config: {
18165
+ ...resolved.selection.config,
18166
+ ...ref.reasoning ? { reasoning: ref.reasoning } : {},
18167
+ ...ref.thinkingLevel ? { thinkingLevel: ref.thinkingLevel } : {}
18168
+ }
18169
+ };
18170
+ }
18171
+ function listConfiguredSubagentSelections(authenticatedAccountKeys) {
17411
18172
  const state = readSettingsState();
17412
18173
  if (state?.subagentModelsEnabled !== true) return [];
17413
18174
  const entries = Array.isArray(state.subagentModels) ? state.subagentModels.filter(isSubagentModelEntry) : [];
17414
- const options = [];
17415
- for (const ref of pickSubagentModelRefs(entries, providersFromSettings())) {
17416
- const resolved = resolveModelSelection(ref.providerId, ref.modelId, authenticatedAccountKeys);
17417
- if (resolved.ok) {
17418
- options.push({
17419
- name: ref.name,
17420
- // 条目级推理覆盖赢过模型行覆盖;缺省保留行级/跟随语义
17421
- config: {
17422
- ...resolved.selection.config,
17423
- ...ref.reasoning ? { reasoning: ref.reasoning } : {},
17424
- ...ref.thinkingLevel ? { thinkingLevel: ref.thinkingLevel } : {}
17425
- },
17426
- ...ref.description ? { description: ref.description } : {}
17427
- });
17428
- }
18175
+ const selections = [];
18176
+ for (const ref of pickSubagentModelRefs(
18177
+ entries,
18178
+ providersFromSettings(),
18179
+ virtualModelsFromSettings()
18180
+ )) {
18181
+ const selection = resolveConfiguredSubagentSelection(ref, authenticatedAccountKeys);
18182
+ if (!selection) continue;
18183
+ selections.push({
18184
+ name: ref.name,
18185
+ ...ref.description ? { description: ref.description } : {},
18186
+ selection
18187
+ });
17429
18188
  }
17430
- return options;
18189
+ return selections;
18190
+ }
18191
+ function configuredSubagentModels(authenticatedAccountKeys) {
18192
+ return listConfiguredSubagentSelections(authenticatedAccountKeys).map(
18193
+ ({ name, description, selection }) => ({
18194
+ name,
18195
+ config: selection.config,
18196
+ ...description ? { description } : {}
18197
+ })
18198
+ );
17431
18199
  }
17432
18200
  function resolveSubagentModelSelection(name, authenticatedAccountKeys) {
17433
- const selected2 = configuredSubagentModels(authenticatedAccountKeys).find(
18201
+ const selected2 = listConfiguredSubagentSelections(authenticatedAccountKeys).find(
17434
18202
  (entry) => entry.name === name
17435
18203
  );
17436
18204
  if (!selected2) return { ok: false, error: `Subagent model is unavailable: ${name}` };
17437
- return {
17438
- ok: true,
17439
- selection: {
17440
- ref: {
17441
- providerId: selected2.config.settingsProviderId,
17442
- modelId: selected2.config.modelId
17443
- },
17444
- runtimeRef: {
17445
- providerId: selected2.config.oauthAccountKey ?? selected2.config.settingsProviderId,
17446
- modelId: selected2.config.modelId
17447
- },
17448
- config: selected2.config
17449
- }
17450
- };
18205
+ return { ok: true, selection: selected2.selection };
17451
18206
  }
17452
18207
  function isSubagentModelEntry(value) {
17453
18208
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
@@ -17689,13 +18444,15 @@ function customProvidersForWorker() {
17689
18444
  continue;
17690
18445
  }
17691
18446
  if (!Array.isArray(provider2.models)) continue;
18447
+ const headers = parseProviderHeaders(provider2.headers);
17692
18448
  out.push({
17693
18449
  settingsId: provider2.id,
17694
18450
  name: provider2.name,
17695
18451
  api: provider2.api,
17696
18452
  baseUrl: provider2.baseUrl,
17697
18453
  apiKey: provider2.apiKey,
17698
- models: provider2.models
18454
+ models: provider2.models,
18455
+ ...headers ? { headers } : {}
17699
18456
  });
17700
18457
  }
17701
18458
  return out;
@@ -17733,12 +18490,14 @@ function spawnModelConfig(provider2, modelId) {
17733
18490
  if (provider2.oauthAccountPool !== void 0 && !isOauthAccountPool(provider2))
17734
18491
  throw new Error("Invalid ChatGPT OAuth pool configuration.");
17735
18492
  const entry = provider2.models.find((model) => model.id === modelId);
18493
+ const headers = parseProviderHeaders(provider2.headers);
17736
18494
  return {
17737
18495
  api: provider2.api,
17738
18496
  baseUrl: provider2.baseUrl,
17739
18497
  apiKey: provider2.apiKey,
17740
18498
  modelId,
17741
18499
  settingsProviderId: provider2.id,
18500
+ ...headers ? { headers } : {},
17742
18501
  ...provider2.oauthAccountKey ? { oauthAccountKey: provider2.oauthAccountKey } : {},
17743
18502
  ...isOauthAccountPool(provider2) ? { oauthAccountPool: provider2.oauthAccountPool } : {},
17744
18503
  // 统一目录后 OAuth 条目 models 只承载稀疏用户覆盖(enabled/别名/能力/档位),
@@ -17802,6 +18561,7 @@ const agentHost = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePro
17802
18561
  isAgentWorkerReady,
17803
18562
  isAgentWorkerRunning,
17804
18563
  menuPluginSkillPaths,
18564
+ menuPluginWorkflowPaths,
17805
18565
  mergePresetPromptKit,
17806
18566
  modelRefForSpawnConfig,
17807
18567
  pluginPresetInstruction,
@@ -17870,7 +18630,8 @@ const agentHost = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePro
17870
18630
  stopWorkflow,
17871
18631
  summarizeConversationTitle,
17872
18632
  thawWorkspace,
17873
- toSessionMcpConfig
18633
+ toSessionMcpConfig,
18634
+ withdrawSteerSession
17874
18635
  }, Symbol.toStringTag, { value: "Module" }));
17875
18636
  async function validateAgentRun(input) {
17876
18637
  let value;
@@ -17931,7 +18692,7 @@ function projectedActivity(message2) {
17931
18692
  }
17932
18693
  return { phase: last?.type === "text" ? "writing" : "thinking" };
17933
18694
  }
17934
- const NOTIFY_TEXT_LIMIT = 1500;
18695
+ const NOTIFY_TEXT_LIMIT = 4e3;
17935
18696
  function toolCallIdsOf(message2) {
17936
18697
  const value = message2;
17937
18698
  if (value?.role !== "assistant" || !Array.isArray(value.content)) return [];
@@ -18541,7 +19302,8 @@ ${failure2}` : failure2;
18541
19302
  const title = this.agents.get(run2.agentId)?.title ?? run2.agentId;
18542
19303
  const durationMs = (run2.finishedAt ?? this.now()) - (run2.startedAt ?? run2.createdAt);
18543
19304
  const body = run2.status === "succeeded" ? run2.text?.trim() : run2.error;
18544
- const excerpt = body && body.length > NOTIFY_TEXT_LIMIT ? `${body.slice(0, NOTIFY_TEXT_LIMIT)}
19305
+ const truncated = !!body && body.length > NOTIFY_TEXT_LIMIT;
19306
+ const excerpt = truncated ? `${body.slice(0, NOTIFY_TEXT_LIMIT)}
18545
19307
  […the subagent's report was cut from ${body.length} to its first ${NOTIFY_TEXT_LIMIT} characters]` : body;
18546
19308
  let tokens = 0;
18547
19309
  for (const usage of run2.usageByMessage.values()) {
@@ -18557,8 +19319,12 @@ ${failure2}` : failure2;
18557
19319
  `<usage>subagent_tokens: ${tokens}
18558
19320
  tool_uses: ${run2.toolCallIds.size}
18559
19321
  duration_ms: ${durationMs}</usage>`,
18560
- `Use subagent report with runId ${run2.runId} for the full result.${run2.mode === "coworker" ? ` To continue this coworker, use subagent send with agentId ${run2.agentId}.` : ""}`
18561
- ].join("\n");
19322
+ // 全文已在通知里时不引导 report,否则模型会把整份报告再拉一遍
19323
+ [
19324
+ truncated ? `Use subagent report with runId ${run2.runId} for the full result.` : "",
19325
+ run2.mode === "coworker" ? `To continue this coworker, use subagent send with agentId ${run2.agentId}.` : ""
19326
+ ].filter(Boolean).join(" ")
19327
+ ].filter(Boolean).join("\n");
18562
19328
  }
18563
19329
  snapshot(run2) {
18564
19330
  return {
@@ -18631,13 +19397,13 @@ duration_ms: ${durationMs}</usage>`,
18631
19397
  serial(key, operation) {
18632
19398
  const previous = this.queues.get(key) ?? Promise.resolve();
18633
19399
  const result = previous.then(operation, operation);
18634
- const tail = result.then(
19400
+ const tail2 = result.then(
18635
19401
  () => void 0,
18636
19402
  () => void 0
18637
19403
  );
18638
- this.queues.set(key, tail);
18639
- void tail.finally(() => {
18640
- if (this.queues.get(key) === tail) this.queues.delete(key);
19404
+ this.queues.set(key, tail2);
19405
+ void tail2.finally(() => {
19406
+ if (this.queues.get(key) === tail2) this.queues.delete(key);
18641
19407
  });
18642
19408
  return result;
18643
19409
  }
@@ -19472,7 +20238,7 @@ async function loadLlama() {
19472
20238
  llamaPromise ??= (async () => {
19473
20239
  let backendError;
19474
20240
  try {
19475
- const { ensureGpuBackend } = await import("./chunks/gpuBackendInstall-CdExgjGi.js");
20241
+ const { ensureGpuBackend } = await import("./chunks/gpuBackendInstall-P7COXJlD.js");
19476
20242
  await ensureGpuBackend().catch((err) => {
19477
20243
  backendError = err;
19478
20244
  console.warn("[llama] GPU backend unavailable, using CPU:", err);
@@ -19993,8 +20759,8 @@ async function reloadConversation(conversationId, deps) {
19993
20759
  const history = await deps.readHistory(conversationId);
19994
20760
  return history.ok ? { ok: true, source: "history", projection: history.projection } : { ok: false, error: history.error };
19995
20761
  }
19996
- const tail = await deps.readParentTail(conversationId);
19997
- return tail.ok ? { ok: true, source: "tail", messages: tail.messages, baseIndex: tail.baseIndex } : { ok: false, error: tail.error };
20762
+ const tail2 = await deps.readParentTail(conversationId);
20763
+ return tail2.ok ? { ok: true, source: "tail", messages: tail2.messages, baseIndex: tail2.baseIndex } : { ok: false, error: tail2.error };
19998
20764
  } catch (error) {
19999
20765
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
20000
20766
  }
@@ -24129,7 +24895,7 @@ async function readSessionTranscript(sessionFile) {
24129
24895
  const resolved = path.resolve(sessionFile);
24130
24896
  if (!resolved.startsWith(`${root}${path.sep}`)) return [];
24131
24897
  const [{ SessionManager: SessionManager2, sessionEntryToContextMessages: sessionEntryToContextMessages2 }, { projectMessage: projectMessage2 }] = await Promise.all(
24132
- [import("@earendil-works/pi-coding-agent"), import("./chunks/workflowPresets-DqSsjOj6.js").then((n) => n.d1)]
24898
+ [import("@earendil-works/pi-coding-agent"), import("./chunks/workflowPresets-CuLnfQqa.js").then((n) => n.dq)]
24133
24899
  );
24134
24900
  const branch = SessionManager2.open(resolved, sessionDir2).getBranch();
24135
24901
  const out = [];
@@ -25230,6 +25996,9 @@ const isGen = (v) => Number.isInteger(v) && v >= 0;
25230
25996
  const isSignal = (v) => typeof v === "string" && v.length > 0 && v.length <= DIRECT_SIGNAL_MAX_CHARS;
25231
25997
  const isSafeIndex = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= -1;
25232
25998
  const isChatId = (v) => isStr(v) && v.length <= 128;
25999
+ const isRequestId = (v) => isStr(v) && v.length <= 100;
26000
+ const isHostPath = (v) => isStr(v) && v.length <= 4096;
26001
+ const isAbsoluteHostPath = (v) => isHostPath(v) && (v.startsWith("/") || /^[A-Za-z]:[\\/]/.test(v) || v.startsWith("\\\\"));
25233
26002
  const BOT_TEXT_MAX_CHARS = 1e5;
25234
26003
  function botCommandError(type, bot) {
25235
26004
  return bot && [
@@ -25554,6 +26323,26 @@ function parsePhoneCommand(value) {
25554
26323
  return { ok: false, error: "invalid requestId" };
25555
26324
  }
25556
26325
  return { ok: true, command: value };
26326
+ case "host-dirs": {
26327
+ if (!isRequestId(v.requestId)) return { ok: false, error: "invalid requestId" };
26328
+ if (v.path !== void 0 && !isHostPath(v.path)) return { ok: false, error: "invalid path" };
26329
+ if (v.create !== void 0 && (!isStr(v.create) || v.create.length > 255 || !v.path)) {
26330
+ return { ok: false, error: "invalid create" };
26331
+ }
26332
+ return {
26333
+ ok: true,
26334
+ command: {
26335
+ type: "host-dirs",
26336
+ requestId: v.requestId,
26337
+ ...v.path !== void 0 ? { path: v.path } : {},
26338
+ ...v.create !== void 0 ? { create: v.create } : {}
26339
+ }
26340
+ };
26341
+ }
26342
+ case "project-add":
26343
+ if (!isRequestId(v.requestId)) return { ok: false, error: "invalid requestId" };
26344
+ if (!isAbsoluteHostPath(v.path)) return { ok: false, error: "invalid path" };
26345
+ return { ok: true, command: { type: "project-add", requestId: v.requestId, path: v.path } };
25557
26346
  default:
25558
26347
  return { ok: false, error: `command not allowed: ${String(v.type)}` };
25559
26348
  }
@@ -25609,8 +26398,8 @@ function narrowSnapshot(event, subscribedId) {
25609
26398
  const { commands: _commands, ...rest } = s;
25610
26399
  const base = { ...rest, sessionId: subscribedId };
25611
26400
  if (!Array.isArray(s.messages)) return { ...base, messages: [], baseIndex: 0 };
25612
- const tail = takeSnapshotTail(s.messages, s.messages.length);
25613
- return fitSnapshotMessages({ ...base, messages: tail.messages, baseIndex: tail.baseIndex });
26401
+ const tail2 = takeSnapshotTail(s.messages, s.messages.length);
26402
+ return fitSnapshotMessages({ ...base, messages: tail2.messages, baseIndex: tail2.baseIndex });
25614
26403
  });
25615
26404
  return sessions2.length > 0 ? { type: "snapshot", sessions: sessions2 } : null;
25616
26405
  }
@@ -25633,6 +26422,69 @@ function shouldForward(event, subscribedId, sinceIndex) {
25633
26422
  if (typeof sessionId === "string") return sessionId === subscribedId;
25634
26423
  return true;
25635
26424
  }
26425
+ async function isDir$1(target) {
26426
+ return stat(target).then(
26427
+ (info) => info.isDirectory(),
26428
+ () => false
26429
+ );
26430
+ }
26431
+ async function listHostDirs(target, home2 = homedir()) {
26432
+ const input = target?.trim() || "~";
26433
+ const expanded = input === "~" ? home2 : input.startsWith("~/") ? path.join(home2, input.slice(2)) : input;
26434
+ let dir = path.resolve(home2, expanded);
26435
+ while (!await isDir$1(dir)) {
26436
+ const up = path.dirname(dir);
26437
+ if (up === dir) return { ok: false, error: "Directory not found." };
26438
+ dir = up;
26439
+ }
26440
+ try {
26441
+ const entries = await readdir(dir, { withFileTypes: true });
26442
+ const dirs = [];
26443
+ for (const entry of entries) {
26444
+ if (entry.name.startsWith(".")) continue;
26445
+ if (entry.isDirectory() || entry.isSymbolicLink() && await isDir$1(path.join(dir, entry.name)))
26446
+ dirs.push(entry.name);
26447
+ }
26448
+ dirs.sort((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
26449
+ const parent = path.dirname(dir);
26450
+ return { ok: true, path: dir, parent: parent === dir ? null : parent, dirs };
26451
+ } catch (error) {
26452
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
26453
+ }
26454
+ }
26455
+ async function createHostDir(parent, rawName) {
26456
+ if (!path.isAbsolute(parent)) return { ok: false, error: "Invalid request." };
26457
+ const name = rawName.trim();
26458
+ if (!name || name === "." || name === ".." || /[/\\\0]/.test(name) || Buffer.byteLength(name) > 255)
26459
+ return { ok: false, error: "Invalid folder name." };
26460
+ const target = path.join(parent, name);
26461
+ try {
26462
+ await mkdir(target);
26463
+ } catch (error) {
26464
+ if (error.code === "EEXIST")
26465
+ return { ok: false, error: "A file or folder with that name already exists." };
26466
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
26467
+ }
26468
+ return listHostDirs(target);
26469
+ }
26470
+ async function pairProjectReply(command, deps) {
26471
+ const { requestId } = command;
26472
+ if (command.type === "host-dirs") {
26473
+ const listing2 = command.create !== void 0 && command.path ? await createHostDir(command.path, command.create) : await listHostDirs(command.path);
26474
+ return listing2.ok ? {
26475
+ type: "host-dirs-result",
26476
+ requestId,
26477
+ path: listing2.path,
26478
+ parent: listing2.parent,
26479
+ dirs: listing2.dirs
26480
+ } : { type: "host-dirs-result", requestId, error: listing2.error };
26481
+ }
26482
+ const result = deps.createProject?.({ requestId: randomUUID(), path: command.path }) ?? {
26483
+ accepted: false,
26484
+ error: "Project registry is not ready."
26485
+ };
26486
+ return result.accepted ? { type: "project-add-result", requestId, projectId: result.value.projectId } : { type: "project-add-result", requestId, error: result.error || "Failed to add project." };
26487
+ }
25636
26488
  function storePath$2() {
25637
26489
  return path.join(app.getPath("userData"), "phone-pairing.bin");
25638
26490
  }
@@ -27582,7 +28434,7 @@ function unloadEngine() {
27582
28434
  const current2 = engine;
27583
28435
  engine = null;
27584
28436
  void current2?.promise.then(
27585
- (loaded) => loaded.dispose(),
28437
+ (loaded2) => loaded2.dispose(),
27586
28438
  () => {
27587
28439
  }
27588
28440
  );
@@ -27692,7 +28544,7 @@ function openSpeechSession(onPartial) {
27692
28544
  if (!enabled) return rejectedSession("disabled");
27693
28545
  if (!modelReady(selected)) return rejectedSession("not-ready");
27694
28546
  const spec = SPEECH_MODELS[selected];
27695
- const loaded = loadEngine();
28547
+ const loaded2 = loadEngine();
27696
28548
  activeSessions++;
27697
28549
  scheduleIdleUnload();
27698
28550
  let phase = "open";
@@ -27700,14 +28552,14 @@ function openSpeechSession(onPartial) {
27700
28552
  let overflow = false;
27701
28553
  let failed2 = false;
27702
28554
  let lastPartial = "";
27703
- const stream2 = spec.streaming ? loaded.then((ready) => ready.openStream()) : null;
28555
+ const stream2 = spec.streaming ? loaded2.then((ready) => ready.openStream()) : null;
27704
28556
  stream2?.catch(() => {
27705
28557
  failed2 = true;
27706
28558
  });
27707
28559
  const segmenter = spec.streaming ? null : createPauseSegmenter();
27708
28560
  const sentences = [];
27709
28561
  let chain = Promise.resolve();
27710
- const recognize = async (samples) => normalizeTranscript(await (await loaded).transcribe(samples));
28562
+ const recognize = async (samples) => normalizeTranscript(await (await loaded2).transcribe(samples));
27711
28563
  const close = () => {
27712
28564
  if (phase === "closed") return;
27713
28565
  phase = "closed";
@@ -27761,10 +28613,10 @@ function openSpeechSession(onPartial) {
27761
28613
  if (failed2) throw new Error("streaming decode failed");
27762
28614
  text2 = await (await stream2).finish();
27763
28615
  } else {
27764
- const tail = segmenter.flush();
28616
+ const tail2 = segmenter.flush();
27765
28617
  await chain;
27766
28618
  if (failed2) throw new Error("sentence decode failed");
27767
- if (tail.speech || sentences.length === 0) sentences.push(await recognize(tail.samples));
28619
+ if (tail2.speech || sentences.length === 0) sentences.push(await recognize(tail2.samples));
27768
28620
  text2 = joinSegments(sentences);
27769
28621
  }
27770
28622
  text2 = normalizeTranscript(text2);
@@ -27856,6 +28708,10 @@ let botPort = null;
27856
28708
  function setPairBotPort(port) {
27857
28709
  botPort = port;
27858
28710
  }
28711
+ let projectDeps = {};
28712
+ function setPairProjectDeps(deps) {
28713
+ projectDeps = deps;
28714
+ }
27859
28715
  function broadcastPairFrame(message2) {
27860
28716
  for (const conn of connections$1.values()) {
27861
28717
  if (conn.phoneOnline) void send$1(conn, message2);
@@ -28532,6 +29388,12 @@ async function handleFrame$1(conn, frame, generation, ioEpoch) {
28532
29388
  case "voice-cancel":
28533
29389
  conn.voiceUploads.cancel(command.requestId);
28534
29390
  break;
29391
+ case "host-dirs":
29392
+ case "project-add":
29393
+ void pairProjectReply(command, projectDeps).then((reply) => {
29394
+ if (connectionCurrent(conn, generation, ioEpoch)) void send$1(conn, reply);
29395
+ }).catch((error) => console.warn("[pair] project command failed", error));
29396
+ break;
28535
29397
  case "rpc-hello":
28536
29398
  case "rpc-bye":
28537
29399
  case "rpc-invoke":
@@ -29051,16 +29913,20 @@ function flushQueue(runtime) {
29051
29913
  deliver: { kind: "prompt", text: taken.item.text, images: taken.item.images }
29052
29914
  };
29053
29915
  }
29054
- function continueGoal(runtime) {
29916
+ function continueGoal(runtime, autoTurnLimit = GOAL_AUTO_TURN_LIMIT) {
29055
29917
  const goal = runtime.goal;
29056
29918
  if (!canFlush(runtime) || goal?.status !== "active" || runtime.queued.length > 0) {
29057
29919
  return { runtime };
29058
29920
  }
29059
- if (goal.autoTurns >= GOAL_AUTO_TURN_LIMIT) {
29921
+ if (goal.autoTurns >= autoTurnLimit) {
29060
29922
  return {
29061
29923
  runtime: {
29062
29924
  ...runtime,
29063
- goal: { ...goal, status: "paused", note: "automatic-turn limit (25) reached" }
29925
+ goal: {
29926
+ ...goal,
29927
+ status: "paused",
29928
+ note: `automatic-turn limit (${autoTurnLimit}) reached`
29929
+ }
29064
29930
  }
29065
29931
  };
29066
29932
  }
@@ -29073,7 +29939,12 @@ function continueGoal(runtime) {
29073
29939
  deliver: { kind: "prompt", text: goalContinueText(goal.text) }
29074
29940
  };
29075
29941
  }
29076
- function onHeadlessIdle(runtime) {
29942
+ function applyHeadlessGoalSignal(runtime, kind, note) {
29943
+ if (!runtime.goal) return runtime;
29944
+ const status2 = kind === "complete" ? "completed" : kind === "blocked" ? "blocked" : "waiting";
29945
+ return { ...runtime, goal: { ...runtime.goal, status: status2, note } };
29946
+ }
29947
+ function onHeadlessIdle(runtime, options) {
29077
29948
  const next = {
29078
29949
  ...runtime,
29079
29950
  status: "idle",
@@ -29083,7 +29954,7 @@ function onHeadlessIdle(runtime) {
29083
29954
  if (runtime.abortRequested) return { runtime: next };
29084
29955
  const queued = flushQueue(next);
29085
29956
  if (queued.deliver) return queued;
29086
- return continueGoal(queued.runtime);
29957
+ return continueGoal(queued.runtime, options?.autoTurnLimit);
29087
29958
  }
29088
29959
  function applyHeadlessQueueAction(runtime, action, newId) {
29089
29960
  switch (action.type) {
@@ -29603,28 +30474,59 @@ function handlePairHeadlessAgentEvent(event) {
29603
30474
  setRuntime(sessionId, { ...runtime, pendingAsks: runtime.pendingAsks + 1 });
29604
30475
  return;
29605
30476
  }
30477
+ if (event.type === "goal-signal") {
30478
+ const next = applyHeadlessGoalSignal(runtime, event.kind, event.note);
30479
+ setRuntime(sessionId, next);
30480
+ persistRuntime(sessionId, next);
30481
+ pushCatalog(sessionId, next);
30482
+ return;
30483
+ }
29606
30484
  if (event.type === "status") {
29607
30485
  const status2 = event.status;
29608
- if (status2 === "running") {
30486
+ if (status2 === "running" || status2 === "idle" || status2 === "failed") {
29609
30487
  const next = { ...runtime, started: true, status: status2 };
29610
30488
  setRuntime(sessionId, next);
29611
30489
  pushCatalog(sessionId, next);
29612
- return;
29613
- }
29614
- if (status2 === "idle" || status2 === "failed") {
29615
- finishTurn(sessionId, { ...runtime, started: true, status: status2 });
29616
30490
  }
29617
30491
  return;
29618
30492
  }
29619
- if (event.type === "turn-completed" || event.type === "turn-failed") {
29620
- finishTurn(sessionId, { ...runtime, started: true, pendingApprovals: 0, pendingAsks: 0 });
30493
+ if (event.type === "turn-failed") {
30494
+ const failed2 = {
30495
+ ...runtime,
30496
+ started: true,
30497
+ status: "failed",
30498
+ pendingApprovals: 0,
30499
+ pendingAsks: 0,
30500
+ ...runtime.goal?.status === "active" ? { goal: { ...runtime.goal, status: "paused", note: event.error } } : {}
30501
+ };
30502
+ const idle = onHeadlessIdle(failed2);
30503
+ finishTurn(sessionId, idle.deliver ? idle : { runtime: { ...idle.runtime, status: "failed" } });
30504
+ return;
30505
+ }
30506
+ if (event.type === "turn-completed") {
30507
+ if (event.aborted || runtime.abortRequested) {
30508
+ finishTurn(sessionId, {
30509
+ runtime: {
30510
+ ...runtime,
30511
+ started: true,
30512
+ status: "idle",
30513
+ abortRequested: false,
30514
+ pendingApprovals: 0,
30515
+ pendingAsks: 0
30516
+ }
30517
+ });
30518
+ return;
30519
+ }
30520
+ finishTurn(
30521
+ sessionId,
30522
+ onHeadlessIdle({ ...runtime, started: true, pendingApprovals: 0, pendingAsks: 0 })
30523
+ );
29621
30524
  }
29622
30525
  }
29623
- function finishTurn(sessionId, runtime) {
30526
+ function finishTurn(sessionId, settled2) {
29624
30527
  const interruptId = pendingInterrupt.get(sessionId);
29625
- const idle = onHeadlessIdle(runtime);
29626
- let next = idle.runtime;
29627
- let delivery = idle.deliver;
30528
+ let next = settled2.runtime;
30529
+ let delivery = settled2.deliver;
29628
30530
  if (interruptId) {
29629
30531
  pendingInterrupt.delete(sessionId);
29630
30532
  const sent = applyHeadlessQueueAction(
@@ -30048,9 +30950,9 @@ function readFirstLine(filePath, maxBytes = 1024 * 1024) {
30048
30950
  }
30049
30951
  }
30050
30952
  function cwdOfSession$1(filePath) {
30051
- const firstLine = readFirstLine(filePath);
30052
- if (firstLine === null) return null;
30053
- const entry = parseLine$6(firstLine);
30953
+ const firstLine2 = readFirstLine(filePath);
30954
+ if (firstLine2 === null) return null;
30955
+ const entry = parseLine$6(firstLine2);
30054
30956
  const payload2 = entry?.payload;
30055
30957
  return typeof payload2?.cwd === "string" ? payload2.cwd : null;
30056
30958
  }
@@ -30329,7 +31231,7 @@ function projectSlug(home2, projectPath) {
30329
31231
  return null;
30330
31232
  }
30331
31233
  }
30332
- function listSessionFiles(home2, identifier) {
31234
+ function listSessionFiles$1(home2, identifier) {
30333
31235
  const dir = path.join(home2, ".gemini", "tmp", identifier, "chats");
30334
31236
  try {
30335
31237
  return fs.readdirSync(dir).filter(
@@ -30354,7 +31256,7 @@ function listGeminiSessions(projectPath, home2 = process.env.HOME ?? "") {
30354
31256
  const seen = /* @__PURE__ */ new Set();
30355
31257
  const sessions2 = [];
30356
31258
  for (const id of ids2) {
30357
- for (const filePath of listSessionFiles(home2, id)) {
31259
+ for (const filePath of listSessionFiles$1(home2, id)) {
30358
31260
  if (seen.has(filePath) || isSubagent(filePath)) continue;
30359
31261
  seen.add(filePath);
30360
31262
  const { title, messages } = readGeminiSession(filePath);
@@ -30456,7 +31358,7 @@ function listGrokSessions(projectPath, home2 = process.env.HOME ?? "") {
30456
31358
  }
30457
31359
  return sessions2.sort((a, b) => b.updatedAt - a.updatedAt);
30458
31360
  }
30459
- const readJson$3 = (filePath) => {
31361
+ const readJson$4 = (filePath) => {
30460
31362
  try {
30461
31363
  const value = JSON.parse(fs.readFileSync(filePath, "utf-8"));
30462
31364
  return value && typeof value === "object" ? value : null;
@@ -30475,10 +31377,10 @@ const storageRootOf = (sessionFile) => path.dirname(path.dirname(path.dirname(se
30475
31377
  const sessionIdOf = (sessionFile) => path.basename(sessionFile, ".json");
30476
31378
  function textPartsOf(storageRoot, messageId) {
30477
31379
  const dir = path.join(storageRoot, "part", messageId);
30478
- return listDir(dir).filter((name) => name.endsWith(".json")).sort().map((name) => readJson$3(path.join(dir, name))).filter((part) => part?.type === "text").map((part) => String(part.text ?? "")).join("").trim();
31380
+ return listDir(dir).filter((name) => name.endsWith(".json")).sort().map((name) => readJson$4(path.join(dir, name))).filter((part) => part?.type === "text").map((part) => String(part.text ?? "")).join("").trim();
30479
31381
  }
30480
31382
  function readOpencodeSession(sessionFile) {
30481
- const session2 = readJson$3(sessionFile);
31383
+ const session2 = readJson$4(sessionFile);
30482
31384
  const title = typeof session2?.title === "string" ? session2.title : "";
30483
31385
  if (!session2) return { title: "", messages: [] };
30484
31386
  const storageRoot = storageRootOf(sessionFile);
@@ -30487,7 +31389,7 @@ function readOpencodeSession(sessionFile) {
30487
31389
  const messages = [];
30488
31390
  const files = listDir(messageDir).filter((name) => name.endsWith(".json")).map((name) => {
30489
31391
  const filePath = path.join(messageDir, name);
30490
- const data = readJson$3(filePath);
31392
+ const data = readJson$4(filePath);
30491
31393
  const created = data && typeof data.time === "object" && data.time ? Number(data.time.created) : 0;
30492
31394
  return { filePath, data, created: Number.isFinite(created) ? created : 0 };
30493
31395
  }).sort((a, b) => a.created - b.created || a.filePath.localeCompare(b.filePath));
@@ -30502,7 +31404,7 @@ function readOpencodeSession(sessionFile) {
30502
31404
  function listOpencodeSessions(projectPath, home2 = process.env.HOME ?? "") {
30503
31405
  const storage = path.join(home2, ".local", "share", "opencode", "storage");
30504
31406
  const projectIds = listDir(path.join(storage, "project")).filter((name) => name.endsWith(".json")).map((name) => {
30505
- const data = readJson$3(path.join(storage, "project", name));
31407
+ const data = readJson$4(path.join(storage, "project", name));
30506
31408
  return data?.worktree === projectPath && typeof data.id === "string" ? data.id : null;
30507
31409
  }).filter((id) => Boolean(id));
30508
31410
  const sessions2 = [];
@@ -30510,7 +31412,7 @@ function listOpencodeSessions(projectPath, home2 = process.env.HOME ?? "") {
30510
31412
  const sessionDir2 = path.join(storage, "session", projectId);
30511
31413
  for (const name of listDir(sessionDir2).filter((n) => n.endsWith(".json"))) {
30512
31414
  const filePath = path.join(sessionDir2, name);
30513
- const meta = readJson$3(filePath);
31415
+ const meta = readJson$4(filePath);
30514
31416
  if (!meta || typeof meta.parentID === "string") continue;
30515
31417
  const { title, messages } = readOpencodeSession(filePath);
30516
31418
  if (messages.length === 0) continue;
@@ -32794,7 +33696,7 @@ async function suggestGoal(input, complete, timeoutMs = GOAL_SUGGEST_TIMEOUT_MS)
32794
33696
  }
32795
33697
  return result;
32796
33698
  }
32797
- function readJson$2(path2) {
33699
+ function readJson$3(path2) {
32798
33700
  try {
32799
33701
  return JSON.parse(readFileSync(path2, "utf8"));
32800
33702
  } catch {
@@ -32830,7 +33732,7 @@ function rewoundWatermark(branch, targetEntryId, watermark) {
32830
33732
  class BotMemoryService {
32831
33733
  constructor(deps) {
32832
33734
  this.deps = deps;
32833
- const saved = deps.watermarksFile ? readJson$2(deps.watermarksFile) : void 0;
33735
+ const saved = deps.watermarksFile ? readJson$3(deps.watermarksFile) : void 0;
32834
33736
  if (saved && typeof saved === "object" && !Array.isArray(saved)) {
32835
33737
  for (const [id, entry] of Object.entries(saved))
32836
33738
  if (typeof entry === "string" && entry) this.watermarks.set(id, entry);
@@ -35416,7 +36318,7 @@ class BotStore {
35416
36318
  }
35417
36319
  for (const name of names2) {
35418
36320
  if (!isBotId(name)) continue;
35419
- const bot = parseBotProfile(migrateRecord("bot", readJson$2(join(root, name, "bot.json"))));
36321
+ const bot = parseBotProfile(migrateRecord("bot", readJson$3(join(root, name, "bot.json"))));
35420
36322
  if (bot?.id === name) this.bots.set(name, bot);
35421
36323
  }
35422
36324
  }
@@ -35802,7 +36704,7 @@ class BotChatStore {
35802
36704
  }
35803
36705
  for (const name of names2) {
35804
36706
  if (!isBotChatId(name)) continue;
35805
- const chat = parseBotChat(migrateRecord("chat", readJson$2(join(root, name, "chat.json"))));
36707
+ const chat = parseBotChat(migrateRecord("chat", readJson$3(join(root, name, "chat.json"))));
35806
36708
  if (chat?.id === name) this.chats.set(name, chat);
35807
36709
  }
35808
36710
  for (const chat of this.chats.values())
@@ -36770,17 +37672,17 @@ function buildDelegationGroupContext(input) {
36770
37672
  const visible = fresh.filter((e) => delegationContextVisible(e, input.botId));
36771
37673
  if (visible.length === 0) return { text: "", cursor: nextCursor };
36772
37674
  const omitted = Math.max(0, visible.length - limit);
36773
- const shown = visible.slice(omitted);
37675
+ const shown2 = visible.slice(omitted);
36774
37676
  const L = DELEGATION_CONTEXT_LABELS;
36775
37677
  const where = L.where(
36776
37678
  typeof input.chatTitle === "string" ? input.chatTitle : "",
36777
37679
  typeof input.threadTitle === "string" ? input.threadTitle : void 0
36778
37680
  );
36779
37681
  const lines = [
36780
- escapeXml(first ? L.first(where, shown.length) : L.update(where, shown.length)),
37682
+ escapeXml(first ? L.first(where, shown2.length) : L.update(where, shown2.length)),
36781
37683
  escapeXml(L.guard),
36782
37684
  ...omitted > 0 && !first ? [TRANSCRIPT_LABELS.omitted(omitted)] : [],
36783
- ...shown.map(
37685
+ ...shown2.map(
36784
37686
  (e) => render(
36785
37687
  {
36786
37688
  ...e,
@@ -36811,7 +37713,7 @@ function previousRunsText(runs, options) {
36811
37713
  "</run>"
36812
37714
  ].join("\n");
36813
37715
  });
36814
- const tail = [
37716
+ const tail2 = [
36815
37717
  ...options.returnReason ? [`<return-reason>${cut(options.returnReason)}</return-reason>`] : [],
36816
37718
  "</previous-runs>"
36817
37719
  ];
@@ -36821,11 +37723,11 @@ function previousRunsText(runs, options) {
36821
37723
  for (let i = blocks.length - 1; i >= 0; i--) {
36822
37724
  const next = [blocks[i], ...kept];
36823
37725
  const omitted2 = i > 0 ? [omittedLine(i)] : [];
36824
- if (size(["<previous-runs>", ...omitted2, ...next, ...tail]) > PREVIOUS_RUNS_MAX) break;
37726
+ if (size(["<previous-runs>", ...omitted2, ...next, ...tail2]) > PREVIOUS_RUNS_MAX) break;
36825
37727
  kept = next;
36826
37728
  }
36827
37729
  const omitted = blocks.length - kept.length;
36828
- return ["<previous-runs>", ...omitted ? [omittedLine(omitted)] : [], ...kept, ...tail].join(
37730
+ return ["<previous-runs>", ...omitted ? [omittedLine(omitted)] : [], ...kept, ...tail2].join(
36829
37731
  "\n"
36830
37732
  );
36831
37733
  }
@@ -39026,7 +39928,7 @@ class GroupChatService {
39026
39928
  this.deps = deps;
39027
39929
  for (const chat of deps.chats.list()) {
39028
39930
  if (chat.kind !== "group") continue;
39029
- const saved = readJson$2(this.file(chat.id));
39931
+ const saved = readJson$3(this.file(chat.id));
39030
39932
  const interrupted = /* @__PURE__ */ new Set();
39031
39933
  if (saved && typeof saved === "object" && "state" in saved && saved.state && typeof saved.state === "object" && "current" in saved.state && typeof saved.state.current === "string") {
39032
39934
  interrupted.add(saved.state.current);
@@ -42059,8 +42961,8 @@ Reply with exactly parallel or serial, without explanation.`,
42059
42961
  }
42060
42962
  };
42061
42963
  }
42062
- async function removeBotMemorySpace(userData2, spaceId) {
42063
- if (!existsSync(join(userData2, "memory", "memory.db"))) return;
42964
+ async function removeBotMemorySpace(userData, spaceId) {
42965
+ if (!existsSync(join(userData, "memory", "memory.db"))) return;
42064
42966
  const host = await Promise.resolve().then(() => memoryHost);
42065
42967
  const db2 = host.memoryDatabase();
42066
42968
  await host.awaitMemoryDistill();
@@ -42571,7 +43473,7 @@ class BotRoutineStore {
42571
43473
  now;
42572
43474
  list(botId) {
42573
43475
  if (!isBotId(botId)) return [];
42574
- const raw = migrateRecord("routines", readJson$2(this.file(botId)));
43476
+ const raw = migrateRecord("routines", readJson$3(this.file(botId)));
42575
43477
  const items = raw && typeof raw === "object" && Array.isArray(raw.routines) ? raw.routines : [];
42576
43478
  return items.map(parseBotRoutine).filter((routine) => routine?.botId === botId);
42577
43479
  }
@@ -43438,7 +44340,9 @@ function getPricingTable(now) {
43438
44340
  pricingInflight ??= (async () => {
43439
44341
  try {
43440
44342
  const runtime = await getRuntime();
43441
- const table = buildPricingTable(runtime.getModels());
44343
+ const piTable = buildPricingTable(runtime.getModels());
44344
+ const devTable = buildPricingTable(getModelsDevModels());
44345
+ const table = { ...devTable, ...piTable };
43442
44346
  pricingCache = { table, loadedAt: now };
43443
44347
  return table;
43444
44348
  } catch {
@@ -44689,7 +45593,8 @@ class AgentSessionIndex {
44689
45593
  }
44690
45594
  if (event.type === "session-reloaded" || event.type === "oauth-pool-select" || event.type === "privacy-mask-ledger" || event.type === "workspace-lock-result" || event.type === "workspace-unlock-result" || event.type === "plugin-mcp-result")
44691
45595
  return false;
44692
- if (event.type === "title-generated" || event.type === "title-failed") return false;
45596
+ if (event.type === "title-generated" || event.type === "title-failed" || event.type === "tool-batch-completed")
45597
+ return false;
44693
45598
  if (event.type === "text-completed" || event.type === "text-failed" || event.type === "choice-classified" || event.type === "choice-failed" || event.type === "text-delta")
44694
45599
  return false;
44695
45600
  if (event.type === "mcp-status" || event.type === "mcp-oauth-refresh") return false;
@@ -45122,7 +46027,12 @@ function materializeSettingsProviders(value) {
45122
46027
  return materializeProviders(providers2, getModelDirectorySnapshot());
45123
46028
  }
45124
46029
  function providerConfig(provider2) {
45125
- return { api: provider2.api, apiKey: provider2.apiKey, baseUrl: provider2.baseUrl };
46030
+ return {
46031
+ api: provider2.api,
46032
+ apiKey: provider2.apiKey,
46033
+ baseUrl: provider2.baseUrl,
46034
+ ...provider2.headers ? { headers: provider2.headers } : {}
46035
+ };
45126
46036
  }
45127
46037
  function success(data) {
45128
46038
  return { ok: true, data };
@@ -45305,12 +46215,20 @@ function parseSubagentModelFields(params, services2, existing) {
45305
46215
  const providerId = requiredString(params, "providerId") ?? (typeof existing?.providerId === "string" ? existing.providerId : null);
45306
46216
  const modelId = requiredString(params, "modelId") ?? (typeof existing?.modelId === "string" ? existing.modelId : null);
45307
46217
  if (!providerId || !modelId) return invalid("providerId and modelId are required");
45308
- const provider2 = providersOf(services2).find((entry) => entry.id === providerId);
45309
- if (!provider2 || provider2.enabled === false) {
45310
- return unavailable(`provider not available: ${providerId}`);
46218
+ if (isVirtualRef({ providerId })) {
46219
+ const virtual = findVirtualModel(
46220
+ parseVirtualModels(settingsState$3(services2.readSettings()).virtualModels),
46221
+ { providerId, modelId }
46222
+ );
46223
+ if (!virtual?.enabled) return unavailable(`model not available: ${modelId}`);
46224
+ } else {
46225
+ const provider2 = providersOf(services2).find((entry) => entry.id === providerId);
46226
+ if (!provider2 || provider2.enabled === false) {
46227
+ return unavailable(`provider not available: ${providerId}`);
46228
+ }
46229
+ const model = Array.isArray(provider2.models) ? provider2.models.find((entry) => asRecord$1(entry)?.id === modelId) : void 0;
46230
+ if (!model || model.enabled === false) return unavailable(`model not available: ${modelId}`);
45311
46231
  }
45312
- const model = Array.isArray(provider2.models) ? provider2.models.find((entry) => asRecord$1(entry)?.id === modelId) : void 0;
45313
- if (!model || model.enabled === false) return unavailable(`model not available: ${modelId}`);
45314
46232
  const description = typeof params.description === "string" ? params.description : typeof existing?.description === "string" ? existing.description : "";
45315
46233
  const reasoning = params.reasoning === "follow" ? void 0 : params.reasoning === "on" || params.reasoning === "off" ? params.reasoning : existing?.reasoning === "on" || existing?.reasoning === "off" ? existing.reasoning : void 0;
45316
46234
  const levelInput = params.thinkingLevel === "follow" ? void 0 : typeof params.thinkingLevel === "string" && MODEL_THINKING_LEVEL_OVERRIDES.includes(params.thinkingLevel) ? params.thinkingLevel : typeof existing?.thinkingLevel === "string" && MODEL_THINKING_LEVEL_OVERRIDES.includes(existing.thinkingLevel) ? existing.thinkingLevel : void 0;
@@ -46659,7 +47577,10 @@ function toMessage(error) {
46659
47577
  }
46660
47578
  return String(error);
46661
47579
  }
46662
- async function listModels(config2, extraHeaders) {
47580
+ function withProviderHeaders(headers, extra) {
47581
+ return extra ? { ...headers, ...extra } : headers;
47582
+ }
47583
+ async function listModels(config2) {
46663
47584
  const base = resolveBase(config2);
46664
47585
  const key = config2.apiKey.trim();
46665
47586
  try {
@@ -46686,14 +47607,17 @@ async function listModels(config2, extraHeaders) {
46686
47607
  url = `${base}/models`;
46687
47608
  headers = { Authorization: `Bearer ${key}` };
46688
47609
  }
46689
- if (extraHeaders) headers = { ...headers, ...extraHeaders };
47610
+ headers = withProviderHeaders(headers, config2.headers);
46690
47611
  let response = await request$2(url, { headers, redirect: "manual" });
46691
47612
  if (response.status === 401 && config2.api === "anthropic-messages" && !isOfficialAnthropicHost(url)) {
46692
47613
  const retryHeaders = {
46693
47614
  Authorization: `Bearer ${key}`,
46694
47615
  "anthropic-version": ANTHROPIC_VERSION
46695
47616
  };
46696
- response = await request$2(url, { headers: retryHeaders, redirect: "manual" });
47617
+ response = await request$2(url, {
47618
+ headers: withProviderHeaders(retryHeaders, config2.headers),
47619
+ redirect: "manual"
47620
+ });
46697
47621
  }
46698
47622
  if (!response.ok) return { ok: false, models: [], error: httpError(response) };
46699
47623
  const data = await response.json();
@@ -46856,6 +47780,7 @@ async function testProvider(config2, modelId) {
46856
47780
  messages: [{ role: "user", content: "hi" }]
46857
47781
  };
46858
47782
  }
47783
+ headers = withProviderHeaders(headers, config2.headers);
46859
47784
  const response = await request$2(url, { method: "POST", headers, body: JSON.stringify(body) });
46860
47785
  const latencyMs = Date.now() - started;
46861
47786
  if (!response.ok) return { ok: false, latencyMs, message: httpError(response) };
@@ -46880,7 +47805,12 @@ async function fetchXaiSubscriptionModels(token) {
46880
47805
  if (!key) return [];
46881
47806
  const [official, cli] = await Promise.all([
46882
47807
  listModels({ api: "openai-completions", apiKey: key, baseUrl: XAI_API_BASE }),
46883
- listModels({ api: "openai-completions", apiKey: key, baseUrl: XAI_CLI_BASE }, CLI_HEADERS)
47808
+ listModels({
47809
+ api: "openai-completions",
47810
+ apiKey: key,
47811
+ baseUrl: XAI_CLI_BASE,
47812
+ headers: CLI_HEADERS
47813
+ })
46884
47814
  ]);
46885
47815
  const merged = /* @__PURE__ */ new Map();
46886
47816
  for (const model of [...official.ok ? official.models : [], ...cli.ok ? cli.models : []]) {
@@ -46967,6 +47897,7 @@ async function queryModelMeta(query) {
46967
47897
  }
46968
47898
  }
46969
47899
  }
47900
+ catalog22 = withModelsDevOauthModels(providerId, catalog22, getModelsDevModels());
46970
47901
  const wanted = query.modelIds.length === 0 ? null : new Set(query.modelIds);
46971
47902
  const models = [];
46972
47903
  const seen = /* @__PURE__ */ new Set();
@@ -46986,10 +47917,17 @@ async function queryModelMeta(query) {
46986
47917
  return { ok: false, models: [], error: "Invalid query" };
46987
47918
  }
46988
47919
  const catalog2 = runtime.getModels();
47920
+ const devModels = getModelsDevModels();
46989
47921
  return {
46990
47922
  ok: true,
46991
47923
  models: query.modelIds.map(
46992
- (modelId) => mapCatalogFallback(modelId, findCatalogModelById(catalog2, modelId))
47924
+ (modelId) => mapCatalogFallback(
47925
+ modelId,
47926
+ mergeCatalogEntry(
47927
+ findCatalogModelById(catalog2, modelId),
47928
+ findModelsDevModel(devModels, modelId)
47929
+ )
47930
+ )
46993
47931
  )
46994
47932
  };
46995
47933
  } catch (error) {
@@ -47281,7 +48219,7 @@ function newestJsonlMtime(dir) {
47281
48219
  }
47282
48220
  return newest;
47283
48221
  }
47284
- function readJson$1(file2) {
48222
+ function readJson$2(file2) {
47285
48223
  try {
47286
48224
  const parsed = JSON.parse(fs.readFileSync(file2, "utf8"));
47287
48225
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
@@ -47303,7 +48241,7 @@ function readEditorWorkspaceTimes(configDir) {
47303
48241
  for (const entry of dirs) {
47304
48242
  if (!entry.isDirectory()) continue;
47305
48243
  const dir = path.join(storageRoot, entry.name);
47306
- const meta = readJson$1(path.join(dir, "workspace.json"));
48244
+ const meta = readJson$2(path.join(dir, "workspace.json"));
47307
48245
  const folder = folderUriToPath(meta?.folder);
47308
48246
  if (!folder) continue;
47309
48247
  const lastUsed = Math.max(
@@ -47353,7 +48291,7 @@ function readEditorProjects(editor2) {
47353
48291
  }
47354
48292
  }
47355
48293
  function readClaudeProjects() {
47356
- const json2 = readJson$1(path.join(HOME$3, ".claude.json"));
48294
+ const json2 = readJson$2(path.join(HOME$3, ".claude.json"));
47357
48295
  const projects2 = json2?.projects;
47358
48296
  if (!projects2 || typeof projects2 !== "object") return [];
47359
48297
  return Object.keys(projects2).map((projectPath) => {
@@ -47372,8 +48310,8 @@ function cwdOfCodexRollout(filePath) {
47372
48310
  try {
47373
48311
  const buffer = Buffer.alloc(4096);
47374
48312
  const bytes = fs.readSync(fd, buffer, 0, buffer.length, 0);
47375
- const firstLine = buffer.toString("utf-8", 0, bytes).split("\n", 1)[0];
47376
- const entry = JSON.parse(firstLine);
48313
+ const firstLine2 = buffer.toString("utf-8", 0, bytes).split("\n", 1)[0];
48314
+ const entry = JSON.parse(firstLine2);
47377
48315
  return typeof entry.payload?.cwd === "string" ? entry.payload.cwd : null;
47378
48316
  } catch {
47379
48317
  return null;
@@ -47412,7 +48350,7 @@ function parseIsoMs(value) {
47412
48350
  }
47413
48351
  function readCodexProjects() {
47414
48352
  const found = [];
47415
- const state = readJson$1(path.join(HOME$3, ".codex", ".codex-global-state.json"));
48353
+ const state = readJson$2(path.join(HOME$3, ".codex", ".codex-global-state.json"));
47416
48354
  const localProjects = state?.["local-projects"];
47417
48355
  const byId2 = /* @__PURE__ */ new Map();
47418
48356
  if (localProjects && typeof localProjects === "object") {
@@ -47815,7 +48753,7 @@ const capabilityGateway = new CapabilityGateway(
47815
48753
  const store = getSshConnectionStore();
47816
48754
  const secret = store.getSecret(id);
47817
48755
  if (!secret) return { ok: false, error: "Connection not found." };
47818
- const { resolveSshTarget: resolveSshTarget2 } = await import("./chunks/workflowPresets-DqSsjOj6.js").then((n) => n.d0);
48756
+ const { resolveSshTarget: resolveSshTarget2 } = await import("./chunks/workflowPresets-CuLnfQqa.js").then((n) => n.dp);
47819
48757
  const failure2 = await sshProbeLogin(resolveSshTarget2(secret), {
47820
48758
  auth: secret.auth,
47821
48759
  port: secret.port,
@@ -48063,12 +49001,12 @@ function getBotServices() {
48063
49001
  if (services) return services;
48064
49002
  const authority = getSourceAuthorityRegistry();
48065
49003
  if (!authority) return null;
48066
- const userData2 = app.getPath("userData");
48067
- const botsRoot = path.join(userData2, "bots");
49004
+ const userData = app.getPath("userData");
49005
+ const botsRoot = path.join(userData, "bots");
48068
49006
  const bots2 = new BotStore(botsRoot);
48069
- const chats = new BotChatStore(path.join(userData2, "bot-chats"));
49007
+ const chats = new BotChatStore(path.join(userData, "bot-chats"));
48070
49008
  const notes = new BotNotesService({
48071
- store: new BotNotesStore({ bots: botsRoot, chats: path.join(userData2, "bot-chats") }),
49009
+ store: new BotNotesStore({ bots: botsRoot, chats: path.join(userData, "bot-chats") }),
48072
49010
  complete: assistantCompleter(4096),
48073
49011
  enabled: (botId) => bots2.get(botId)?.memory.enabled === true,
48074
49012
  recent: recentDistilled,
@@ -48162,9 +49100,9 @@ function getBotServices() {
48162
49100
  discussEnabled: botDiscussModeEnabled
48163
49101
  });
48164
49102
  const delegationStore = new DelegationStore(
48165
- path.join(userData2, "bot-chats", "delegations.jsonl")
49103
+ path.join(userData, "bot-chats", "delegations.jsonl")
48166
49104
  );
48167
- const taskStore = new GroupTaskStore(path.join(userData2, "bot-chats"));
49105
+ const taskStore = new GroupTaskStore(path.join(userData, "bot-chats"));
48168
49106
  let titlerRef;
48169
49107
  const composerRefs = createComposerRefs({
48170
49108
  bots: bots2,
@@ -48337,7 +49275,7 @@ function getBotServices() {
48337
49275
  emit: emitBotEvent
48338
49276
  });
48339
49277
  const inbox = new BotInboxService({
48340
- store: new BotInboxStore(path.join(userData2, "bot-chats", "inbox.jsonl")),
49278
+ store: new BotInboxStore(path.join(userData, "bot-chats", "inbox.jsonl")),
48341
49279
  conversation: (id) => authority.conversation(id),
48342
49280
  delegations: () => delegationStore.list(),
48343
49281
  routines: () => routines.listAll(),
@@ -48360,7 +49298,7 @@ function getBotServices() {
48360
49298
  const memory2 = new BotMemoryService({
48361
49299
  bots: bots2,
48362
49300
  chats,
48363
- watermarksFile: path.join(userData2, "bot-chats", "memory-watermarks.json"),
49301
+ watermarksFile: path.join(userData, "bot-chats", "memory-watermarks.json"),
48364
49302
  isCodeProject: (id) => {
48365
49303
  const project = authority.project(id);
48366
49304
  return project?.state === "active" && project.kind !== "bot-home" && project.kind !== "scratch";
@@ -51160,19 +52098,51 @@ async function requestTitleSummary(conversationId, input, sessionModel) {
51160
52098
  if (state?.titleSummaryEnabled !== true) {
51161
52099
  return { ok: false, error: "title summary disabled" };
51162
52100
  }
52101
+ const candidates = await resolveTitleCandidates(state, sessionModel);
52102
+ if (!candidates) return { ok: false, error: "model credentials unavailable" };
52103
+ if (candidates.length === 0) return { ok: false, error: "no usable title model" };
52104
+ return summarizeConversationTitle(conversationId, input, candidates);
52105
+ }
52106
+ async function resolveTitleCandidates(state, sessionModel) {
51163
52107
  let credentialKeys;
51164
52108
  try {
51165
52109
  credentialKeys = await readStoredOauthCredentialKeys();
51166
52110
  } catch {
51167
- return { ok: false, error: "model credentials unavailable" };
52111
+ return null;
51168
52112
  }
51169
52113
  const candidates = [];
51170
52114
  for (const candidate of titleModelCandidates(state, sessionModel)) {
51171
52115
  const resolved = resolveModelSelection(candidate.providerId, candidate.modelId, credentialKeys);
51172
52116
  if (resolved.ok && resolved.selection) candidates.push(resolved.selection.config);
51173
52117
  }
51174
- if (candidates.length === 0) return { ok: false, error: "no usable title model" };
51175
- return summarizeConversationTitle(conversationId, input, candidates);
52118
+ return candidates;
52119
+ }
52120
+ const TOOL_BATCH_LABEL_TIMEOUT_MS = 15e3;
52121
+ async function labelToolBatch(identity, digest) {
52122
+ const state = readSettings()?.["enso-settings"]?.state;
52123
+ if (state?.titleSummaryEnabled !== true) return;
52124
+ const candidates = await resolveTitleCandidates(state);
52125
+ if (!candidates?.length) return;
52126
+ try {
52127
+ const label2 = cleanToolBatchLabel(
52128
+ await completeText({
52129
+ systemPrompt: TOOL_BATCH_LABEL_SYSTEM_PROMPT,
52130
+ userText: toolBatchLabelPrompt(digest),
52131
+ candidates,
52132
+ timeoutMs: TOOL_BATCH_LABEL_TIMEOUT_MS,
52133
+ maxTokens: 128,
52134
+ reasoning: "off"
52135
+ })
52136
+ );
52137
+ if (label2)
52138
+ appendSessionCustomEntry(identity, {
52139
+ kind: "tool-batch-label",
52140
+ callId: digest.callId,
52141
+ label: label2,
52142
+ at: Date.now()
52143
+ });
52144
+ } catch {
52145
+ }
51176
52146
  }
51177
52147
  function wirePairSessionHost() {
51178
52148
  configurePairSessionHost({
@@ -51560,6 +52530,10 @@ function registerAgentHandlers() {
51560
52530
  clearMcpStatuses();
51561
52531
  pushMcpStatus({ type: "mcp-status-cleared" });
51562
52532
  }
52533
+ if (workerEvent.type === "tool-batch-completed") {
52534
+ void labelToolBatch(workerEvent.identity, workerEvent.digest);
52535
+ return;
52536
+ }
51563
52537
  if (workerEvent.type === "session-reloaded" || workerEvent.type === "workspace-lock-result" || workerEvent.type === "oauth-pool-select" || workerEvent.type === "privacy-mask-ledger" || workerEvent.type === "mcp-oauth-refresh" || workerEvent.type === "plugin-mcp-result" || workerEvent.type === "workspace-unlock-result")
51564
52538
  return;
51565
52539
  dispatchService?.observe(workerEvent);
@@ -52163,6 +53137,15 @@ function registerAgentHandlers() {
52163
53137
  );
52164
53138
  }
52165
53139
  );
53140
+ ipcMain.handle(
53141
+ IPC_CHANNELS.AGENT_WITHDRAW_STEER,
53142
+ (_event, sessionId, deliveryId) => {
53143
+ const rejected = botControlError(sessionId);
53144
+ if (rejected) return rejected;
53145
+ const identity = exactIdentity(sessionId);
53146
+ return identity && isDeliveryId(deliveryId) ? withdrawSteerSession(identity, deliveryId) : { ok: false, error: "invalid withdraw-steer or stale session generation" };
53147
+ }
53148
+ );
52166
53149
  ipcMain.handle(IPC_CHANNELS.AGENT_ABORT, (_event, sessionId) => {
52167
53150
  const identity = exactIdentity(sessionId);
52168
53151
  return identity ? abortSession(identity) : { ok: false, error: "invalid abort or stale session generation" };
@@ -52505,7 +53488,19 @@ function registerAppBadgeHandlers() {
52505
53488
  }
52506
53489
  const THEME_ANCHORS = [
52507
53490
  "canvas",
53491
+ "sidebar-toggle",
53492
+ "search-button",
53493
+ "new-session",
52508
53494
  "sidebar",
53495
+ "group-chip",
53496
+ "section-header",
53497
+ "project-row",
53498
+ "tree-chevron",
53499
+ "session-row",
53500
+ "session-status",
53501
+ "row-menu",
53502
+ "node-switcher",
53503
+ "settings-button",
52509
53504
  "main",
52510
53505
  "title-bar",
52511
53506
  "session-tabs",
@@ -52517,6 +53512,7 @@ const THEME_ANCHORS = [
52517
53512
  "thinking",
52518
53513
  "todo",
52519
53514
  "code-block",
53515
+ "approval",
52520
53516
  "composer",
52521
53517
  "status-line",
52522
53518
  "settings-nav",
@@ -53665,11 +54661,19 @@ function registerAssetHandlers() {
53665
54661
  }).then((local2) => [...plugin, ...local2]);
53666
54662
  }
53667
54663
  );
53668
- ipcMain.handle(IPC_CHANNELS.ASSETS_LIST_WORKFLOW_PRESETS, (_event, conversationId) => {
53669
- if (typeof conversationId !== "string" || !conversationId) return [];
53670
- const cwd = resolveLocalCwdForBrowser(conversationId) ?? void 0;
53671
- return listWorkflowPresets(workflowPresetRoots(cwd, { customDir: customWorkflowPresetDir() }));
53672
- });
54664
+ ipcMain.handle(
54665
+ IPC_CHANNELS.ASSETS_LIST_WORKFLOW_PRESETS,
54666
+ (_event, conversationId, presetId) => {
54667
+ if (typeof conversationId !== "string" || !conversationId) return [];
54668
+ const cwd = resolveLocalCwdForBrowser(conversationId) ?? void 0;
54669
+ const pluginFiles = menuPluginWorkflowPaths(
54670
+ typeof presetId === "string" && presetId ? presetId : void 0
54671
+ );
54672
+ return listWorkflowPresets(
54673
+ workflowPresetRoots(cwd, { customDir: customWorkflowPresetDir(), pluginFiles })
54674
+ );
54675
+ }
54676
+ );
53673
54677
  ipcMain.handle(IPC_CHANNELS.WORKFLOW_PRESETS_LIST, () => [
53674
54678
  ...listCustomWorkflowPresets(customWorkflowPresetDir()),
53675
54679
  ...listBuiltinWorkflowPresets()
@@ -53774,7 +54778,7 @@ const trusted = (id) => isMainRenderer(id) || isSettingsRenderer(id);
53774
54778
  function registerBotTemplateHandlers() {
53775
54779
  ipcMain.handle(IPC_CHANNELS.BOT_TEMPLATES_GET, (event) => {
53776
54780
  if (!trusted(event.sender.id)) return { ok: false, error: "Invalid request." };
53777
- return { ok: true, library: parseTemplateLibrary(readJson$2(libraryPath())) };
54781
+ return { ok: true, library: parseTemplateLibrary(readJson$3(libraryPath())) };
53778
54782
  });
53779
54783
  ipcMain.handle(IPC_CHANNELS.BOT_TEMPLATES_SAVE, (event, request2) => {
53780
54784
  if (!trusted(event.sender.id) || !request2 || typeof request2 !== "object")
@@ -54206,6 +55210,24 @@ function registerDcgHandlers() {
54206
55210
  }
54207
55211
  });
54208
55212
  }
55213
+ const MAX_PASSWORD = 1024;
55214
+ function parsePassword(value) {
55215
+ if (value === null) return null;
55216
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_PASSWORD)
55217
+ return void 0;
55218
+ return /[\r\n\0]/.test(value) ? void 0 : value;
55219
+ }
55220
+ function registerElevationHandlers() {
55221
+ ipcMain.handle(
55222
+ IPC_CHANNELS.ELEVATION_PENDING,
55223
+ (event) => canAnswerElevation(event.sender.id) ? elevationBroker.list() : []
55224
+ );
55225
+ ipcMain.handle(IPC_CHANNELS.ELEVATION_ANSWER, (event, id, password) => {
55226
+ if (!canAnswerElevation(event.sender.id) || typeof id !== "string") return false;
55227
+ const parsed = parsePassword(password);
55228
+ return parsed === void 0 ? false : elevationBroker.answer(id, parsed);
55229
+ });
55230
+ }
54209
55231
  const MAX_ASSET_BYTES$1 = 8 * 1024 * 1024;
54210
55232
  const MAX_ARTIFACT_BYTES = 8 * 1024 * 1024;
54211
55233
  const MAX_VIEW_STATE_BYTES = 1024 * 1024;
@@ -54414,6 +55436,10 @@ function registerExtensionPluginHandlers() {
54414
55436
  return plugins().setCrossSessionInject(id, allowed);
54415
55437
  }
54416
55438
  );
55439
+ ipcMain.handle(IPC_CHANNELS.EXTENSION_PLUGINS_SET_DEV_WATCH, (_e, id, on) => {
55440
+ if (!isId(id) || typeof on !== "boolean") return { ok: false, error: "参数不合法" };
55441
+ return plugins().setDevWatch(id, on);
55442
+ });
54417
55443
  ipcMain.handle(IPC_CHANNELS.EXTENSION_PLUGINS_APPROVE_PENDING, (_e, id) => {
54418
55444
  if (!isId(id)) return { ok: false, error: "参数不合法" };
54419
55445
  return plugins().approvePending(id);
@@ -56264,9 +57290,9 @@ async function loadFile(cwd, rel, status2, host) {
56264
57290
  let oldText = "";
56265
57291
  let newText = "";
56266
57292
  if (status2 === "modified" || status2 === "deleted") {
56267
- const shown = await host.run(["show", `HEAD:${rel}`], cwd);
56268
- if (shown.code !== 0) return null;
56269
- oldText = shown.stdout;
57293
+ const shown2 = await host.run(["show", `HEAD:${rel}`], cwd);
57294
+ if (shown2.code !== 0) return null;
57295
+ oldText = shown2.stdout;
56270
57296
  }
56271
57297
  if (status2 !== "deleted") {
56272
57298
  const current2 = await host.readFile(abs);
@@ -56276,7 +57302,7 @@ async function loadFile(cwd, rel, status2, host) {
56276
57302
  if (oldText === newText) return null;
56277
57303
  return { path: rel, status: status2, oldText, newText };
56278
57304
  }
56279
- function isDir$1(dir) {
57305
+ function isDir(dir) {
56280
57306
  try {
56281
57307
  return statSync(dir).isDirectory();
56282
57308
  } catch {
@@ -56285,7 +57311,7 @@ function isDir$1(dir) {
56285
57311
  }
56286
57312
  function localGitDiffHost() {
56287
57313
  return {
56288
- isDir: isDir$1,
57314
+ isDir,
56289
57315
  run: (args, cwd) => runGit(args, cwd),
56290
57316
  readFile: async (absPath) => readUtf8(absPath)
56291
57317
  };
@@ -58699,6 +59725,12 @@ function remoteLinkRevoked(pairId) {
58699
59725
  if (senders.length > 0) refreshRemoteLeadership();
58700
59726
  }
58701
59727
  function registerPairHandlers() {
59728
+ setPairProjectDeps({
59729
+ createProject: (request2) => {
59730
+ const registry2 = getSourceAuthorityRegistry();
59731
+ return registry2 ? registry2.createProject(request2) : { accepted: false, error: "Project registry is not ready." };
59732
+ }
59733
+ });
58702
59734
  setPairStatusListener(() => {
58703
59735
  const status2 = getPairStatus();
58704
59736
  broadcastToRenderers(IPC_CHANNELS.PAIR_STATUS_CHANGED, status2);
@@ -58762,7 +59794,7 @@ const SHOWN = 3;
58762
59794
  const DETAIL_MAX = 80;
58763
59795
  const DENIED = "User denied this operation";
58764
59796
  const clip = (text2) => text2.length > DETAIL_MAX ? `${text2.slice(0, DETAIL_MAX - 1)}…` : text2;
58765
- const textOf = (message2) => message2.content.map((part) => part.type === "text" ? part.text : "").join("");
59797
+ const textOf$1 = (message2) => message2.content.map((part) => part.type === "text" ? part.text : "").join("");
58766
59798
  function liveActivity(session2, queued) {
58767
59799
  const { messages } = session2;
58768
59800
  let start = messages.length;
@@ -58784,14 +59816,14 @@ function liveActivity(session2, queued) {
58784
59816
  id: part.id,
58785
59817
  name: part.name,
58786
59818
  detail: clip(detailOf(part.arguments)),
58787
- status: !done ? "running" : !done.isError ? "done" : textOf(done) === DENIED ? "denied" : isHumanRequestTimeout(textOf(done)) ? "timeout" : "error",
59819
+ status: !done ? "running" : !done.isError ? "done" : textOf$1(done) === DENIED ? "denied" : isHumanRequestTimeout(textOf$1(done)) ? "timeout" : "error",
58788
59820
  ...done?.toolDurationMs !== void 0 ? { durationMs: done.toolDurationMs } : {},
58789
59821
  ...!done && startedAt !== void 0 ? { startedAt } : {}
58790
59822
  });
58791
59823
  }
58792
59824
  }
58793
59825
  const last = turn.at(-1);
58794
- const state = session2.retry ? "retrying" : steps.some((step) => step.status === "running") ? "tool" : last?.role === "assistant" && last.content.at(-1)?.type === "text" && textOf(last) ? "typing" : "thinking";
59826
+ const state = session2.retry ? "retrying" : steps.some((step) => step.status === "running") ? "tool" : last?.role === "assistant" && last.content.at(-1)?.type === "text" && textOf$1(last) ? "typing" : "thinking";
58795
59827
  return {
58796
59828
  state,
58797
59829
  ...session2.runStartedAt !== void 0 ? { startedAt: session2.runStartedAt } : {},
@@ -59362,51 +60394,6 @@ function registerPrivacyMaskHandlers() {
59362
60394
  return listPrivacyMaskRecords(days);
59363
60395
  });
59364
60396
  }
59365
- async function isDir(target) {
59366
- return stat(target).then(
59367
- (info) => info.isDirectory(),
59368
- () => false
59369
- );
59370
- }
59371
- async function listHostDirs(target, home2 = homedir()) {
59372
- const input = target?.trim() || "~";
59373
- const expanded = input === "~" ? home2 : input.startsWith("~/") ? path.join(home2, input.slice(2)) : input;
59374
- let dir = path.resolve(home2, expanded);
59375
- while (!await isDir(dir)) {
59376
- const up = path.dirname(dir);
59377
- if (up === dir) return { ok: false, error: "Directory not found." };
59378
- dir = up;
59379
- }
59380
- try {
59381
- const entries = await readdir(dir, { withFileTypes: true });
59382
- const dirs = [];
59383
- for (const entry of entries) {
59384
- if (entry.name.startsWith(".")) continue;
59385
- if (entry.isDirectory() || entry.isSymbolicLink() && await isDir(path.join(dir, entry.name)))
59386
- dirs.push(entry.name);
59387
- }
59388
- dirs.sort((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
59389
- const parent = path.dirname(dir);
59390
- return { ok: true, path: dir, parent: parent === dir ? null : parent, dirs };
59391
- } catch (error) {
59392
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
59393
- }
59394
- }
59395
- async function createHostDir(parent, rawName) {
59396
- if (!path.isAbsolute(parent)) return { ok: false, error: "Invalid request." };
59397
- const name = rawName.trim();
59398
- if (!name || name === "." || name === ".." || /[/\\\0]/.test(name) || Buffer.byteLength(name) > 255)
59399
- return { ok: false, error: "Invalid folder name." };
59400
- const target = path.join(parent, name);
59401
- try {
59402
- await mkdir(target);
59403
- } catch (error) {
59404
- if (error.code === "EEXIST")
59405
- return { ok: false, error: "A file or folder with that name already exists." };
59406
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
59407
- }
59408
- return listHostDirs(target);
59409
- }
59410
60397
  function parseRevealRequest(request2) {
59411
60398
  if (!request2 || typeof request2 !== "object" || Array.isArray(request2)) return null;
59412
60399
  const projectId = request2.projectId;
@@ -60136,7 +61123,13 @@ function toApiConfig(input) {
60136
61123
  if (typeof api !== "string" || typeof apiKey !== "string" || typeof baseUrl !== "string") {
60137
61124
  return null;
60138
61125
  }
60139
- return { api, apiKey, baseUrl };
61126
+ const headers = parseProviderHeaders(input.headers);
61127
+ return {
61128
+ api,
61129
+ apiKey,
61130
+ baseUrl,
61131
+ ...headers ? { headers } : {}
61132
+ };
60140
61133
  }
60141
61134
  const MAX_MODEL_IDS = 256;
60142
61135
  const MAX_MODEL_ID_LENGTH = 256;
@@ -60190,6 +61183,7 @@ function registerProviderHandlers() {
60190
61183
  if (!parsed) return { ok: false, models: [], error: "Invalid query" };
60191
61184
  return queryModelMeta(parsed);
60192
61185
  });
61186
+ ipcMain.handle(IPC_CHANNELS.PROVIDERS_REFRESH_MODEL_CATALOG, () => refreshModelCatalogNow());
60193
61187
  ipcMain.handle(
60194
61188
  IPC_CHANNELS.PROVIDERS_CLASSIFIER_MODELS,
60195
61189
  (_event, providerId) => listClassifierModels(providerId)
@@ -61233,6 +62227,7 @@ function registerIpcHandlers() {
61233
62227
  registerAppBadgeHandlers();
61234
62228
  registerSpeechHandlers();
61235
62229
  registerDcgHandlers();
62230
+ registerElevationHandlers();
61236
62231
  }
61237
62232
  function createAppQuitDrain(steps) {
61238
62233
  let draining = false;
@@ -65890,8 +66885,8 @@ function parseServerConfig(text2) {
65890
66885
  }
65891
66886
  return { ok: true, config: config2 };
65892
66887
  }
65893
- function readServerConfig(dataDir) {
65894
- const file2 = path.join(dataDir, CONFIG_FILE);
66888
+ function readServerConfig(dataDir2) {
66889
+ const file2 = path.join(dataDir2, CONFIG_FILE);
65895
66890
  let text2;
65896
66891
  try {
65897
66892
  text2 = readFileSync(file2, "utf8");
@@ -65921,9 +66916,9 @@ function serializeServerConfig(config2) {
65921
66916
  return `${lines.join("\n")}
65922
66917
  `;
65923
66918
  }
65924
- function writeServerConfig(dataDir, config2) {
65925
- const file2 = path.join(dataDir, CONFIG_FILE);
65926
- mkdirSync(dataDir, { recursive: true });
66919
+ function writeServerConfig(dataDir2, config2) {
66920
+ const file2 = path.join(dataDir2, CONFIG_FILE);
66921
+ mkdirSync(dataDir2, { recursive: true });
65927
66922
  const tmp = `${file2}.tmp`;
65928
66923
  writeFileSync(tmp, serializeServerConfig(config2), { mode: 384 });
65929
66924
  renameSync(tmp, file2);
@@ -65955,6 +66950,212 @@ function applyConfigEnv(env, config2) {
65955
66950
  if (!env[key]?.trim()) env[key] = value;
65956
66951
  }
65957
66952
  }
66953
+ const DOS_EPOCH = 33;
66954
+ const ZIP_VERSION = 20;
66955
+ const DEFLATE = 8;
66956
+ const UTF8 = 2048;
66957
+ function readManifest(dir, hostVersion) {
66958
+ const path2 = join(dir, "enso-plugin.json");
66959
+ let text2;
66960
+ try {
66961
+ text2 = readFileSync(path2, "utf8");
66962
+ } catch (error) {
66963
+ if (isEnoent(error)) throw new Error("找不到清单 enso-plugin.json");
66964
+ throw error;
66965
+ }
66966
+ let raw;
66967
+ try {
66968
+ raw = JSON.parse(text2);
66969
+ } catch {
66970
+ throw new Error("清单不是合法 JSON");
66971
+ }
66972
+ const parsed = parseExtensionPluginManifest(raw, hostVersion);
66973
+ if (!parsed.ok) throw new Error(parsed.errors.join("\n"));
66974
+ return parsed.manifest;
66975
+ }
66976
+ function isEnoent(error) {
66977
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
66978
+ }
66979
+ function collect(root) {
66980
+ const names2 = [];
66981
+ const walk2 = (dir) => {
66982
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
66983
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
66984
+ const full = join(dir, entry.name);
66985
+ if (entry.isDirectory()) {
66986
+ if (entry.name === "test") continue;
66987
+ walk2(full);
66988
+ continue;
66989
+ }
66990
+ if (!entry.isFile() || entry.name.endsWith(".zip")) continue;
66991
+ if (dir === root && entry.name === "enso-testing.mjs") continue;
66992
+ names2.push(relative(root, full).split(sep).join("/"));
66993
+ }
66994
+ };
66995
+ walk2(root);
66996
+ names2.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
66997
+ return names2;
66998
+ }
66999
+ function buildZip(files) {
67000
+ const parts = [];
67001
+ const centrals = [];
67002
+ let offset = 0;
67003
+ for (const file2 of files) {
67004
+ const name = Buffer.from(file2.name, "utf8");
67005
+ const compressed = deflateRawSync(file2.data);
67006
+ const crc2 = crc32(file2.data) >>> 0;
67007
+ const local2 = Buffer.alloc(30);
67008
+ local2.writeUInt32LE(67324752, 0);
67009
+ local2.writeUInt16LE(ZIP_VERSION, 4);
67010
+ local2.writeUInt16LE(UTF8, 6);
67011
+ local2.writeUInt16LE(DEFLATE, 8);
67012
+ local2.writeUInt16LE(0, 10);
67013
+ local2.writeUInt16LE(DOS_EPOCH, 12);
67014
+ local2.writeUInt32LE(crc2, 14);
67015
+ local2.writeUInt32LE(compressed.length, 18);
67016
+ local2.writeUInt32LE(file2.data.length, 22);
67017
+ local2.writeUInt16LE(name.length, 26);
67018
+ parts.push(local2, name, compressed);
67019
+ const central = Buffer.alloc(46);
67020
+ central.writeUInt32LE(33639248, 0);
67021
+ central.writeUInt16LE(ZIP_VERSION, 4);
67022
+ central.writeUInt16LE(ZIP_VERSION, 6);
67023
+ central.writeUInt16LE(UTF8, 8);
67024
+ central.writeUInt16LE(DEFLATE, 10);
67025
+ central.writeUInt16LE(0, 12);
67026
+ central.writeUInt16LE(DOS_EPOCH, 14);
67027
+ central.writeUInt32LE(crc2, 16);
67028
+ central.writeUInt32LE(compressed.length, 20);
67029
+ central.writeUInt32LE(file2.data.length, 24);
67030
+ central.writeUInt16LE(name.length, 28);
67031
+ central.writeUInt32LE(offset, 42);
67032
+ centrals.push(central, name);
67033
+ offset += local2.length + name.length + compressed.length;
67034
+ }
67035
+ const centralDir = Buffer.concat(centrals);
67036
+ const eocd = Buffer.alloc(22);
67037
+ eocd.writeUInt32LE(101010256, 0);
67038
+ eocd.writeUInt16LE(files.length, 8);
67039
+ eocd.writeUInt16LE(files.length, 10);
67040
+ eocd.writeUInt32LE(centralDir.length, 12);
67041
+ eocd.writeUInt32LE(offset, 16);
67042
+ return Buffer.concat([...parts, centralDir, eocd]);
67043
+ }
67044
+ function packPlugin(dir, opts) {
67045
+ const root = resolve(dir);
67046
+ const manifest = readManifest(root, opts.hostVersion);
67047
+ const bytes = buildZip(
67048
+ collect(root).map((name) => ({
67049
+ name,
67050
+ data: readFileSync(join(root, ...name.split("/")))
67051
+ }))
67052
+ );
67053
+ const file2 = opts.out ? resolve(opts.out) : join(dirname(root), `${manifest.id}-${manifest.version}.zip`);
67054
+ mkdirSync(dirname(file2), { recursive: true });
67055
+ writeFileSync(file2, bytes);
67056
+ return {
67057
+ file: file2,
67058
+ sha256: createHash("sha256").update(bytes).digest("hex"),
67059
+ size: bytes.length,
67060
+ id: manifest.id,
67061
+ version: manifest.version
67062
+ };
67063
+ }
67064
+ const PLUGIN_TESTING_SOURCE = `// 零依赖宿主桩,供 node --test 调用 main.mjs 的 activate。
67065
+ export async function mountMain(activate, options = {}) {
67066
+ const calls = [];
67067
+ const host = options.host ?? {};
67068
+ const tools = new Map();
67069
+ const commands = new Map();
67070
+ const events = new Map();
67071
+ const schedules = new Map();
67072
+ const methods = new Map();
67073
+ const exportsMap = new Map();
67074
+ const triggers = new Map();
67075
+
67076
+ const call = (api, args) => {
67077
+ calls.push({ api, args });
67078
+ const fn = host[api];
67079
+ if (typeof fn === 'function') return fn(...args);
67080
+ if (api === 'config.get') return options.config ?? {};
67081
+ return undefined;
67082
+ };
67083
+
67084
+ const register = (map, key, handler) => {
67085
+ map.set(key, handler);
67086
+ return () => {
67087
+ if (map.get(key) === handler) map.delete(key);
67088
+ };
67089
+ };
67090
+
67091
+ const enso = {
67092
+ pluginId: options.pluginId ?? 'test.plugin',
67093
+ dataDir: options.dataDir ?? '.',
67094
+ tools: { register: (name, handler) => register(tools, name, handler) },
67095
+ commands: { register: (id, handler) => register(commands, id, handler) },
67096
+ events: { on: (event, handler) => register(events, event, handler) },
67097
+ schedules: { register: (id, handler) => register(schedules, id, handler) },
67098
+ renderer: { handle: (name, handler) => register(methods, name, handler) },
67099
+ exports: { handle: (name, handler) => register(exportsMap, name, handler) },
67100
+ triggers: { register: (symbol, handler) => register(triggers, symbol, handler) },
67101
+ ui: {
67102
+ notify: (...args) => call('ui.notify', args),
67103
+ view: {
67104
+ emit: (...args) => call('ui.view.emit', args),
67105
+ open: (...args) => call('ui.view.open', args),
67106
+ },
67107
+ status: { update: (...args) => call('ui.status.update', args) },
67108
+ clipboard: { writeText: (...args) => call('ui.clipboard.writeText', args) },
67109
+ openExternal: (...args) => call('ui.openExternal', args),
67110
+ },
67111
+ fs: {
67112
+ readText: (...args) => call('fs.readText', args),
67113
+ writeText: (...args) => call('fs.writeText', args),
67114
+ },
67115
+ net: { fetch: (...args) => call('net.fetch', args) },
67116
+ config: { get: (...args) => call('config.get', args) },
67117
+ artifacts: { write: (...args) => call('artifacts.write', args) },
67118
+ session: {
67119
+ inject: (...args) => call('session.inject', args),
67120
+ abort: (...args) => call('session.abort', args),
67121
+ list: (...args) => call('session.list', args),
67122
+ status: (...args) => call('session.status', args),
67123
+ focus: (...args) => call('session.focus', args),
67124
+ create: (...args) => call('session.create', args),
67125
+ },
67126
+ composer: {
67127
+ readDraft: (...args) => call('composer.readDraft', args),
67128
+ insertText: (...args) => call('composer.insertText', args),
67129
+ replaceDraft: (...args) => call('composer.replaceDraft', args),
67130
+ },
67131
+ mcp: {
67132
+ tools: (...args) => call('mcp.tools', args),
67133
+ call: (...args) => call('mcp.call', args),
67134
+ },
67135
+ plugins: { call: (...args) => call('plugins.call', args) },
67136
+ host: { capabilities: (...args) => call('host.capabilities', args) },
67137
+ };
67138
+
67139
+ await activate(enso);
67140
+
67141
+ const ctxOr = (ctx) => ctx ?? { sessionId: 'test-session', progress: async () => {} };
67142
+ const invoke = async (map, kind, key, args) => {
67143
+ const handler = map.get(key);
67144
+ if (typeof handler !== 'function') throw new Error('未注册: ' + kind + ' ' + key);
67145
+ return await handler(...args);
67146
+ };
67147
+
67148
+ return {
67149
+ enso,
67150
+ calls,
67151
+ tool: (name, args, ctx) => invoke(tools, 'tool', name, [args, ctxOr(ctx)]),
67152
+ command: (id, ctx) => invoke(commands, 'command', id, [ctxOr(ctx)]),
67153
+ fire: (event, data, ctx) => invoke(events, 'event', event, [data, ctxOr(ctx)]),
67154
+ schedule: (id) => invoke(schedules, 'schedule', id, [ctxOr()]),
67155
+ method: (name, args, ctx) => invoke(methods, 'method', name, [args, ctxOr(ctx)]),
67156
+ };
67157
+ }
67158
+ `;
65958
67159
  const PLUGIN_USAGE = `用法: enso-server plugin <action>
65959
67160
 
65960
67161
  list 已安装插件与状态
@@ -65963,6 +67164,7 @@ const PLUGIN_USAGE = `用法: enso-server plugin <action>
65963
67164
  enable <id> / disable <id> 启用 / 停用
65964
67165
  approve <id> / reject <id> 更新扩大了授权时:同意新版本 / 保留旧版本
65965
67166
  reload <id> [--yes] 从上次安装的来源(目录、zip 或链接)重新安装;开发时改完代码用它更新
67167
+ dev <id> / dev-off <id> 开发模式:从目录安装的插件改动后自动重装(授权扩大时停下,需要 reload 同意)
65966
67168
  uninstall <id> 卸载并删除插件数据
65967
67169
  inject-anywhere <id> 允许插件向任意运行中的会话发消息(默认只能发到发起调用的会话)
65968
67170
  inject-current <id> 恢复为只能发到发起调用的会话
@@ -65972,7 +67174,9 @@ const PLUGIN_USAGE = `用法: enso-server plugin <action>
65972
67174
  config <id> key=value ... 设置;key= 留空则在终端里输入(不进 shell 历史)
65973
67175
  [--unset key] 清除某项
65974
67176
  validate <目录> 校验 enso-plugin.json,并确认 main / renderer 入口存在
65975
- init <目录> [--id <id>] 生成最小插件(清单、main.mjs、ui.js、类型引用)`;
67177
+ init <目录> [--id <id>] 生成最小插件(清单、main.mjs、ui.js、类型引用)
67178
+ pack <目录> [--out <zip>] 校验后打成确定性 zip(排除隐藏文件、node_modules、test/),输出 sha256
67179
+ testing <目录> 写入 enso-testing.mjs 与 test/main.test.mjs,用 node --test 测 main.mjs`;
65976
67180
  const list = (items) => items.length ? items.join(", ") : "无";
65977
67181
  function formatInstallPreview(p) {
65978
67182
  const lines = [
@@ -66128,6 +67332,17 @@ async function runPluginCommand(args, deps) {
66128
67332
  deps.log("完成");
66129
67333
  return;
66130
67334
  }
67335
+ if ((action === "dev" || action === "dev-off") && target) {
67336
+ ensureOk(
67337
+ await deps.call({
67338
+ cmd: "plugin",
67339
+ action: action === "dev" ? "dev-on" : "dev-off",
67340
+ id: target
67341
+ })
67342
+ );
67343
+ deps.log(action === "dev" ? "开发模式已开,目录改动后自动重装" : "开发模式已关");
67344
+ return;
67345
+ }
66131
67346
  if (action === "validate") {
66132
67347
  if (!target || flags.length > 0) throw new Error(PLUGIN_USAGE);
66133
67348
  runValidate(target, deps);
@@ -66138,8 +67353,46 @@ async function runPluginCommand(args, deps) {
66138
67353
  runInit(target, flags, deps);
66139
67354
  return;
66140
67355
  }
67356
+ if (action === "pack") {
67357
+ if (!target) throw new Error(PLUGIN_USAGE);
67358
+ const out = flags[0] === "--out" && flags[1] && flags.length === 2 ? flags[1] : void 0;
67359
+ if (flags.length > 0 && !out) throw new Error(PLUGIN_USAGE);
67360
+ const packed = packPlugin(pluginDir(target, deps.cwd), {
67361
+ hostVersion: version$1,
67362
+ ...out ? { out: resolve(deps.cwd, out) } : {}
67363
+ });
67364
+ deps.log(`${packed.id} ${packed.version} → ${packed.file}`);
67365
+ deps.log(` 大小 ${packed.size} 字节,sha256 ${packed.sha256}`);
67366
+ return;
67367
+ }
67368
+ if (action === "testing") {
67369
+ if (!target || flags.length > 0) throw new Error(PLUGIN_USAGE);
67370
+ runTesting(target, deps);
67371
+ return;
67372
+ }
66141
67373
  throw new Error(PLUGIN_USAGE);
66142
67374
  }
67375
+ const TEST_SAMPLE = `import assert from 'node:assert/strict';
67376
+ import { test } from 'node:test';
67377
+ import { mountMain } from '../enso-testing.mjs';
67378
+ import { activate } from '../main.mjs';
67379
+
67380
+ test('main.mjs 能挂载', async () => {
67381
+ const plugin = await mountMain(activate);
67382
+ assert.ok(plugin.enso);
67383
+ });
67384
+ `;
67385
+ function runTesting(target, deps) {
67386
+ const dir = pluginDir(target, deps.cwd);
67387
+ if (!existsSync(join(dir, "enso-plugin.json"))) throw new Error("找不到 enso-plugin.json");
67388
+ writeFileSync(join(dir, "enso-testing.mjs"), PLUGIN_TESTING_SOURCE);
67389
+ const sample = join(dir, "test", "main.test.mjs");
67390
+ if (!existsSync(sample)) {
67391
+ mkdirSync(dirname(sample), { recursive: true });
67392
+ writeFileSync(sample, TEST_SAMPLE);
67393
+ }
67394
+ deps.log(`已写入 enso-testing.mjs,运行:cd ${dir} && node --test`);
67395
+ }
66143
67396
  const SCAFFOLD_FILES = ["enso-plugin.json", "main.mjs", "ui.js", "jsconfig.json"];
66144
67397
  function pluginDir(target, cwd) {
66145
67398
  return resolve(cwd, target);
@@ -66746,6 +67999,7 @@ const USAGE = `EnsoCode Server — 无界面宿主,手机 / 浏览器配对后
66746
67999
  service install [web 参数] 注册 systemd 服务(开机自启、崩溃拉起);web 参数写入配置文件
66747
68000
  service uninstall 移除 systemd 服务
66748
68001
  logs 跟随 systemd 服务日志
68002
+ run [选项] 无界面跑一轮真实会话(enso-server run --help)
66749
68003
 
66750
68004
  内置 web(默认关闭;开启后手机直接访问本机,不经公共中继):
66751
68005
  --web 开启
@@ -66858,7 +68112,7 @@ function systemctl(user, ...args) {
66858
68112
  const result = spawnSync("systemctl", user ? ["--user", ...args] : args, { stdio: "inherit" });
66859
68113
  if (result.status !== 0) fail(`systemctl ${args.join(" ")} 失败`);
66860
68114
  }
66861
- async function service(action, flags, dataDir, socketPath2) {
68115
+ async function service(action, flags, dataDir2, socketPath2) {
66862
68116
  if (action !== "install" && action !== "uninstall") fail(USAGE);
66863
68117
  const parsed = parseWebConfig(flags, process.env);
66864
68118
  if (!parsed.ok) fail(`${parsed.error}
@@ -66870,12 +68124,12 @@ ${USAGE}`);
66870
68124
  if (existsSync(unitFile)) systemctl(!root, "disable", "--now", "enso-server");
66871
68125
  rmSync(unitFile, { force: true });
66872
68126
  systemctl(!root, "daemon-reload");
66873
- console.log(`已移除 enso-server 服务(数据保留在 ${dataDir})`);
68127
+ console.log(`已移除 enso-server 服务(数据保留在 ${dataDir2})`);
66874
68128
  return;
66875
68129
  }
66876
68130
  if (!existsSync(unitFile) && await isRunning(socketPath2))
66877
68131
  fail("enso-server 正在前台运行,先停掉它(Ctrl+C)再注册服务");
66878
- const env = { ENSO_DATA_DIR: dataDir, PATH: process.env.PATH ?? "" };
68132
+ const env = { ENSO_DATA_DIR: dataDir2, PATH: process.env.PATH ?? "" };
66879
68133
  const patch = {};
66880
68134
  const relayUrl = process.env.ENSO_RELAY_URL?.trim();
66881
68135
  const npmRegistry = process.env.ENSO_NPM_REGISTRY?.trim();
@@ -66886,9 +68140,9 @@ ${USAGE}`);
66886
68140
  patch.web = { enabled: true, host, port, ...publicUrl !== localUrl ? { publicUrl } : {} };
66887
68141
  }
66888
68142
  if (Object.keys(patch).length) {
66889
- const current2 = readServerConfig(dataDir);
68143
+ const current2 = readServerConfig(dataDir2);
66890
68144
  if (!current2.ok) fail(current2.error);
66891
- console.log(`设置已写入 ${writeServerConfig(dataDir, { ...current2.config, ...patch })}`);
68145
+ console.log(`设置已写入 ${writeServerConfig(dataDir2, { ...current2.config, ...patch })}`);
66892
68146
  }
66893
68147
  mkdirSync(unitDir, { recursive: true });
66894
68148
  writeFileSync(
@@ -66929,7 +68183,7 @@ function terminalPrompt() {
66929
68183
  };
66930
68184
  }
66931
68185
  const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
66932
- function hostSystem(dataDir, socketPath2) {
68186
+ function hostSystem(dataDir2, socketPath2) {
66933
68187
  const { root, unitFile } = unitLocation();
66934
68188
  const timeout = () => AbortSignal.timeout(5e3);
66935
68189
  return {
@@ -66979,7 +68233,7 @@ function hostSystem(dataDir, socketPath2) {
66979
68233
  }
66980
68234
  return CONFIG_ENV_KEYS.filter((key) => unit.includes(`Environment="${key}=`));
66981
68235
  },
66982
- installService: () => service("install", [], dataDir, socketPath2),
68236
+ installService: () => service("install", [], dataDir2, socketPath2),
66983
68237
  restartService: () => spawnSync(
66984
68238
  "systemctl",
66985
68239
  root ? ["restart", "enso-server"] : ["--user", "restart", "enso-server"],
@@ -67061,7 +68315,9 @@ const PLUGIN_ID_ACTIONS = [
67061
68315
  "reject",
67062
68316
  "uninstall",
67063
68317
  "inject-anywhere",
67064
- "inject-current"
68318
+ "inject-current",
68319
+ "dev-on",
68320
+ "dev-off"
67065
68321
  ];
67066
68322
  const PLUGIN_TOKEN_ACTIONS = ["commit", "discard"];
67067
68323
  function parsePluginCommand(input) {
@@ -67125,6 +68381,1154 @@ function parseControlCommand(line2) {
67125
68381
  if (cmd === "plugin") return parsePluginCommand(parsed);
67126
68382
  return { error: "unknown command" };
67127
68383
  }
68384
+ const OUTPUT_FORMATS = ["text", "json", "stream-json"];
68385
+ const RUN_NETWORK_TOOLS = ["web", "browser", "image_generation"];
68386
+ const TOOL_ALIASES = {
68387
+ bash: "bash",
68388
+ shell: "bash",
68389
+ powershell: "powershell",
68390
+ read: "read",
68391
+ write: "write",
68392
+ edit: "edit",
68393
+ grep: "grep",
68394
+ find: "find",
68395
+ ls: "ls",
68396
+ web: "web",
68397
+ web_search: "web",
68398
+ web_fetch: "web",
68399
+ browser: "browser",
68400
+ imagegen: "image_generation",
68401
+ image_generation: "image_generation",
68402
+ ask_user: "ask_user",
68403
+ askuser: "ask_user",
68404
+ goal: "goal",
68405
+ goal_complete: "goal",
68406
+ goal_blocked: "goal",
68407
+ goal_wait: "goal",
68408
+ memory: "memory",
68409
+ computer: "computer",
68410
+ subagent: "subagent",
68411
+ workflow: "workflow",
68412
+ todo: "todo",
68413
+ plan: "plan",
68414
+ background_tasks: "background_tasks",
68415
+ isolated_sandbox: "isolated_sandbox",
68416
+ workspace_write: "workspace_write"
68417
+ };
68418
+ const RUN_USAGE = `enso-server run — 无界面跑一轮真实 agent 会话
68419
+
68420
+ 用法:
68421
+ enso-server run --prompt <文本|@文件|-> [选项]
68422
+
68423
+ 选项:
68424
+ --cwd <dir> 工作目录,默认当前目录
68425
+ --mode <mode> supervised | auto-edits | full | assistant(默认 full)
68426
+ --target <text> | --goal <text>
68427
+ 以 /goal 自动续跑;可与 --prompt 同时给出
68428
+ --auto-turns <n> goal 自动轮数上限,默认 25
68429
+ --provider <id> 供应商 id;新建时默认 enso-run
68430
+ --model <id> 模型 id
68431
+ --api <kind> openai-completions | openai-responses | anthropic-messages
68432
+ 以及供应商层支持的其它协议
68433
+ --api-key <key> API key(也可用环境变量,见下)
68434
+ --base-url <url> 模型端点,例如 https://host/v1
68435
+ --reasoning-effort <level> off | minimal | low | medium | high | xhigh | max
68436
+ --timeout-ms <n> 整次运行的墙钟上限;超时退出 124
68437
+ --output-format <format> text | json | stream-json(默认 text)
68438
+ --resume <session id> 恢复已有会话
68439
+ --continue 恢复当前目录最近一次 run 会话
68440
+ --disallowed-tools <list> 逗号或空白分隔的工具名或内置组 id
68441
+ --allow-tools <list> 重新允许 run 默认关掉的 web、browser、image_generation
68442
+ --usage-log <path> 用量 JSONL(每次模型调用一行,外加一行 summary)
68443
+ --data-dir <dir> 数据目录,覆盖 ENSO_DATA_DIR
68444
+
68445
+ 环境变量(命令行优先):
68446
+ ENSO_DATA_DIR ENSO_PROVIDER_ID ENSO_MODEL ENSO_API_KEY ENSO_BASE_URL ENSO_API
68447
+ ENSO_REASONING_EFFORT ENSO_TIMEOUT_MS
68448
+ ENSO_API_KEY 和 ENSO_BASE_URL 都没设置、也没指定供应商但给了模型时,整组回退
68449
+ OPENAI_API_KEY + OPENAI_BASE_URL,其次 ANTHROPIC_API_KEY + ANTHROPIC_BASE_URL
68450
+ 未设置 ENSO_MODEL 时回退 OPENAI_MODEL;没给地址时用协议默认端点
68451
+
68452
+ 已有 $ENSO_DATA_DIR/settings.json 里的 providers 会用;标志或环境变量可以覆盖或新建一条。
68453
+ run 默认无人值守:会挡住的审批按档位当场拒绝,不会等待。web / browser / image_generation
68454
+ 默认关闭,避免除模型端点以外的出站请求。
68455
+
68456
+ 退出码: 0 成功;1 运行失败;2 参数或配置错误;3 goal 阻塞或等待;
68457
+ 4 自动轮数用尽或连续无进展;124 超时;130 SIGINT/SIGTERM。
68458
+ 诊断只写 stderr。`;
68459
+ const FLAG_VALUE = /* @__PURE__ */ new Set([
68460
+ "--prompt",
68461
+ "-p",
68462
+ "--cwd",
68463
+ "--mode",
68464
+ "--target",
68465
+ "--goal",
68466
+ "--auto-turns",
68467
+ "--provider",
68468
+ "--model",
68469
+ "--api",
68470
+ "--api-key",
68471
+ "--base-url",
68472
+ "--reasoning-effort",
68473
+ "--timeout-ms",
68474
+ "--output-format",
68475
+ "--resume",
68476
+ "--disallowed-tools",
68477
+ "--allow-tools",
68478
+ "--usage-log",
68479
+ "--data-dir"
68480
+ ]);
68481
+ function parseToolList(value) {
68482
+ const out = [];
68483
+ for (const match of value.matchAll(/[A-Za-z0-9_.:-]+(?:\([^)]*\))?/g)) {
68484
+ const head = match[0].split("(")[0] || match[0];
68485
+ const key = head.toLowerCase();
68486
+ const canonical2 = TOOL_ALIASES[key] ?? key;
68487
+ if (!out.includes(canonical2)) out.push(canonical2);
68488
+ }
68489
+ return out;
68490
+ }
68491
+ function disabledToolsForRun(disallowed, allow) {
68492
+ const allowed = new Set(allow);
68493
+ const denied = /* @__PURE__ */ new Set();
68494
+ for (const id of RUN_NETWORK_TOOLS) if (!allowed.has(id)) denied.add(id);
68495
+ for (const id of allow) if (!disallowed.includes(id)) denied.delete(id);
68496
+ for (const id of disallowed) denied.add(id);
68497
+ return [...denied];
68498
+ }
68499
+ function envValue(env, ...keys) {
68500
+ for (const key of keys) {
68501
+ const value = env[key]?.trim();
68502
+ if (value) return value;
68503
+ }
68504
+ return void 0;
68505
+ }
68506
+ function vendorEndpoint(env) {
68507
+ const openai = envValue(env, "OPENAI_API_KEY");
68508
+ if (openai) {
68509
+ const baseUrl = envValue(env, "OPENAI_BASE_URL");
68510
+ return { apiKey: openai, ...baseUrl ? { baseUrl } : {} };
68511
+ }
68512
+ const anthropic = envValue(env, "ANTHROPIC_API_KEY");
68513
+ if (anthropic) {
68514
+ const baseUrl = envValue(env, "ANTHROPIC_BASE_URL");
68515
+ return { apiKey: anthropic, api: "anthropic-messages", ...baseUrl ? { baseUrl } : {} };
68516
+ }
68517
+ return void 0;
68518
+ }
68519
+ function parsePositiveInt(value, name, max) {
68520
+ if (!/^[0-9]+$/.test(value)) return `${name} 必须是正整数`;
68521
+ const parsed = Number(value);
68522
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > max) {
68523
+ return `${name} 必须是 1 到 ${max} 的整数`;
68524
+ }
68525
+ return parsed;
68526
+ }
68527
+ function parseRunArgs(argv, env = process.env, defaultCwd = process.cwd()) {
68528
+ const values = /* @__PURE__ */ new Map();
68529
+ let continueSession = false;
68530
+ let help = false;
68531
+ for (let i = 0; i < argv.length; i++) {
68532
+ const token = argv[i] ?? "";
68533
+ if (token === "--help" || token === "-h") {
68534
+ help = true;
68535
+ continue;
68536
+ }
68537
+ if (token === "--continue") {
68538
+ continueSession = true;
68539
+ continue;
68540
+ }
68541
+ const name = token.includes("=") ? token.slice(0, token.indexOf("=")) : token;
68542
+ if (!name.startsWith("--") && name !== "-p")
68543
+ return { ok: false, error: `无法识别的参数 ${token}` };
68544
+ if (!FLAG_VALUE.has(name)) return { ok: false, error: `无法识别的参数 ${name}` };
68545
+ const inline = token.includes("=") ? token.slice(token.indexOf("=") + 1) : void 0;
68546
+ let value = inline;
68547
+ if (value === void 0) {
68548
+ value = argv[i + 1];
68549
+ if (value === void 0 || value.startsWith("--")) {
68550
+ return { ok: false, error: `${name} 需要一个值` };
68551
+ }
68552
+ i++;
68553
+ }
68554
+ if (values.has(name)) return { ok: false, error: `${name} 只能出现一次` };
68555
+ values.set(name, value);
68556
+ }
68557
+ if (help && values.size === 0 && !continueSession) return { ok: false, error: "", help: true };
68558
+ const prompt = values.get("--prompt") ?? values.get("-p");
68559
+ const goalFlag = values.get("--goal");
68560
+ const targetFlag = values.get("--target");
68561
+ if (goalFlag !== void 0 && targetFlag !== void 0 && goalFlag !== targetFlag) {
68562
+ return { ok: false, error: "--goal 和 --target 不一致" };
68563
+ }
68564
+ const goal = goalFlag ?? targetFlag;
68565
+ if (!prompt && !goal) return { ok: false, error: "需要 --prompt,或 --goal / --target" };
68566
+ if (prompt !== void 0 && prompt !== "-" && !prompt.startsWith("@") && !prompt.trim()) {
68567
+ return { ok: false, error: "--prompt 不能为空" };
68568
+ }
68569
+ if (goal !== void 0 && !goal.trim()) return { ok: false, error: "--goal 不能为空" };
68570
+ const resume = values.get("--resume")?.trim();
68571
+ if (continueSession && resume) return { ok: false, error: "--resume 和 --continue 不能同时使用" };
68572
+ if (resume === "") return { ok: false, error: "--resume 需要会话 id" };
68573
+ const modeText = values.get("--mode") ?? "full";
68574
+ if (!APPROVAL_MODES$1.includes(modeText)) {
68575
+ return { ok: false, error: `--mode 必须是 ${APPROVAL_MODES$1.join(" | ")}` };
68576
+ }
68577
+ const formatText = values.get("--output-format") ?? "text";
68578
+ if (!OUTPUT_FORMATS.includes(formatText)) {
68579
+ return { ok: false, error: "--output-format 必须是 text | json | stream-json" };
68580
+ }
68581
+ const apiText = values.get("--api") ?? envValue(env, "ENSO_API");
68582
+ if (apiText && !MODEL_API_KINDS.includes(apiText)) {
68583
+ return { ok: false, error: `--api 必须是 ${MODEL_API_KINDS.join(" | ")}` };
68584
+ }
68585
+ const reasoning = values.get("--reasoning-effort") ?? envValue(env, "ENSO_REASONING_EFFORT");
68586
+ if (reasoning && reasoning !== "off" && reasoning !== "none" && !THINKING_LEVELS.includes(reasoning)) {
68587
+ return {
68588
+ ok: false,
68589
+ error: "--reasoning-effort 必须是 off、none 或 minimal | low | medium | high | xhigh | max"
68590
+ };
68591
+ }
68592
+ let autoTurns = 25;
68593
+ const turnsText = values.get("--auto-turns");
68594
+ if (turnsText !== void 0) {
68595
+ const parsed = parsePositiveInt(turnsText, "--auto-turns", 1e4);
68596
+ if (typeof parsed === "string") return { ok: false, error: parsed };
68597
+ autoTurns = parsed;
68598
+ }
68599
+ let timeoutMs;
68600
+ const timeoutText = values.get("--timeout-ms") ?? envValue(env, "ENSO_TIMEOUT_MS");
68601
+ if (timeoutText !== void 0) {
68602
+ const parsed = parsePositiveInt(timeoutText, "--timeout-ms", 864e5);
68603
+ if (typeof parsed === "string") return { ok: false, error: parsed };
68604
+ timeoutMs = parsed;
68605
+ }
68606
+ const providerId = values.get("--provider")?.trim() || envValue(env, "ENSO_PROVIDER_ID");
68607
+ const modelId = values.get("--model")?.trim() || envValue(env, "ENSO_MODEL", "OPENAI_MODEL");
68608
+ let apiKey = values.get("--api-key") || envValue(env, "ENSO_API_KEY");
68609
+ let baseUrl = values.get("--base-url")?.trim() || envValue(env, "ENSO_BASE_URL");
68610
+ let api = apiText;
68611
+ const vendor = !apiKey && !baseUrl && !providerId && modelId ? vendorEndpoint(env) : void 0;
68612
+ if (vendor) {
68613
+ apiKey = vendor.apiKey;
68614
+ baseUrl = vendor.baseUrl;
68615
+ api ??= vendor.api;
68616
+ }
68617
+ return {
68618
+ ok: true,
68619
+ args: {
68620
+ ...prompt !== void 0 ? { prompt } : {},
68621
+ cwd: values.get("--cwd")?.trim() || defaultCwd,
68622
+ mode: modeText,
68623
+ ...goal ? { goal: goal.trim() } : {},
68624
+ autoTurns,
68625
+ providerId,
68626
+ modelId,
68627
+ apiKey,
68628
+ baseUrl,
68629
+ ...api ? { api } : {},
68630
+ ...reasoning ? { reasoningEffort: reasoning } : {},
68631
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
68632
+ outputFormat: formatText,
68633
+ ...resume ? { resume } : {},
68634
+ continue: continueSession,
68635
+ disallowedTools: parseToolList(values.get("--disallowed-tools") ?? ""),
68636
+ allowTools: parseToolList(values.get("--allow-tools") ?? ""),
68637
+ usageLog: values.get("--usage-log")?.trim() || void 0,
68638
+ dataDir: values.get("--data-dir")?.trim() || void 0
68639
+ }
68640
+ };
68641
+ }
68642
+ function normalizeAssistantOutput(text2) {
68643
+ return text2.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
68644
+ }
68645
+ function initialPrompt(prompt, goal) {
68646
+ const objective = goal?.trim();
68647
+ const text2 = prompt.trim();
68648
+ if (objective && text2 && text2 !== objective) return `${text2}
68649
+
68650
+ ${goalKickoffText(objective)}`;
68651
+ if (objective) return goalKickoffText(objective);
68652
+ return text2;
68653
+ }
68654
+ function nextGoalStep(input) {
68655
+ const goal = input.runtime.goal;
68656
+ if (goal?.status !== "active") {
68657
+ return {
68658
+ runtime: input.runtime,
68659
+ lastOutput: input.lastOutput,
68660
+ noProgressRuns: input.noProgressRuns
68661
+ };
68662
+ }
68663
+ const output = normalizeAssistantOutput(input.assistantText);
68664
+ const stuck = output === "" || output === input.lastOutput;
68665
+ const noProgressRuns = stuck ? input.noProgressRuns + 1 : 0;
68666
+ if (noProgressRuns >= 3) {
68667
+ return {
68668
+ runtime: {
68669
+ ...input.runtime,
68670
+ goal: { ...goal, status: "paused", note: "no progress in 3 consecutive runs" }
68671
+ },
68672
+ lastOutput: output,
68673
+ noProgressRuns
68674
+ };
68675
+ }
68676
+ const idle = onHeadlessIdle(
68677
+ { ...input.runtime, status: "idle", started: true, pendingApprovals: 0, pendingAsks: 0 },
68678
+ { autoTurnLimit: input.autoTurnLimit }
68679
+ );
68680
+ return {
68681
+ runtime: idle.runtime,
68682
+ ...idle.deliver ? { deliver: idle.deliver } : {},
68683
+ lastOutput: output,
68684
+ noProgressRuns
68685
+ };
68686
+ }
68687
+ function priceUsage(model, usage, table) {
68688
+ return costOf(
68689
+ {
68690
+ model,
68691
+ input: usage.input,
68692
+ output: usage.output,
68693
+ cacheRead: usage.cacheRead,
68694
+ cacheWrite: usage.cacheWrite
68695
+ },
68696
+ table
68697
+ );
68698
+ }
68699
+ function usageCallRecord(call2) {
68700
+ return { type: "call", ...call2 };
68701
+ }
68702
+ function usageSummaryRecord(calls, timestamp) {
68703
+ let cost = calls.length > 0 ? 0 : null;
68704
+ const totals = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
68705
+ for (const call2 of calls) {
68706
+ totals.inputTokens += call2.inputTokens;
68707
+ totals.outputTokens += call2.outputTokens;
68708
+ totals.cacheReadTokens += call2.cacheReadTokens;
68709
+ totals.cacheWriteTokens += call2.cacheWriteTokens;
68710
+ cost = cost === null || call2.costUsd === null ? null : cost + call2.costUsd;
68711
+ }
68712
+ return { type: "summary", timestamp, ...totals, costUsd: cost, calls: calls.length };
68713
+ }
68714
+ class UsageLogWriter {
68715
+ file;
68716
+ constructor(file2) {
68717
+ this.file = file2;
68718
+ if (!file2) return;
68719
+ mkdirSync(path.dirname(file2), { recursive: true });
68720
+ writeFileSync(file2, "");
68721
+ }
68722
+ write(record2) {
68723
+ if (!this.file) return;
68724
+ appendFileSync(this.file, `${JSON.stringify(record2)}
68725
+ `);
68726
+ }
68727
+ }
68728
+ function textOf(message2) {
68729
+ return (message2.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text ?? "").join("");
68730
+ }
68731
+ function toolResultText(message2) {
68732
+ return (message2.content ?? []).map((part) => typeof part.text === "string" ? part.text : "").join("");
68733
+ }
68734
+ class RunTranscript {
68735
+ constructor(provider2, pricing, now = Date.now) {
68736
+ this.provider = provider2;
68737
+ this.pricing = pricing;
68738
+ this.now = now;
68739
+ }
68740
+ provider;
68741
+ pricing;
68742
+ now;
68743
+ texts = /* @__PURE__ */ new Map();
68744
+ seenTools = /* @__PURE__ */ new Map();
68745
+ logged = /* @__PURE__ */ new Set();
68746
+ pending = /* @__PURE__ */ new Map();
68747
+ finalText = "";
68748
+ calls = [];
68749
+ ingest(key, message2, parent) {
68750
+ const records = [];
68751
+ const id = `${key}@${message2.timestamp ?? ""}`;
68752
+ const cut2 = key.lastIndexOf(":");
68753
+ const scope = cut2 >= 0 ? key.slice(0, cut2) : "";
68754
+ const index = Number(key.slice(cut2 + 1));
68755
+ for (const [pendingKey, pending2] of this.pending) {
68756
+ if (pending2.scope !== scope) continue;
68757
+ const ended = pendingKey === key ? pending2.id !== id : pending2.index < index;
68758
+ if (!ended) continue;
68759
+ this.pending.delete(pendingKey);
68760
+ if (!this.logged.has(pending2.id)) {
68761
+ records.push(this.log(pending2.id, pending2.model, pending2.usage));
68762
+ }
68763
+ }
68764
+ if (message2.role === "assistant") {
68765
+ const next = textOf(message2);
68766
+ const prev = this.texts.get(key) ?? "";
68767
+ if (next && next !== prev) {
68768
+ const delta = next.startsWith(prev) ? next.slice(prev.length) : next;
68769
+ if (delta) records.push({ type: "assistant.delta", text: delta });
68770
+ this.texts.set(key, next);
68771
+ if (parent) this.finalText = next;
68772
+ }
68773
+ for (const part of message2.content ?? []) {
68774
+ if (part.type !== "toolCall" || typeof part.id !== "string" || !part.name) continue;
68775
+ const signature2 = JSON.stringify(part.arguments ?? null);
68776
+ if (this.seenTools.get(part.id) === signature2) continue;
68777
+ this.seenTools.set(part.id, signature2);
68778
+ records.push({
68779
+ type: "tool.call",
68780
+ id: part.id,
68781
+ name: part.name,
68782
+ arguments: part.arguments ?? {}
68783
+ });
68784
+ }
68785
+ if (message2.usage && !this.logged.has(id)) {
68786
+ this.pending.set(key, {
68787
+ id,
68788
+ scope,
68789
+ index,
68790
+ model: message2.model || "unknown",
68791
+ usage: message2.usage
68792
+ });
68793
+ }
68794
+ } else if (message2.role === "toolResult") {
68795
+ records.push({
68796
+ type: "tool.result",
68797
+ ...message2.toolCallId ? { id: message2.toolCallId } : {},
68798
+ ...message2.toolName ? { name: message2.toolName } : {},
68799
+ text: toolResultText(message2),
68800
+ ...message2.isError ? { isError: true } : {}
68801
+ });
68802
+ }
68803
+ return records;
68804
+ }
68805
+ /** 轮次结束时补记最后一次调用的用量。 */
68806
+ flushTurn() {
68807
+ const records = [];
68808
+ for (const pending2 of this.pending.values()) {
68809
+ if (!this.logged.has(pending2.id)) {
68810
+ records.push(this.log(pending2.id, pending2.model, pending2.usage));
68811
+ }
68812
+ }
68813
+ this.pending.clear();
68814
+ return records;
68815
+ }
68816
+ usage() {
68817
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: 0 };
68818
+ for (const call2 of this.calls) {
68819
+ totals.input += call2.inputTokens;
68820
+ totals.output += call2.outputTokens;
68821
+ totals.cacheRead += call2.cacheReadTokens;
68822
+ totals.cacheWrite += call2.cacheWriteTokens;
68823
+ totals.costUsd = totals.costUsd === null || call2.costUsd === null ? null : totals.costUsd + call2.costUsd;
68824
+ }
68825
+ return this.calls.length > 0 ? totals : { ...totals, costUsd: null };
68826
+ }
68827
+ log(id, model, usage) {
68828
+ this.logged.add(id);
68829
+ const costUsd = priceUsage(model, usage, this.pricing);
68830
+ const call2 = {
68831
+ timestamp: new Date(this.now()).toISOString(),
68832
+ provider: this.provider,
68833
+ model,
68834
+ inputTokens: usage.input,
68835
+ outputTokens: usage.output,
68836
+ cacheReadTokens: usage.cacheRead,
68837
+ cacheWriteTokens: usage.cacheWrite,
68838
+ costUsd
68839
+ };
68840
+ this.calls.push(call2);
68841
+ return {
68842
+ type: "usage",
68843
+ provider: call2.provider,
68844
+ model: call2.model,
68845
+ inputTokens: call2.inputTokens,
68846
+ outputTokens: call2.outputTokens,
68847
+ cacheReadTokens: call2.cacheReadTokens,
68848
+ cacheWriteTokens: call2.cacheWriteTokens,
68849
+ costUsd
68850
+ };
68851
+ }
68852
+ }
68853
+ function renderResult(result, format) {
68854
+ if (format === "text") return result.finalMessage ? `${result.finalMessage}
68855
+ ` : "";
68856
+ return `${JSON.stringify(result)}
68857
+ `;
68858
+ }
68859
+ function isApi(value) {
68860
+ return MODEL_API_KINDS.includes(value);
68861
+ }
68862
+ function inferApi(baseUrl, explicit) {
68863
+ if (explicit) return explicit;
68864
+ if (baseUrl?.toLowerCase().includes("anthropic")) return "anthropic-messages";
68865
+ return "openai-completions";
68866
+ }
68867
+ function coerceProvider(value) {
68868
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
68869
+ const raw = value;
68870
+ if (typeof raw.id !== "string" || !raw.id) return null;
68871
+ if (typeof raw.api !== "string" || !isApi(raw.api)) return null;
68872
+ if (typeof raw.apiKey !== "string" || typeof raw.baseUrl !== "string") return null;
68873
+ if (!Array.isArray(raw.models)) return null;
68874
+ const name = typeof raw.name === "string" && raw.name ? raw.name : raw.id;
68875
+ const enabled2 = raw.enabled === void 0 ? true : raw.enabled === true;
68876
+ const models = raw.models.filter(
68877
+ (model) => Boolean(model) && typeof model === "object" && typeof model.id === "string" && model.id.length > 0
68878
+ );
68879
+ return {
68880
+ id: raw.id,
68881
+ name,
68882
+ api: raw.api,
68883
+ apiKey: raw.apiKey,
68884
+ baseUrl: raw.baseUrl,
68885
+ enabled: enabled2,
68886
+ models,
68887
+ ...typeof raw.importedFrom === "string" ? { importedFrom: raw.importedFrom } : {},
68888
+ ...typeof raw.catalogId === "string" ? { catalogId: raw.catalogId } : {},
68889
+ ...raw.headers ? { headers: raw.headers } : {},
68890
+ ...raw.oauthAccountKey ? { oauthAccountKey: raw.oauthAccountKey } : {},
68891
+ ...raw.oauthAccountPool ? { oauthAccountPool: raw.oauthAccountPool } : {}
68892
+ };
68893
+ }
68894
+ function enabledModelId(provider2, preferred) {
68895
+ if (preferred) {
68896
+ const match = provider2.models.find(
68897
+ (model) => model.id === preferred && model.enabled !== false
68898
+ );
68899
+ return match ? match.id : null;
68900
+ }
68901
+ return provider2.models.find((model) => model.enabled !== false)?.id ?? null;
68902
+ }
68903
+ function withModel(provider2, modelId) {
68904
+ if (provider2.models.some((model) => model.id === modelId)) return provider2;
68905
+ return { ...provider2, models: [...provider2.models, { id: modelId }] };
68906
+ }
68907
+ function resolveRunProvider(request2, providersRaw) {
68908
+ const rawList = Array.isArray(providersRaw) ? [...providersRaw] : [];
68909
+ const known = rawList.map((item) => coerceProvider(item));
68910
+ const endpoint = Boolean(request2.apiKey || request2.baseUrl || request2.api);
68911
+ if (endpoint) {
68912
+ if (!request2.modelId) return { ok: false, error: "新建供应商时需要 --model 或 ENSO_MODEL" };
68913
+ if (!request2.apiKey) return { ok: false, error: "新建供应商时需要 --api-key 或 ENSO_API_KEY" };
68914
+ const id = request2.providerId || "enso-run";
68915
+ const api = inferApi(request2.baseUrl, request2.api);
68916
+ const baseUrl = request2.baseUrl || DEFAULT_BASE_URLS[api];
68917
+ const index2 = known.findIndex((provider22) => provider22?.id === id);
68918
+ const previous = index2 >= 0 ? known[index2] : null;
68919
+ const base = previous ?? {
68920
+ id,
68921
+ name: id,
68922
+ api,
68923
+ apiKey: request2.apiKey,
68924
+ baseUrl,
68925
+ enabled: true,
68926
+ models: []
68927
+ };
68928
+ const next2 = withModel(
68929
+ {
68930
+ ...base,
68931
+ name: base.name || id,
68932
+ api,
68933
+ apiKey: request2.apiKey,
68934
+ baseUrl,
68935
+ enabled: true
68936
+ },
68937
+ request2.modelId
68938
+ );
68939
+ const providers22 = [...rawList];
68940
+ if (index2 >= 0) providers22[index2] = next2;
68941
+ else providers22.push(next2);
68942
+ return {
68943
+ ok: true,
68944
+ value: {
68945
+ providerId: id,
68946
+ modelId: request2.modelId,
68947
+ providers: providers22,
68948
+ changed: JSON.stringify(providers22) !== JSON.stringify(rawList)
68949
+ }
68950
+ };
68951
+ }
68952
+ const usable = known.filter((provider22) => provider22 !== null);
68953
+ const provider2 = (request2.providerId ? usable.find((item) => item.id === request2.providerId) : void 0) ?? (!request2.providerId ? usable.find((item) => item.enabled && enabledModelId(item)) : void 0);
68954
+ if (!provider2) {
68955
+ return {
68956
+ ok: false,
68957
+ error: request2.providerId ? `设置里没有供应商 ${request2.providerId}` : "没有可用供应商。用 --api-key、--base-url 和 --model 指定,或先写入 settings.json"
68958
+ };
68959
+ }
68960
+ if (!provider2.enabled) return { ok: false, error: `供应商 ${provider2.id} 已停用` };
68961
+ let modelId = enabledModelId(provider2, request2.modelId);
68962
+ let next = provider2;
68963
+ if (!modelId && request2.modelId) {
68964
+ next = withModel(provider2, request2.modelId);
68965
+ modelId = request2.modelId;
68966
+ }
68967
+ if (!modelId) return { ok: false, error: `供应商 ${provider2.id} 没有可用模型` };
68968
+ const reason = modelUsability({ providerId: provider2.id, modelId }, [next], {
68969
+ oauthCredentials: { status: "ready", authenticatedAccountKeys: /* @__PURE__ */ new Set() }
68970
+ });
68971
+ if (reason !== "usable") return { ok: false, error: `模型不可用: ${reason}` };
68972
+ const index = known.findIndex((item) => item?.id === provider2.id);
68973
+ const providers2 = [...rawList];
68974
+ if (index >= 0) providers2[index] = next;
68975
+ return {
68976
+ ok: true,
68977
+ value: {
68978
+ providerId: provider2.id,
68979
+ modelId,
68980
+ providers: providers2,
68981
+ changed: JSON.stringify(providers2) !== JSON.stringify(rawList)
68982
+ }
68983
+ };
68984
+ }
68985
+ function settingsProviders(settings) {
68986
+ if (!settings || typeof settings !== "object") return void 0;
68987
+ const store = settings["enso-settings"];
68988
+ if (!store || typeof store !== "object") return void 0;
68989
+ const state = store.state;
68990
+ if (!state || typeof state !== "object") return void 0;
68991
+ return state.providers;
68992
+ }
68993
+ function writeProviderSettings(file2, providers2) {
68994
+ let current2 = {};
68995
+ try {
68996
+ const parsed = JSON.parse(readFileSync(file2, "utf8"));
68997
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
68998
+ current2 = parsed;
68999
+ }
69000
+ } catch {
69001
+ current2 = {};
69002
+ }
69003
+ const store = current2["enso-settings"] && typeof current2["enso-settings"] === "object" ? current2["enso-settings"] : {};
69004
+ const state = store.state && typeof store.state === "object" ? store.state : {};
69005
+ const next = {
69006
+ ...current2,
69007
+ "enso-settings": { ...store, state: { ...state, providers: providers2 } }
69008
+ };
69009
+ mkdirSync(path.dirname(file2), { recursive: true });
69010
+ const temp = `${file2}.tmp`;
69011
+ writeFileSync(temp, `${JSON.stringify(next, null, 2)}
69012
+ `, { mode: 384 });
69013
+ renameSync(temp, file2);
69014
+ chmodSync(file2, 384);
69015
+ }
69016
+ function firstLine(file2) {
69017
+ const fd = openSync(file2, "r");
69018
+ try {
69019
+ const buf = Buffer.alloc(4096);
69020
+ const read = readSync(fd, buf, 0, buf.length, 0);
69021
+ return buf.subarray(0, read).toString("utf8").split("\n", 1)[0] ?? "";
69022
+ } finally {
69023
+ closeSync(fd);
69024
+ }
69025
+ }
69026
+ function readSessionHeader(file2) {
69027
+ try {
69028
+ const parsed = JSON.parse(firstLine(file2));
69029
+ if (!parsed || typeof parsed !== "object") return null;
69030
+ const entry = parsed;
69031
+ if (entry.type !== "session") return null;
69032
+ return {
69033
+ ...typeof entry.id === "string" && entry.id ? { id: entry.id } : {},
69034
+ ...typeof entry.cwd === "string" && entry.cwd ? { cwd: entry.cwd } : {}
69035
+ };
69036
+ } catch {
69037
+ return null;
69038
+ }
69039
+ }
69040
+ function listSessionFiles(sessionDir2) {
69041
+ if (!existsSync(sessionDir2)) return [];
69042
+ const found = [];
69043
+ const walk2 = (dir) => {
69044
+ for (const name of readdirSync(dir)) {
69045
+ const file2 = path.join(dir, name);
69046
+ let stat2;
69047
+ try {
69048
+ stat2 = statSync(file2);
69049
+ } catch {
69050
+ continue;
69051
+ }
69052
+ if (stat2.isDirectory()) {
69053
+ walk2(file2);
69054
+ continue;
69055
+ }
69056
+ if (!name.endsWith(".jsonl")) continue;
69057
+ const header = readSessionHeader(file2);
69058
+ if (!header?.id) continue;
69059
+ const resolved = path.resolve(file2);
69060
+ const root = path.resolve(sessionDir2);
69061
+ if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) continue;
69062
+ found.push({
69063
+ sessionId: header.id,
69064
+ sessionFile: resolved,
69065
+ ...header.cwd ? { cwd: header.cwd } : {},
69066
+ mtimeMs: stat2.mtimeMs
69067
+ });
69068
+ }
69069
+ };
69070
+ walk2(sessionDir2);
69071
+ return found;
69072
+ }
69073
+ function findSessionById(sessionDir2, sessionId) {
69074
+ return listSessionFiles(sessionDir2).find((session2) => session2.sessionId === sessionId) ?? null;
69075
+ }
69076
+ function findLatestSessionForCwd(sessionDir2, cwd) {
69077
+ const target = path.resolve(cwd);
69078
+ const matches = listSessionFiles(sessionDir2).filter(
69079
+ (session2) => session2.cwd && path.resolve(session2.cwd) === target
69080
+ );
69081
+ matches.sort((left, right) => right.mtimeMs - left.mtimeMs);
69082
+ return matches[0] ?? null;
69083
+ }
69084
+ function readRunLast(file2) {
69085
+ try {
69086
+ const parsed = JSON.parse(readFileSync(file2, "utf8"));
69087
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
69088
+ const out = {};
69089
+ for (const [key, value] of Object.entries(parsed)) {
69090
+ if (!value || typeof value !== "object") continue;
69091
+ const entry = value;
69092
+ if (typeof entry.sessionId !== "string" || typeof entry.sessionFile !== "string") continue;
69093
+ out[key] = { sessionId: entry.sessionId, sessionFile: entry.sessionFile };
69094
+ }
69095
+ return out;
69096
+ } catch {
69097
+ return {};
69098
+ }
69099
+ }
69100
+ function writeRunLast(file2, cwd, entry) {
69101
+ const current2 = readRunLast(file2);
69102
+ current2[path.resolve(cwd)] = entry;
69103
+ mkdirSync(path.dirname(file2), { recursive: true });
69104
+ const temp = `${file2}.tmp`;
69105
+ writeFileSync(temp, `${JSON.stringify(current2, null, 2)}
69106
+ `);
69107
+ renameSync(temp, file2);
69108
+ }
69109
+ const STARTUP_TIMEOUT_MS = 6e4;
69110
+ function readJson$1(file2) {
69111
+ try {
69112
+ return JSON.parse(readFileSync(file2, "utf8"));
69113
+ } catch {
69114
+ return void 0;
69115
+ }
69116
+ }
69117
+ function resolvePrompt(args, io) {
69118
+ if (args.prompt === void 0) return { ok: true, text: "" };
69119
+ if (args.prompt === "-") {
69120
+ const text2 = io.readStdin();
69121
+ if (!text2.trim()) return { ok: false, error: "--prompt - 读到空标准输入" };
69122
+ return { ok: true, text: text2 };
69123
+ }
69124
+ if (args.prompt.startsWith("@")) {
69125
+ const file2 = path.resolve(args.cwd, args.prompt.slice(1));
69126
+ try {
69127
+ const text2 = readFileSync(file2, "utf8");
69128
+ if (!text2.trim()) return { ok: false, error: `提示文件是空的: ${file2}` };
69129
+ return { ok: true, text: text2 };
69130
+ } catch {
69131
+ return { ok: false, error: `读不到提示文件 ${file2}` };
69132
+ }
69133
+ }
69134
+ return { ok: true, text: args.prompt };
69135
+ }
69136
+ function toTranscript(message2) {
69137
+ return {
69138
+ role: message2.role,
69139
+ content: message2.content.flatMap((part) => {
69140
+ if (part.type === "text") return [{ type: "text", text: part.text }];
69141
+ if (part.type === "toolCall") {
69142
+ return [{ type: "toolCall", id: part.id, name: part.name, arguments: part.arguments }];
69143
+ }
69144
+ return [];
69145
+ }),
69146
+ ...message2.toolName ? { toolName: message2.toolName } : {},
69147
+ ...message2.toolCallId ? { toolCallId: message2.toolCallId } : {},
69148
+ ...message2.isError ? { isError: true } : {},
69149
+ ...message2.stopReason ? { stopReason: message2.stopReason } : {},
69150
+ ...message2.usage ? { usage: message2.usage } : {},
69151
+ ...message2.model ? { model: message2.model } : {},
69152
+ ...message2.timestamp !== void 0 ? { timestamp: message2.timestamp } : {}
69153
+ };
69154
+ }
69155
+ function configFailure(error) {
69156
+ return /unavailable|assistant|provider|model|api key|select an|invalid|missing/i.test(error);
69157
+ }
69158
+ function goalStop(runtime) {
69159
+ const goal = runtime.goal;
69160
+ if (!goal || goal.status === "completed") {
69161
+ return { code: 0, status: "success", reason: goal ? "completed" : "finished" };
69162
+ }
69163
+ if (goal.status === "blocked") return { code: 3, status: "blocked", reason: "goal-blocked" };
69164
+ if (goal.status === "waiting") return { code: 3, status: "waiting", reason: "goal-waiting" };
69165
+ if (goal.note?.startsWith("no progress")) {
69166
+ return { code: 4, status: "exhausted", reason: "no-progress" };
69167
+ }
69168
+ return { code: 4, status: "exhausted", reason: "auto-turns-exhausted" };
69169
+ }
69170
+ async function executeRun(args, io) {
69171
+ const fail2 = (error) => {
69172
+ io.writeStderr(`${error}
69173
+ `);
69174
+ return 2;
69175
+ };
69176
+ let cwd;
69177
+ try {
69178
+ cwd = path.resolve(args.cwd);
69179
+ if (!statSync(cwd).isDirectory()) return fail2(`--cwd 不是目录: ${cwd}`);
69180
+ } catch {
69181
+ return fail2(`--cwd 不存在: ${path.resolve(args.cwd)}`);
69182
+ }
69183
+ const prompt = resolvePrompt({ ...args, cwd }, io);
69184
+ if (!prompt.ok) return fail2(prompt.error);
69185
+ if (!prompt.text.trim() && !args.goal) return fail2("需要 --prompt,或 --goal / --target");
69186
+ const dataDir2 = app.getPath("userData");
69187
+ const settingsFile = path.join(dataDir2, "settings.json");
69188
+ const existing = readJson$1(settingsFile);
69189
+ const resolved = resolveRunProvider(
69190
+ {
69191
+ providerId: args.providerId,
69192
+ modelId: args.modelId,
69193
+ apiKey: args.apiKey,
69194
+ baseUrl: args.baseUrl,
69195
+ api: args.api
69196
+ },
69197
+ settingsProviders(existing)
69198
+ );
69199
+ if (!resolved.ok) return fail2(resolved.error);
69200
+ if (resolved.value.changed) writeProviderSettings(settingsFile, resolved.value.providers);
69201
+ const sessionDir2 = path.join(agentDataDir(), "sessions");
69202
+ const lastFile = path.join(agentDataDir(), "run-last.json");
69203
+ let sessionId = randomUUID();
69204
+ let resumeFile;
69205
+ if (args.resume) {
69206
+ const found = findSessionById(sessionDir2, args.resume);
69207
+ if (!found) return fail2(`找不到会话 ${args.resume}`);
69208
+ sessionId = found.sessionId;
69209
+ resumeFile = found.sessionFile;
69210
+ } else if (args.continue) {
69211
+ const remembered = readRunLast(lastFile)[cwd];
69212
+ const found = remembered && findSessionById(sessionDir2, remembered.sessionId) || findLatestSessionForCwd(sessionDir2, cwd);
69213
+ if (!found) return fail2(`当前目录没有可继续的会话: ${cwd}`);
69214
+ sessionId = found.sessionId;
69215
+ resumeFile = found.sessionFile;
69216
+ }
69217
+ const effort = args.reasoningEffort;
69218
+ const thinkingLevel = effort && effort !== "off" && effort !== "none" && THINKING_LEVELS.includes(effort) ? effort : void 0;
69219
+ const identity = { sessionId, generation: randomUUID() };
69220
+ const transcript = new RunTranscript(resolved.value.providerId, loadUsageModelPricing());
69221
+ const usageFile = args.usageLog ? path.resolve(cwd, args.usageLog) : void 0;
69222
+ const usageLog = new UsageLogWriter(usageFile);
69223
+ const startedAt = Date.now();
69224
+ let runtime = {
69225
+ ...emptyHeadlessRuntime(),
69226
+ ...args.goal ? { goal: { text: args.goal, status: "active", autoTurns: 0 } } : {}
69227
+ };
69228
+ let lastOutput = "";
69229
+ let noProgressRuns = 0;
69230
+ let turns = 0;
69231
+ let sessionFile = resumeFile;
69232
+ let ready = false;
69233
+ let spawned = false;
69234
+ let settled2 = false;
69235
+ let loggedCalls = 0;
69236
+ let stopTimer;
69237
+ let startupTimer;
69238
+ const stderr = (line2) => io.writeStderr(line2.endsWith("\n") ? line2 : `${line2}
69239
+ `);
69240
+ const emit2 = (records) => {
69241
+ if (args.outputFormat === "stream-json") {
69242
+ for (const record2 of records) io.writeStdout(`${JSON.stringify(record2)}
69243
+ `);
69244
+ }
69245
+ while (loggedCalls < transcript.calls.length) {
69246
+ const call2 = transcript.calls[loggedCalls];
69247
+ if (call2) usageLog.write(usageCallRecord(call2));
69248
+ loggedCalls += 1;
69249
+ }
69250
+ };
69251
+ const writeResult = (stop) => {
69252
+ const usage = transcript.usage();
69253
+ const goal = runtime.goal;
69254
+ const finalMessage = transcript.finalText || goal?.note || "";
69255
+ const result = {
69256
+ status: stop.status,
69257
+ exitCode: stop.code,
69258
+ exitReason: stop.reason,
69259
+ sessionId,
69260
+ finalMessage,
69261
+ turns,
69262
+ durationMs: Date.now() - startedAt,
69263
+ usage,
69264
+ ...sessionFile ? { sessionFile } : {},
69265
+ ...goal ? { goal: { status: goal.status, ...goal.note ? { note: goal.note } : {} } } : {}
69266
+ };
69267
+ if (stop.error) stderr(stop.error);
69268
+ if (args.outputFormat === "stream-json") {
69269
+ io.writeStdout(`${JSON.stringify({ type: "result", ...result })}
69270
+ `);
69271
+ } else if (spawned || stop.code !== 2) {
69272
+ io.writeStdout(renderResult(result, args.outputFormat === "json" ? "json" : "text"));
69273
+ }
69274
+ usageLog.write(usageSummaryRecord(transcript.calls, (/* @__PURE__ */ new Date()).toISOString()));
69275
+ };
69276
+ return await new Promise((resolve2) => {
69277
+ const cleanup = async () => {
69278
+ if (spawned) {
69279
+ abortSession(identity);
69280
+ await Promise.race([
69281
+ releaseParentSession(identity),
69282
+ new Promise((done) => setTimeout(done, 3e3))
69283
+ ]);
69284
+ }
69285
+ await stopAgentWorkerForQuit(3e3);
69286
+ stopAgentWorker();
69287
+ };
69288
+ const stop = (next) => {
69289
+ if (settled2) return;
69290
+ settled2 = true;
69291
+ if (startupTimer) clearTimeout(startupTimer);
69292
+ if (stopTimer) clearTimeout(stopTimer);
69293
+ emit2(transcript.flushTurn());
69294
+ writeResult(next);
69295
+ void cleanup().catch((error) => stderr(error instanceof Error ? error.message : String(error))).finally(() => resolve2(next.code));
69296
+ };
69297
+ if (io.signal.aborted) {
69298
+ stop({ code: 130, status: "interrupted", reason: "interrupted" });
69299
+ return;
69300
+ }
69301
+ io.signal.addEventListener(
69302
+ "abort",
69303
+ () => stop({ code: 130, status: "interrupted", reason: "interrupted" }),
69304
+ { once: true }
69305
+ );
69306
+ if (args.timeoutMs) {
69307
+ stopTimer = setTimeout(
69308
+ () => stop({ code: 124, status: "timeout", reason: "timeout" }),
69309
+ args.timeoutMs
69310
+ );
69311
+ }
69312
+ startupTimer = setTimeout(
69313
+ () => {
69314
+ if (ready) return;
69315
+ stop({ code: 1, status: "error", reason: "worker-start-timeout" });
69316
+ },
69317
+ Math.min(args.timeoutMs ?? STARTUP_TIMEOUT_MS, STARTUP_TIMEOUT_MS)
69318
+ );
69319
+ const relate = (event) => {
69320
+ if (!("identity" in event) || !event.identity) return null;
69321
+ const current2 = event.identity;
69322
+ if ("parent" in current2 && current2.parent.sessionId === sessionId) {
69323
+ return { key: current2.sessionId, parent: false };
69324
+ }
69325
+ if (current2.sessionId === sessionId) return { key: sessionId, parent: true };
69326
+ return null;
69327
+ };
69328
+ setAgentEventListener((event) => {
69329
+ try {
69330
+ if (settled2) return;
69331
+ if (event.type === "worker-exited") {
69332
+ stop({ code: 1, status: "error", reason: "worker-exited" });
69333
+ return;
69334
+ }
69335
+ const who = relate(event);
69336
+ if (!who) return;
69337
+ if (event.type === "message-upsert") {
69338
+ emit2(
69339
+ transcript.ingest(`${who.key}:${event.index}`, toTranscript(event.message), who.parent)
69340
+ );
69341
+ return;
69342
+ }
69343
+ if (!who.parent) return;
69344
+ if (event.type === "goal-signal") {
69345
+ runtime = applyHeadlessGoalSignal(runtime, event.kind, event.note);
69346
+ emit2([{ type: "goal", kind: event.kind, note: event.note }]);
69347
+ return;
69348
+ }
69349
+ if (event.type === "status") {
69350
+ runtime = { ...runtime, status: event.status, started: true };
69351
+ emit2([
69352
+ {
69353
+ type: "status",
69354
+ status: event.status,
69355
+ ...event.error ? { error: event.error } : {}
69356
+ }
69357
+ ]);
69358
+ if (event.status === "failed") {
69359
+ turns += 1;
69360
+ emit2(transcript.flushTurn());
69361
+ stop({ code: 1, status: "error", reason: "turn-failed", error: event.error });
69362
+ }
69363
+ return;
69364
+ }
69365
+ if (event.type === "parent-rejected") {
69366
+ const code = configFailure(event.reason) ? 2 : 1;
69367
+ stop({
69368
+ code,
69369
+ status: "error",
69370
+ reason: code === 2 ? "config" : "rejected",
69371
+ error: event.reason
69372
+ });
69373
+ return;
69374
+ }
69375
+ if (event.type === "parent-ready") {
69376
+ spawned = true;
69377
+ ready = true;
69378
+ sessionFile = event.sessionFile;
69379
+ if (startupTimer) clearTimeout(startupTimer);
69380
+ writeRunLast(lastFile, cwd, { sessionId, sessionFile });
69381
+ const text2 = initialPrompt(prompt.text, args.goal);
69382
+ if (runtime.goal) runtime = { ...runtime, goal: { ...runtime.goal, autoTurns: 1 } };
69383
+ const sent = promptSession(identity, text2);
69384
+ if (!sent.ok) {
69385
+ stop({ code: 1, status: "error", reason: "prompt-rejected", error: sent.error });
69386
+ }
69387
+ return;
69388
+ }
69389
+ if (event.type === "turn-failed") {
69390
+ turns += 1;
69391
+ emit2(transcript.flushTurn());
69392
+ stop({ code: 1, status: "error", reason: "turn-failed", error: event.error });
69393
+ return;
69394
+ }
69395
+ if (event.type !== "turn-completed" || event.aborted) {
69396
+ if (event.type === "turn-completed") {
69397
+ turns += 1;
69398
+ emit2(transcript.flushTurn());
69399
+ stop({ code: 1, status: "error", reason: "aborted" });
69400
+ }
69401
+ return;
69402
+ }
69403
+ turns += 1;
69404
+ emit2(transcript.flushTurn());
69405
+ if (!args.goal) {
69406
+ stop({ code: 0, status: "success", reason: "finished" });
69407
+ return;
69408
+ }
69409
+ const step = nextGoalStep({
69410
+ runtime,
69411
+ assistantText: transcript.finalText,
69412
+ lastOutput,
69413
+ noProgressRuns,
69414
+ autoTurnLimit: args.autoTurns
69415
+ });
69416
+ runtime = step.runtime;
69417
+ lastOutput = step.lastOutput;
69418
+ noProgressRuns = step.noProgressRuns;
69419
+ if (step.deliver && runtime.goal?.status === "active") {
69420
+ const sent = promptSession(identity, step.deliver.text);
69421
+ if (!sent.ok)
69422
+ stop({ code: 1, status: "error", reason: "prompt-rejected", error: sent.error });
69423
+ return;
69424
+ }
69425
+ stop(goalStop(runtime));
69426
+ } catch (error) {
69427
+ stop({
69428
+ code: 1,
69429
+ status: "error",
69430
+ reason: "internal",
69431
+ error: error instanceof Error ? error.message : String(error)
69432
+ });
69433
+ }
69434
+ });
69435
+ try {
69436
+ startAgentWorker();
69437
+ const spawnedCommand = spawnSession(
69438
+ identity,
69439
+ {
69440
+ sessionId,
69441
+ providerId: resolved.value.providerId,
69442
+ modelId: resolved.value.modelId,
69443
+ cwd,
69444
+ approvalMode: args.mode,
69445
+ autoRejectApprovals: true,
69446
+ ...resumeFile ? { resumeFile } : {},
69447
+ ...thinkingLevel ? { reasoningEnabled: true, thinkingLevel } : {}
69448
+ },
69449
+ /* @__PURE__ */ new Set(),
69450
+ void 0,
69451
+ void 0,
69452
+ { extraDisabledTools: disabledToolsForRun(args.disallowedTools, args.allowTools) }
69453
+ );
69454
+ if (!spawnedCommand.ok) {
69455
+ const code = configFailure(spawnedCommand.error ?? "") ? 2 : 1;
69456
+ stop({
69457
+ code,
69458
+ status: "error",
69459
+ reason: code === 2 ? "config" : "spawn-failed",
69460
+ error: spawnedCommand.error
69461
+ });
69462
+ } else {
69463
+ spawned = true;
69464
+ stderr(
69465
+ `[enso-server] run session=${sessionId} provider=${resolved.value.providerId} model=${resolved.value.modelId}`
69466
+ );
69467
+ }
69468
+ } catch (error) {
69469
+ stop({
69470
+ code: 1,
69471
+ status: "error",
69472
+ reason: "spawn-failed",
69473
+ error: error instanceof Error ? error.message : String(error)
69474
+ });
69475
+ }
69476
+ });
69477
+ }
69478
+ function captureStdout() {
69479
+ const write = process.stdout.write.bind(process.stdout);
69480
+ const writeStderr = process.stderr.write.bind(process.stderr);
69481
+ const redirect = (...args) => {
69482
+ const text2 = args.map((item) => typeof item === "string" ? item : String(item)).join(" ");
69483
+ writeStderr(`${text2}
69484
+ `);
69485
+ };
69486
+ console.log = redirect;
69487
+ console.info = redirect;
69488
+ console.debug = redirect;
69489
+ return (chunk) => {
69490
+ write(chunk);
69491
+ };
69492
+ }
69493
+ async function runCli(argv) {
69494
+ const parsed = parseRunArgs(argv);
69495
+ if (!parsed.ok) {
69496
+ if (parsed.help) {
69497
+ process.stdout.write(`${RUN_USAGE}
69498
+ `);
69499
+ return 0;
69500
+ }
69501
+ process.stderr.write(`${parsed.error}
69502
+ ${RUN_USAGE}
69503
+ `);
69504
+ return 2;
69505
+ }
69506
+ if (parsed.args.dataDir) process.env.ENSO_DATA_DIR = parsed.args.dataDir;
69507
+ process.env[ENSO_HEADLESS_RUN_ENV] = "1";
69508
+ const writeStdout = captureStdout();
69509
+ const controller = new AbortController();
69510
+ let signals = 0;
69511
+ const onSignal = () => {
69512
+ signals += 1;
69513
+ if (signals > 1) process.exit(130);
69514
+ controller.abort();
69515
+ };
69516
+ process.on("SIGINT", onSignal);
69517
+ process.on("SIGTERM", onSignal);
69518
+ try {
69519
+ return await executeRun(parsed.args, {
69520
+ writeStdout,
69521
+ writeStderr: (chunk) => {
69522
+ process.stderr.write(chunk);
69523
+ },
69524
+ readStdin: () => readFileSync(0, "utf8"),
69525
+ signal: controller.signal
69526
+ });
69527
+ } finally {
69528
+ process.off("SIGINT", onSignal);
69529
+ process.off("SIGTERM", onSignal);
69530
+ }
69531
+ }
67128
69532
  const AUTO_RESTART_IDLE_MS = 5 * 60 * 1e3;
67129
69533
  function isTurnRestartBlocked(snapshot2) {
67130
69534
  return snapshot2.agentBusy || snapshot2.queuedCount > 0 || snapshot2.pendingAskCount > 0 || snapshot2.pendingApprovalCount > 0;
@@ -71481,7 +73885,7 @@ function createRelayServer(options) {
71481
73885
  if (pathname.startsWith("/v1/")) return json(res, 404, { error: "not found" });
71482
73886
  return serveStatic(req, res, pathname);
71483
73887
  }
71484
- const server2 = createServer((req, res) => {
73888
+ const server2 = createServer$1((req, res) => {
71485
73889
  route(req, res).catch(() => {
71486
73890
  if (!res.headersSent) json(res, 500, { error: "internal" });
71487
73891
  else res.destroy();
@@ -71620,6 +74024,9 @@ async function handlePlugin(command) {
71620
74024
  case "inject-anywhere":
71621
74025
  case "inject-current":
71622
74026
  return plugins.setCrossSessionInject(command.id, command.action === "inject-anywhere");
74027
+ case "dev-on":
74028
+ case "dev-off":
74029
+ return plugins.setDevWatch(command.id, command.action === "dev-on");
71623
74030
  case "config-get":
71624
74031
  return plugins.configView(command.id);
71625
74032
  case "restage":
@@ -71654,7 +74061,7 @@ async function handle(line2, updater, web) {
71654
74061
  function listenControl(updater, web) {
71655
74062
  const file2 = socketPath();
71656
74063
  if (existsSync(file2)) rmSync(file2);
71657
- const server2 = createServer$1({ allowHalfOpen: true }, (socket) => {
74064
+ const server2 = createServer({ allowHalfOpen: true }, (socket) => {
71658
74065
  createInterface({ input: socket }).on("line", (line2) => {
71659
74066
  void handle(line2, updater, web).catch((error) => ({ ok: false, error: String(error) })).then((reply) => socket.end(`${JSON.stringify(reply)}
71660
74067
  `));
@@ -71719,6 +74126,10 @@ async function serve(web) {
71719
74126
  }
71720
74127
  async function main() {
71721
74128
  const argv = process.argv.slice(2);
74129
+ if (argv[0] === "run") {
74130
+ const code = await runCli(argv.slice(1));
74131
+ process.exit(code);
74132
+ }
71722
74133
  if (argv[0] === "start") {
71723
74134
  const config2 = readServerConfig(app.getPath("userData"));
71724
74135
  if (!config2.ok) {