@draht/coding-agent 2026.10.4 → 2026.10.8-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +32 -6
  3. package/dist/bundle/chunks/{anthropic-messages-GAKYXF65.js → anthropic-messages-E2P6C3P7.js} +1 -1
  4. package/dist/bundle/chunks/anthropic.js +1 -1
  5. package/dist/bundle/chunks/{azure-openai-responses-ZIXMK6JO.js → azure-openai-responses-JZMSTDIM.js} +1 -1
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +20 -20
  7. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  8. package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
  9. package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-6QIFWMDF.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-AHGUOQPH.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-BOGY4QVF.js} +4 -4
  12. package/dist/bundle/chunks/{chunk-RZKPFWMH.js → chunk-D3HO453P.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-FHX2S5IG.js} +1 -1
  14. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  15. package/dist/bundle/chunks/chunk-GD2WVXWT.js +65 -0
  16. package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-KJJJSTND.js} +307 -168
  17. package/dist/bundle/chunks/{chunk-BXSHCX3G.js → chunk-KY2BG6BC.js} +1 -1
  18. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  19. package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
  20. package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
  21. package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-QVTLBSTH.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-U6LDZZGM.js} +10 -10
  23. package/dist/bundle/chunks/{chunk-D6TMD5Q2.js → chunk-UTRX2VHB.js} +8 -8
  24. package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-VQOV5VFH.js} +1 -1
  25. package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
  26. package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-O6OWCY7N.js} +1 -1
  27. package/dist/bundle/chunks/execute-4JU5WQXP.js +18 -0
  28. package/dist/bundle/chunks/google-antigravity.js +1 -1
  29. package/dist/bundle/chunks/google-gemini-cli.js +1 -1
  30. package/dist/bundle/chunks/{google-generative-ai-RPUPQ6PM.js → google-generative-ai-HPNDIAZD.js} +1 -1
  31. package/dist/bundle/chunks/{google-vertex-EZES5QVQ.js → google-vertex-KPAWJ4SP.js} +1 -1
  32. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  33. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  34. package/dist/bundle/chunks/{mistral-conversations-AOYGU43Y.js → mistral-conversations-FMSPWQ7A.js} +1 -1
  35. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  36. package/dist/bundle/chunks/{node-LQ52KV6B.js → node-4JNG6XQO.js} +1 -1
  37. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-6IIDYB3K.js} +1 -1
  38. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  39. package/dist/bundle/chunks/{openai-codex-responses-M2Y77JEQ.js → openai-codex-responses-TU7NGPXE.js} +1 -1
  40. package/dist/bundle/chunks/openai-codex.js +1 -1
  41. package/dist/bundle/chunks/{openai-completions-A4OKYOYV.js → openai-completions-GANCQQO5.js} +1 -1
  42. package/dist/bundle/chunks/{openai-responses-6IXV53T3.js → openai-responses-ASDPAX3E.js} +1 -1
  43. package/dist/bundle/chunks/{openrouter-images-LYV4NKFM.js → openrouter-images-NROSQXMZ.js} +1 -1
  44. package/dist/bundle/chunks/openrouter.js +1 -1
  45. package/dist/bundle/chunks/{pi-messages-KKMEUT3Z.js → pi-messages-2QEJYOAO.js} +1 -1
  46. package/dist/bundle/chunks/radius.js +1 -1
  47. package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-FIGQHW75.js} +1 -1
  48. package/dist/bundle/chunks/runtime-TJ3EAMJK.js +3 -0
  49. package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-HC5RR36T.js} +1 -1
  50. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  51. package/dist/bundle/chunks/virtual-modules-UIGTRGHQ.js +2 -0
  52. package/dist/bundle/chunks/xai.js +1 -1
  53. package/dist/bundle/cli-runtime.js +1 -1
  54. package/dist/bundle/index.js +1 -1
  55. package/dist/bundle/rpc-entry.js +1 -1
  56. package/dist/cli/args.js +3 -3
  57. package/dist/cli/args.js.map +1 -1
  58. package/dist/core/builtins/duet.d.ts +5 -2
  59. package/dist/core/builtins/duet.d.ts.map +1 -1
  60. package/dist/core/builtins/duet.js +65 -27
  61. package/dist/core/builtins/duet.js.map +1 -1
  62. package/dist/core/builtins/index.d.ts.map +1 -1
  63. package/dist/core/builtins/index.js +2 -0
  64. package/dist/core/builtins/index.js.map +1 -1
  65. package/dist/core/builtins/polyphase.d.ts +15 -0
  66. package/dist/core/builtins/polyphase.d.ts.map +1 -0
  67. package/dist/core/builtins/polyphase.js +196 -0
  68. package/dist/core/builtins/polyphase.js.map +1 -0
  69. package/dist/core/builtins/subagent.d.ts +44 -34
  70. package/dist/core/builtins/subagent.d.ts.map +1 -1
  71. package/dist/core/builtins/subagent.js +827 -560
  72. package/dist/core/builtins/subagent.js.map +1 -1
  73. package/dist/core/extensions/types.d.ts +17 -2
  74. package/dist/core/extensions/types.d.ts.map +1 -1
  75. package/dist/core/extensions/types.js.map +1 -1
  76. package/dist/core/keybindings.d.ts +30 -0
  77. package/dist/core/keybindings.d.ts.map +1 -1
  78. package/dist/core/keybindings.js +24 -0
  79. package/dist/core/keybindings.js.map +1 -1
  80. package/dist/core/model-resolver.js +4 -4
  81. package/dist/core/model-resolver.js.map +1 -1
  82. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  83. package/dist/core/multi-agent/permission-gate.js +4 -1
  84. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  85. package/dist/core/polyphase/approval.d.ts +35 -0
  86. package/dist/core/polyphase/approval.d.ts.map +1 -0
  87. package/dist/core/polyphase/approval.js +184 -0
  88. package/dist/core/polyphase/approval.js.map +1 -0
  89. package/dist/core/polyphase/child-events.d.ts +107 -0
  90. package/dist/core/polyphase/child-events.d.ts.map +1 -0
  91. package/dist/core/polyphase/child-events.js +862 -0
  92. package/dist/core/polyphase/child-events.js.map +1 -0
  93. package/dist/core/polyphase/child-process.d.ts +65 -0
  94. package/dist/core/polyphase/child-process.d.ts.map +1 -0
  95. package/dist/core/polyphase/child-process.js +361 -0
  96. package/dist/core/polyphase/child-process.js.map +1 -0
  97. package/dist/core/polyphase/commands.d.ts +44 -0
  98. package/dist/core/polyphase/commands.d.ts.map +1 -0
  99. package/dist/core/polyphase/commands.js +244 -0
  100. package/dist/core/polyphase/commands.js.map +1 -0
  101. package/dist/core/polyphase/details.d.ts +40 -0
  102. package/dist/core/polyphase/details.d.ts.map +1 -0
  103. package/dist/core/polyphase/details.js +538 -0
  104. package/dist/core/polyphase/details.js.map +1 -0
  105. package/dist/core/polyphase/emitter.d.ts +20 -0
  106. package/dist/core/polyphase/emitter.d.ts.map +1 -0
  107. package/dist/core/polyphase/emitter.js +90 -0
  108. package/dist/core/polyphase/emitter.js.map +1 -0
  109. package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
  110. package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
  111. package/dist/core/polyphase/jsonl-reader.js +161 -0
  112. package/dist/core/polyphase/jsonl-reader.js.map +1 -0
  113. package/dist/core/polyphase/keyword.d.ts +27 -0
  114. package/dist/core/polyphase/keyword.d.ts.map +1 -0
  115. package/dist/core/polyphase/keyword.js +97 -0
  116. package/dist/core/polyphase/keyword.js.map +1 -0
  117. package/dist/core/polyphase/limiter.d.ts +38 -0
  118. package/dist/core/polyphase/limiter.d.ts.map +1 -0
  119. package/dist/core/polyphase/limiter.js +129 -0
  120. package/dist/core/polyphase/limiter.js.map +1 -0
  121. package/dist/core/polyphase/model-selection.d.ts +35 -0
  122. package/dist/core/polyphase/model-selection.d.ts.map +1 -0
  123. package/dist/core/polyphase/model-selection.js +72 -0
  124. package/dist/core/polyphase/model-selection.js.map +1 -0
  125. package/dist/core/polyphase/render/format.d.ts +52 -0
  126. package/dist/core/polyphase/render/format.d.ts.map +1 -0
  127. package/dist/core/polyphase/render/format.js +169 -0
  128. package/dist/core/polyphase/render/format.js.map +1 -0
  129. package/dist/core/polyphase/render/renderers.d.ts +63 -0
  130. package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
  131. package/dist/core/polyphase/render/renderers.js +277 -0
  132. package/dist/core/polyphase/render/renderers.js.map +1 -0
  133. package/dist/core/polyphase/render/run-block.d.ts +45 -0
  134. package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
  135. package/dist/core/polyphase/render/run-block.js +843 -0
  136. package/dist/core/polyphase/render/run-block.js.map +1 -0
  137. package/dist/core/polyphase/render/snapshot.d.ts +106 -0
  138. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
  139. package/dist/core/polyphase/render/snapshot.js +292 -0
  140. package/dist/core/polyphase/render/snapshot.js.map +1 -0
  141. package/dist/core/polyphase/result-text.d.ts +41 -0
  142. package/dist/core/polyphase/result-text.d.ts.map +1 -0
  143. package/dist/core/polyphase/result-text.js +326 -0
  144. package/dist/core/polyphase/result-text.js.map +1 -0
  145. package/dist/core/polyphase/session.d.ts +33 -0
  146. package/dist/core/polyphase/session.d.ts.map +1 -0
  147. package/dist/core/polyphase/session.js +106 -0
  148. package/dist/core/polyphase/session.js.map +1 -0
  149. package/dist/core/polyphase/settings.d.ts +18 -0
  150. package/dist/core/polyphase/settings.d.ts.map +1 -0
  151. package/dist/core/polyphase/settings.js +93 -0
  152. package/dist/core/polyphase/settings.js.map +1 -0
  153. package/dist/core/polyphase/store.d.ts +197 -0
  154. package/dist/core/polyphase/store.d.ts.map +1 -0
  155. package/dist/core/polyphase/store.js +558 -0
  156. package/dist/core/polyphase/store.js.map +1 -0
  157. package/dist/core/polyphase/types.d.ts +371 -0
  158. package/dist/core/polyphase/types.d.ts.map +1 -0
  159. package/dist/core/polyphase/types.js +36 -0
  160. package/dist/core/polyphase/types.js.map +1 -0
  161. package/dist/core/polyphase/ui/controller.d.ts +28 -0
  162. package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
  163. package/dist/core/polyphase/ui/controller.js +150 -0
  164. package/dist/core/polyphase/ui/controller.js.map +1 -0
  165. package/dist/core/polyphase/ui/dock.d.ts +27 -0
  166. package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
  167. package/dist/core/polyphase/ui/dock.js +121 -0
  168. package/dist/core/polyphase/ui/dock.js.map +1 -0
  169. package/dist/core/polyphase/ui/inspector.d.ts +117 -0
  170. package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
  171. package/dist/core/polyphase/ui/inspector.js +1016 -0
  172. package/dist/core/polyphase/ui/inspector.js.map +1 -0
  173. package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
  174. package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
  175. package/dist/core/polyphase/ui/transcript-layout.js +210 -0
  176. package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
  177. package/dist/core/polyphase/update-pump.d.ts +18 -0
  178. package/dist/core/polyphase/update-pump.d.ts.map +1 -0
  179. package/dist/core/polyphase/update-pump.js +132 -0
  180. package/dist/core/polyphase/update-pump.js.map +1 -0
  181. package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
  182. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
  183. package/dist/core/polyphase/workflow/agent-host.js +187 -0
  184. package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
  185. package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
  186. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
  187. package/dist/core/polyphase/workflow/guidance.js +119 -0
  188. package/dist/core/polyphase/workflow/guidance.js.map +1 -0
  189. package/dist/core/polyphase/workflow/launch.d.ts +41 -0
  190. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
  191. package/dist/core/polyphase/workflow/launch.js +173 -0
  192. package/dist/core/polyphase/workflow/launch.js.map +1 -0
  193. package/dist/core/polyphase/workflow/meta.d.ts +43 -0
  194. package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
  195. package/dist/core/polyphase/workflow/meta.js +529 -0
  196. package/dist/core/polyphase/workflow/meta.js.map +1 -0
  197. package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
  198. package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
  199. package/dist/core/polyphase/workflow/prelude.js +93 -0
  200. package/dist/core/polyphase/workflow/prelude.js.map +1 -0
  201. package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
  202. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
  203. package/dist/core/polyphase/workflow/runtime.js +217 -0
  204. package/dist/core/polyphase/workflow/runtime.js.map +1 -0
  205. package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
  206. package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
  207. package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
  208. package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
  209. package/dist/core/polyphase/workflow/saved.d.ts +55 -0
  210. package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
  211. package/dist/core/polyphase/workflow/saved.js +299 -0
  212. package/dist/core/polyphase/workflow/saved.js.map +1 -0
  213. package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
  214. package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
  215. package/dist/core/polyphase/workflow/structured-output.js +66 -0
  216. package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
  217. package/dist/core/polyphase/workflow/tool.d.ts +24 -0
  218. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
  219. package/dist/core/polyphase/workflow/tool.js +139 -0
  220. package/dist/core/polyphase/workflow/tool.js.map +1 -0
  221. package/dist/core/sdk.d.ts +1 -1
  222. package/dist/core/sdk.js +1 -1
  223. package/dist/core/sdk.js.map +1 -1
  224. package/dist/core/settings-manager.d.ts +27 -0
  225. package/dist/core/settings-manager.d.ts.map +1 -1
  226. package/dist/core/settings-manager.js.map +1 -1
  227. package/dist/core/socket-server/permission-relay.js +4 -0
  228. package/dist/core/socket-server/permission-relay.js.map +1 -1
  229. package/dist/core/trust-manager.d.ts +3 -2
  230. package/dist/core/trust-manager.d.ts.map +1 -1
  231. package/dist/core/trust-manager.js +5 -2
  232. package/dist/core/trust-manager.js.map +1 -1
  233. package/dist/experimental/micro/runtime.js +1 -1
  234. package/dist/experimental/micro/runtime.js.map +1 -1
  235. package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
  236. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/keybinding-hints.js +18 -0
  238. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  239. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  240. package/dist/modes/interactive/interactive-mode.js +11 -2
  241. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  242. package/dist/modes/rpc/rpc-types.d.ts +9 -0
  243. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  244. package/dist/modes/rpc/rpc-types.js.map +1 -1
  245. package/dist/prompts/commands/orchestrate.md +1 -1
  246. package/dist/utils/shell.d.ts.map +1 -1
  247. package/dist/utils/shell.js +7 -1
  248. package/dist/utils/shell.js.map +1 -1
  249. package/docs/docs.json +4 -0
  250. package/docs/duet.md +3 -3
  251. package/docs/environment-variables.md +11 -0
  252. package/docs/json.md +7 -0
  253. package/docs/keybindings.md +20 -0
  254. package/docs/polyphase.md +391 -0
  255. package/docs/rpc-commands.md +9 -9
  256. package/docs/settings.md +12 -0
  257. package/docs/virtual-models.md +3 -3
  258. package/examples/extensions/preset.ts +3 -3
  259. package/examples/extensions/subagent/README.md +1 -1
  260. package/examples/extensions/subagent/agents/planner.md +1 -1
  261. package/examples/extensions/subagent/agents/reviewer.md +1 -1
  262. package/examples/extensions/subagent/agents/scout.md +1 -1
  263. package/examples/extensions/subagent/agents/worker.md +1 -1
  264. package/examples/extensions/summarize.ts +3 -3
  265. package/examples/sdk/02-custom-model.ts +1 -1
  266. package/examples/sdk/12-full-control.ts +1 -1
  267. package/examples/sdk/README.md +1 -1
  268. package/package.json +10 -10
  269. package/prompts/commands/orchestrate.md +1 -1
  270. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  271. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +0 -2
  272. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  273. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
  274. package/dist/bundle/chunks/chunk-IWTUBX6V.js +0 -4
  275. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  276. package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
  277. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  278. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  279. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  280. package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
  281. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-FBU742QF.js} +0 -0
  282. /package/dist/bundle/chunks/{chunk-SVNWI7EV.js → chunk-XHCO4PPH.js} +0 -0
@@ -0,0 +1,312 @@
1
+ import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
+ import{toCodemodeIdentifier}from"./chunk-PGJAHC3R.js";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}import{Worker}from"node:worker_threads";function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function outputItemChars(item){return item.type==="text"?item.text.length:item.data.length}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}function parseStoreWrites(json){let writes={set:{},delete:[]};for(let[key,value]of JSON.parse(json))value===void 0?writes.delete.push(key):writes.set[key]=JSON.parse(value);return writes}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}var Execution=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;maxOutputChars;outputChars=0;finished=!1;constructor(options){this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.tools=options.tools,this.globals=options.globals,this.signal=options.signal,this.maxOutputChars=options.maxOutputChars,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),options.wasm.then(wasm=>this.start(options,wasm),error=>{this.finish({kind:"sandbox",message:`Failed to load QuickJS: ${errorMessage(error)}`})})}abort(message){return this.finish({kind:"aborted",message}),this.promise}start(options,wasm){if(this.finished)return;let workerData={code:options.code,tools:[...options.tools.values()].map(tool=>({name:tool.name,jsName:toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:[...options.globals.values()].map(global=>({name:global.name,spread:global.spread===!0})),wasm,memoryLimitBytes:options.memoryLimitBytes,store:options.store,interrupt:this.interrupt},worker;try{worker=new Worker(options.workerUrl,{workerData})}catch(error){this.finish({kind:"sandbox",message:`Failed to start worker: ${errorMessage(error)}`});return}this.worker=worker,worker.on("message",message=>this.handleMessage(message)),worker.on("error",error=>{this.finish({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{this.finish({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})})}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.worker?.postMessage(message)}handleMessage(message){if(!(this.finished||!isWorkerToHostMessage(message)))switch(message.type){case"output":this.output.push(message.item),this.outputChars+=outputItemChars(message.item),this.maxOutputChars!==void 0&&this.outputChars>this.maxOutputChars&&this.finish({kind:"sandbox",message:`Script output exceeded ${this.maxOutputChars} characters and was stopped`});break;case"call":this.handleCall(message);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}handleDone(message){if(!message.ok){let parsed=JSON.parse(message.error);this.finish({kind:"script",...parsed});return}this.finish(void 0,message.value===void 0?void 0:JSON.parse(message.value),message.writes)}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.tools:this.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear();let result=error?{ok:!1,error,output:this.output,calls:this.calls}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes===void 0?{set:{},delete:[]}:parseStoreWrites(writes)};if(!this.worker){this.resolveResult(result);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandbox=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;maxOutputChars;wasm;workerUrl;running=new Set;closed=!1;constructor(options={}){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.maxOutputChars=options.maxOutputChars,this.wasm=options.wasm,this.workerUrl=options.workerUrl??defaultWorkerUrl();for(let tool of options.tools??[])this.registerTool(tool);let namespaces=new Set;for(let global of options.globals??[]){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(this.globalsByName.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),this.globalsByName.set(global.name,global)}for(let name of namespaces)if(this.globalsByName.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let execution=new Execution({code,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,maxOutputChars:this.maxOutputChars,store:serializeStore(options.store),wasm:this.wasm===void 0?loadQuickJSWasm():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};var IMAGE_HELPER_EXPECTS="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
3
+ "use strict";
4
+ const stringify = JSON.stringify;
5
+ const parse = JSON.parse;
6
+ const promiseThen = Promise.prototype.then;
7
+ const ErrorCtor = Error;
8
+ const TypeErrorCtor = TypeError;
9
+ const pending = new Map();
10
+ let nextId = 1;
11
+ let finished = false;
12
+ // Thrown by exit() to unwind the script after it already reported success.
13
+ const EXIT = Object.freeze({});
14
+
15
+ function done(ok, payload, writes) {
16
+ if (finished) return;
17
+ finished = true;
18
+ bridge("done", ok, payload, writes);
19
+ }
20
+
21
+ function serialize(value) {
22
+ return value === undefined ? undefined : stringify(value);
23
+ }
24
+
25
+ // QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
26
+ // text reads the same as a Node error, and drop this prelude's frames.
27
+ function errorText(error) {
28
+ const head = error.message ? error.name + ": " + error.message : String(error.name);
29
+ const frames =
30
+ typeof error.stack === "string"
31
+ ? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
32
+ : [];
33
+ return [head, ...frames].join("\\n");
34
+ }
35
+
36
+ function format(value) {
37
+ if (typeof value === "string") return value;
38
+ if (value instanceof ErrorCtor) return errorText(value);
39
+ try {
40
+ const json = stringify(value);
41
+ return json === undefined ? String(value) : json;
42
+ } catch {
43
+ return String(value);
44
+ }
45
+ }
46
+
47
+ function describeError(error) {
48
+ if (error instanceof ErrorCtor) {
49
+ return stringify({ name: error.name, message: error.message, stack: errorText(error) });
50
+ }
51
+ return stringify({ message: format(error) });
52
+ }
53
+
54
+ function caller(kind, name, spread) {
55
+ return (...args) =>
56
+ new Promise((resolve, reject) => {
57
+ let json;
58
+ try {
59
+ json = serialize(spread ? args : args[0]);
60
+ } catch (error) {
61
+ reject(error);
62
+ return;
63
+ }
64
+ const id = nextId++;
65
+ pending.set(id, { resolve, reject });
66
+ bridge(kind, id, name, json);
67
+ });
68
+ }
69
+
70
+ const tools = Object.create(null);
71
+ const allTools = [];
72
+ for (const { name, jsName, description } of parse(toolsJson)) {
73
+ const fn = caller("call", name);
74
+ // The first tool wins when two names normalize to the same identifier.
75
+ if (!(jsName in tools)) {
76
+ tools[jsName] = fn;
77
+ allTools.push(Object.freeze({ name: jsName, description }));
78
+ }
79
+ if (!(name in tools)) tools[name] = fn;
80
+ }
81
+ Object.freeze(tools);
82
+ Object.freeze(allTools);
83
+
84
+ const namespaces = new Map();
85
+ for (const { name, spread } of parse(globalsJson)) {
86
+ const fn = caller("global", name, spread);
87
+ const dot = name.indexOf(".");
88
+ if (dot === -1) {
89
+ Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
90
+ continue;
91
+ }
92
+ const namespace = name.slice(0, dot);
93
+ if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
94
+ namespaces.get(namespace)[name.slice(dot + 1)] = fn;
95
+ }
96
+ for (const [namespace, members] of namespaces) {
97
+ Object.defineProperty(globalThis, namespace, { value: Object.freeze(members), enumerable: true });
98
+ }
99
+
100
+ // key -> JSON text. Sizes count key and JSON characters.
101
+ const stored = new Map(Object.entries(parse(storeJson)));
102
+ const writes = new Map();
103
+ let storedChars = 0;
104
+ for (const [key, json] of stored) storedChars += key.length + json.length;
105
+
106
+ function checkKey(name, key) {
107
+ if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
108
+ }
109
+
110
+ function store(key, value) {
111
+ checkKey("store", key);
112
+ const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
113
+ if (value === undefined) {
114
+ stored.delete(key);
115
+ storedChars -= previous;
116
+ writes.set(key, undefined);
117
+ return;
118
+ }
119
+ let json;
120
+ try {
121
+ json = stringify(value);
122
+ } catch (error) {
123
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
124
+ }
125
+ if (json === undefined) {
126
+ throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
127
+ }
128
+ if (json.length > 262144) {
129
+ throw new RangeError("store(" + stringify(key) + ") value exceeds 262144 characters of JSON");
130
+ }
131
+ const next = storedChars - previous + key.length + json.length;
132
+ if (next > 1048576) {
133
+ throw new RangeError("store is full: stored values would exceed 1048576 characters of JSON");
134
+ }
135
+ stored.set(key, json);
136
+ storedChars = next;
137
+ writes.set(key, json);
138
+ }
139
+
140
+ function load(key) {
141
+ checkKey("load", key);
142
+ const json = stored.get(key);
143
+ return json === undefined ? undefined : parse(json);
144
+ }
145
+
146
+ function serializeWrites() {
147
+ const entries = [];
148
+ for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
149
+ return stringify(entries);
150
+ }
151
+
152
+ Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
153
+ Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
154
+
155
+ // Primitives become their string form, everything else JSON.
156
+ function outputText(value) {
157
+ if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
158
+ return String(value);
159
+ }
160
+ const json = stringify(value);
161
+ return json === undefined ? String(value) : json;
162
+ }
163
+
164
+ function text(value) {
165
+ let rendered;
166
+ try {
167
+ rendered = outputText(value);
168
+ } catch (error) {
169
+ throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
170
+ }
171
+ if (!finished) bridge("output", "text", rendered);
172
+ }
173
+
174
+ function imageUrl(value) {
175
+ if (typeof value === "string") return value;
176
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
177
+ throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
178
+ }
179
+ if (value.image_url !== undefined) {
180
+ if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
181
+ return value.image_url;
182
+ }
183
+ if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
184
+ if (value.type !== "image") {
185
+ throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
186
+ }
187
+ if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
188
+ if (value.data.toLowerCase().startsWith("data:")) return value.data;
189
+ return "data:;base64," + value.data;
190
+ }
191
+
192
+ // Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
193
+ // JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
194
+ const IMAGE_SIGNATURES = [
195
+ ["image/png", /^iVBORw0KGg/],
196
+ ["image/jpeg", /^[/]9j[/](?!9)/],
197
+ ["image/gif", /^R0lGOD[dl]h/],
198
+ ["image/webp", /^UklG.{8}RUJQ/],
199
+ ];
200
+
201
+ function image(value) {
202
+ const url = imageUrl(value);
203
+ if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
204
+ const colon = url.indexOf(":");
205
+ const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
206
+ if (scheme === "http" || scheme === "https") {
207
+ throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
208
+ }
209
+ const comma = url.indexOf(",");
210
+ const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
211
+ if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
212
+ throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
213
+ }
214
+ // Providers reject the whole request on a bad image, and a persisted image block would be
215
+ // resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
216
+ // is ignored in favor of the detected one, as providers also reject mismatches.
217
+ const data = url.slice(comma + 1).replace(/\\s+/g, "");
218
+ if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
219
+ throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
220
+ }
221
+ const head = data.slice(0, 16);
222
+ const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
223
+ if (!signature) {
224
+ throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
225
+ }
226
+ if (!finished) bridge("output", "image", data, signature[0]);
227
+ }
228
+
229
+ function exit() {
230
+ let writesJson;
231
+ try {
232
+ writesJson = serializeWrites();
233
+ } catch (error) {
234
+ done(false, describeError(error));
235
+ throw EXIT;
236
+ }
237
+ done(true, undefined, writesJson);
238
+ throw EXIT;
239
+ }
240
+
241
+ const console = {};
242
+ for (const level of ["log", "info", "warn", "error", "debug"]) {
243
+ console[level] = (...args) => {
244
+ if (!finished) bridge("output", "text", args.map(format).join(" "));
245
+ };
246
+ }
247
+ Object.freeze(console);
248
+
249
+ Object.defineProperty(globalThis, "tools", { value: tools, enumerable: true });
250
+ Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
251
+ Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
252
+ Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
253
+ Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
254
+ Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
255
+
256
+ return {
257
+ settle(id, ok, payload) {
258
+ const entry = pending.get(id);
259
+ if (!entry) return;
260
+ pending.delete(id);
261
+ if (!ok) {
262
+ entry.reject(new ErrorCtor(payload));
263
+ return;
264
+ }
265
+ let value;
266
+ try {
267
+ value = payload === undefined ? undefined : parse(payload);
268
+ } catch (error) {
269
+ entry.reject(error);
270
+ return;
271
+ }
272
+ entry.resolve(value);
273
+ },
274
+ run(fn) {
275
+ let promise;
276
+ try {
277
+ promise = fn(tools, console);
278
+ } catch (error) {
279
+ done(false, describeError(error));
280
+ return;
281
+ }
282
+ promiseThen.call(
283
+ promise,
284
+ (value) => {
285
+ let json;
286
+ try {
287
+ json = serialize(value);
288
+ } catch (error) {
289
+ done(false, describeError(error));
290
+ return;
291
+ }
292
+ done(true, json, serializeWrites());
293
+ },
294
+ (error) => {
295
+ done(false, describeError(error));
296
+ },
297
+ );
298
+ },
299
+ stalled() {
300
+ if (finished || pending.size > 0) return false;
301
+ done(
302
+ false,
303
+ stringify({
304
+ name: "Error",
305
+ message:
306
+ "The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
307
+ }),
308
+ );
309
+ return true;
310
+ },
311
+ };
312
+ })`;export{loadQuickJSWasm,CodemodeSandbox};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{require_proper_lockfile}from"./chunk-TIA2T6EO.js";import{CONFIG_DIR_NAME,normalizePath,resolvePath,stripBom}from"./chunk-6ZJKIMU7.js";import{__toESM}from"./chunk-HZ2UHMBT.js";var MCP_EXPOSURES=["codemode","deferred","direct","hidden"],MCP_EXPOSURE_ALIASES={"codemode-deferred":"codemode"},LOOPBACK_HOSTS=["localhost","127.0.0.1","[::1]"];function isLoopbackRedirectUri(value){if(!URL.canParse(value))return!1;let url=new URL(value);return url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)&&url.search===""&&url.hash===""}var SERVER_NAME=/^[A-Za-z0-9_-]+$/;function mcpNamespace(server){return`mcp__${server.replace(/-/g,"_")}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every(entry=>typeof entry=="string")}function validateOAuth(value){if(value===void 0)return;if(!isRecord(value))return"oauth must be an object";if(value.clientId!==void 0&&typeof value.clientId!="string")return"oauth.clientId must be a string";if(value.clientSecret!==void 0&&typeof value.clientSecret!="string")return"oauth.clientSecret must be a string";let port=value.callbackPort;if(port!==void 0&&(typeof port!="number"||!Number.isInteger(port)||port<1||port>65535))return"oauth.callbackPort must be a port number";if(value.callbackUrl!==void 0){if(typeof value.callbackUrl!="string"||!isLoopbackRedirectUri(value.callbackUrl))return"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";let urlPort=new URL(value.callbackUrl).port;if(urlPort&&port!==void 0&&Number(urlPort)!==port)return"oauth.callbackUrl and oauth.callbackPort name different ports"}if(value.scope!==void 0&&typeof value.scope!="string")return"oauth.scope must be a string";if(value.clientName!==void 0&&(typeof value.clientName!="string"||!value.clientName.trim()))return"oauth.clientName must be a non-empty string"}function isExposure(value){return typeof value=="string"&&MCP_EXPOSURES.includes(value)}function resolveExposureAlias(value){return typeof value=="string"?MCP_EXPOSURE_ALIASES[value]??value:value}function resolveExposureAliases(value){let{exposure,toolExposure}=value,resolved={...value};return exposure!==void 0&&(resolved.exposure=resolveExposureAlias(exposure)),isRecord(toolExposure)&&(resolved.toolExposure=Object.fromEntries(Object.entries(toolExposure).map(([tool,entry])=>[tool,resolveExposureAlias(entry)]))),resolved}function toolPatternRegExp(pattern){let source=pattern.split("*").map(part=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`)}function getMcpToolExposure(config,toolName){let overrides=config.toolExposure??{},exact=overrides[toolName];if(exact!==void 0)return exact;for(let[pattern,exposure]of Object.entries(overrides))if(pattern.includes("*")&&toolPatternRegExp(pattern).test(toolName))return exposure;return config.exposure??"codemode"}function validateMcpServerConfig(name,raw){if(!SERVER_NAME.test(name))return`invalid server name "${name}" (use letters, digits, "_" and "-")`;if(!isRecord(raw))return`server "${name}" must be an object`;let value=resolveExposureAliases(raw),{type,exposure,enabled,timeout,toolExposure,description}=value,exposures=MCP_EXPOSURES.map(value2=>`"${value2}"`).join(", ");if(exposure!==void 0&&!isExposure(exposure))return`server "${name}": exposure must be one of ${exposures}`;if(toolExposure!==void 0){if(!isRecord(toolExposure))return`server "${name}": toolExposure must map tool names to exposures`;for(let[tool,value2]of Object.entries(toolExposure))if(!isExposure(value2))return`server "${name}": toolExposure "${tool}" must be one of ${exposures}`}if(enabled!==void 0&&typeof enabled!="boolean")return`server "${name}": enabled must be a boolean`;if(description!==void 0&&typeof description!="string")return`server "${name}": description must be a string`;if(timeout!==void 0&&(typeof timeout!="number"||!(timeout>0)))return`server "${name}": timeout must be a positive number of seconds`;if(type==="sse")return`server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof value.url=="string"&&(type===void 0||type==="http"||type==="streamable-http")){if(!URL.canParse(value.url)||!/^https?:$/.test(new URL(value.url).protocol))return`server "${name}": url must be an http or https URL`;if(value.headers!==void 0&&!isStringRecord(value.headers))return`server "${name}": headers must map names to strings`;let oauthError=validateOAuth(value.oauth);if(oauthError)return`server "${name}": ${oauthError}`;if(value.auth!==void 0){if(!isRecord(value.auth)||typeof value.auth.provider!="string"||!value.auth.provider)return`server "${name}": auth.provider must be a provider name`;let url=new URL(value.url);if(url.protocol!=="https:"&&!LOOPBACK_HOSTS.includes(url.hostname))return`server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`}return value}return typeof value.command=="string"&&(type===void 0||type==="stdio")?value.args!==void 0&&!(Array.isArray(value.args)&&value.args.every(arg=>typeof arg=="string"))?`server "${name}": args must be an array of strings`:value.env!==void 0&&!isStringRecord(value.env)?`server "${name}": env must map names to strings`:value.cwd!==void 0&&typeof value.cwd!="string"?`server "${name}": cwd must be a string`:value:`server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`}var McpServerRegistry=class{servers=new Map;changeListener;register(server){this.servers.set(server.name,server),this.changeListener?.()}unregister(name,extensionPath){this.servers.get(name)?.extensionPath===extensionPath&&(this.servers.delete(name),this.changeListener?.())}get(name){return this.servers.get(name)}list(){return[...this.servers.values()].map(server=>({...server,config:structuredClone(server.config)}))}setChangeListener(listener){this.changeListener=listener}};var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,join as join2}from"node:path";import{lstatSync,realpathSync}from"node:fs";import{homedir}from"node:os";import{isAbsolute,join,parse}from"node:path";var realpathNative=realpathSync.native;function errorCode(error){return typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0}function resolveRealSegment(prefix,segment){let candidate=join(prefix,segment);if(candidate.includes("\\"))try{return lstatSync(candidate).isSymbolicLink()?{ok:!1,missing:!1,reason:`refusing to follow ${JSON.stringify(candidate)}: a symbolic link named through a backslash cannot be resolved on every runtime`}:{ok:!0,path:candidate}}catch(error){return{ok:!1,missing:errorCode(error)==="ENOENT",reason:`${error.message}`}}try{return{ok:!0,path:realpathNative(candidate)}}catch(error){return{ok:!1,missing:errorCode(error)==="ENOENT",reason:`${error.message}`}}}function resolveRealPrefix(path){let normalized=normalizePath(path,{expandTilde:!1}),expanded=normalized==="~"||normalized.startsWith("~/")?homedir()+normalized.slice(1):normalized,root=isAbsolute(expanded)?parse(expanded).root:"",real=root||process.cwd(),unresolved=[],failed=!1;for(let segment of expanded.slice(root.length).split("/")){if(segment===""||segment===".")continue;if(unresolved.length>0){segment===".."?unresolved.pop():unresolved.push(segment);continue}let resolved=resolveRealSegment(real,segment);resolved.ok?real=resolved.path:(failed=!0,unresolved.push(segment))}return{real,unresolved,failed}}function spellRealPrefix({real,unresolved}){return unresolved.length===0?real:join(real,...unresolved)}function realPathStrict(path){let{real,failed}=resolveRealPrefix(path);return failed?void 0:real}function trustKeyPath(path){return spellRealPrefix(resolveRealPrefix(path))}function comparablePath(path){return spellRealPrefix(resolveRealPrefix(path))}function realHomeDir(){return realPathStrict(process.env.HOME||homedir())}var TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES=["settings.json","mcp.json","permissions.yml","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES=[join2(".agents","skills"),join2(CONFIG_DIR_NAME,"agents")];function trustKeyEscapesProjectConfigDir(cwd){let lexicalCwd=resolvePath(cwd);return hasProjectConfigResources(lexicalCwd)&&realPathStrict(lexicalCwd)!==realPathStrict(cwd)}function findNearestTrustEntry(data,cwd){let prefix=resolveRealPrefix(cwd),trustBinds=!prefix.failed&&!trustKeyEscapesProjectConfigDir(cwd),currentDir=spellRealPrefix(prefix);for(;;){let value=data[currentDir];if(value===!1||value===!0&&trustBinds)return{path:currentDir,decision:value};let parentDir=dirname(currentDir);if(parentDir===currentDir)return null;currentDir=parentDir}}function getProjectTrustParentPath(cwd){let trustPath=trustKeyPath(cwd),parentDir=dirname(trustPath);return parentDir===trustPath?void 0:parentDir}function getProjectTrustOptions(cwd,options){let trustPath=trustKeyPath(cwd),trustOptions=[{label:"Trust",trusted:!0,updates:[{path:trustPath,decision:!0}],savedPath:trustPath}],parentPath=getProjectTrustParentPath(cwd);return parentPath!==void 0&&trustOptions.push({label:`Trust parent folder (${parentPath})`,trusted:!0,updates:[{path:parentPath,decision:!0},{path:trustPath,decision:null}],savedPath:parentPath}),options?.includeSessionOnly&&trustOptions.push({label:"Trust (this session only)",trusted:!0,updates:[]}),trustOptions.push({label:"Do not trust",trusted:!1,updates:[{path:trustPath,decision:!1}],savedPath:trustPath}),options?.includeSessionOnly&&trustOptions.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),trustOptions}function readTrustFile(path){if(!existsSync(path))return{};let parsed;try{parsed=JSON.parse(stripBom(readFileSync(path,"utf-8")))}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Failed to read trust store ${path}: ${message}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`Invalid trust store ${path}: expected an object`);let data={};for(let[key,value]of Object.entries(parsed)){if(value!==!0&&value!==!1&&value!==null)throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);data[key]=value}return data}function writeTrustFile(path,data){let sorted={};for(let key of Object.keys(data).sort()){let value=data[key];(value===!0||value===!1||value===null)&&(sorted[key]=value)}mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(sorted,null,2)}
2
+ import{require_proper_lockfile}from"./chunk-2JZLKNZ4.js";import{CONFIG_DIR_NAME,normalizePath,resolvePath,stripBom}from"./chunk-VXUJMEMO.js";import{__toESM}from"./chunk-HZ2UHMBT.js";var MCP_EXPOSURES=["codemode","deferred","direct","hidden"],MCP_EXPOSURE_ALIASES={"codemode-deferred":"codemode"},LOOPBACK_HOSTS=["localhost","127.0.0.1","[::1]"];function isLoopbackRedirectUri(value){if(!URL.canParse(value))return!1;let url=new URL(value);return url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)&&url.search===""&&url.hash===""}var SERVER_NAME=/^[A-Za-z0-9_-]+$/;function mcpNamespace(server){return`mcp__${server.replace(/-/g,"_")}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every(entry=>typeof entry=="string")}function validateOAuth(value){if(value===void 0)return;if(!isRecord(value))return"oauth must be an object";if(value.clientId!==void 0&&typeof value.clientId!="string")return"oauth.clientId must be a string";if(value.clientSecret!==void 0&&typeof value.clientSecret!="string")return"oauth.clientSecret must be a string";let port=value.callbackPort;if(port!==void 0&&(typeof port!="number"||!Number.isInteger(port)||port<1||port>65535))return"oauth.callbackPort must be a port number";if(value.callbackUrl!==void 0){if(typeof value.callbackUrl!="string"||!isLoopbackRedirectUri(value.callbackUrl))return"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";let urlPort=new URL(value.callbackUrl).port;if(urlPort&&port!==void 0&&Number(urlPort)!==port)return"oauth.callbackUrl and oauth.callbackPort name different ports"}if(value.scope!==void 0&&typeof value.scope!="string")return"oauth.scope must be a string";if(value.clientName!==void 0&&(typeof value.clientName!="string"||!value.clientName.trim()))return"oauth.clientName must be a non-empty string"}function isExposure(value){return typeof value=="string"&&MCP_EXPOSURES.includes(value)}function resolveExposureAlias(value){return typeof value=="string"?MCP_EXPOSURE_ALIASES[value]??value:value}function resolveExposureAliases(value){let{exposure,toolExposure}=value,resolved={...value};return exposure!==void 0&&(resolved.exposure=resolveExposureAlias(exposure)),isRecord(toolExposure)&&(resolved.toolExposure=Object.fromEntries(Object.entries(toolExposure).map(([tool,entry])=>[tool,resolveExposureAlias(entry)]))),resolved}function toolPatternRegExp(pattern){let source=pattern.split("*").map(part=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`)}function getMcpToolExposure(config,toolName){let overrides=config.toolExposure??{},exact=overrides[toolName];if(exact!==void 0)return exact;for(let[pattern,exposure]of Object.entries(overrides))if(pattern.includes("*")&&toolPatternRegExp(pattern).test(toolName))return exposure;return config.exposure??"codemode"}function validateMcpServerConfig(name,raw){if(!SERVER_NAME.test(name))return`invalid server name "${name}" (use letters, digits, "_" and "-")`;if(!isRecord(raw))return`server "${name}" must be an object`;let value=resolveExposureAliases(raw),{type,exposure,enabled,timeout,toolExposure,description}=value,exposures=MCP_EXPOSURES.map(value2=>`"${value2}"`).join(", ");if(exposure!==void 0&&!isExposure(exposure))return`server "${name}": exposure must be one of ${exposures}`;if(toolExposure!==void 0){if(!isRecord(toolExposure))return`server "${name}": toolExposure must map tool names to exposures`;for(let[tool,value2]of Object.entries(toolExposure))if(!isExposure(value2))return`server "${name}": toolExposure "${tool}" must be one of ${exposures}`}if(enabled!==void 0&&typeof enabled!="boolean")return`server "${name}": enabled must be a boolean`;if(description!==void 0&&typeof description!="string")return`server "${name}": description must be a string`;if(timeout!==void 0&&(typeof timeout!="number"||!(timeout>0)))return`server "${name}": timeout must be a positive number of seconds`;if(type==="sse")return`server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof value.url=="string"&&(type===void 0||type==="http"||type==="streamable-http")){if(!URL.canParse(value.url)||!/^https?:$/.test(new URL(value.url).protocol))return`server "${name}": url must be an http or https URL`;if(value.headers!==void 0&&!isStringRecord(value.headers))return`server "${name}": headers must map names to strings`;let oauthError=validateOAuth(value.oauth);if(oauthError)return`server "${name}": ${oauthError}`;if(value.auth!==void 0){if(!isRecord(value.auth)||typeof value.auth.provider!="string"||!value.auth.provider)return`server "${name}": auth.provider must be a provider name`;let url=new URL(value.url);if(url.protocol!=="https:"&&!LOOPBACK_HOSTS.includes(url.hostname))return`server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`}return value}return typeof value.command=="string"&&(type===void 0||type==="stdio")?value.args!==void 0&&!(Array.isArray(value.args)&&value.args.every(arg=>typeof arg=="string"))?`server "${name}": args must be an array of strings`:value.env!==void 0&&!isStringRecord(value.env)?`server "${name}": env must map names to strings`:value.cwd!==void 0&&typeof value.cwd!="string"?`server "${name}": cwd must be a string`:value:`server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`}var McpServerRegistry=class{servers=new Map;changeListener;register(server){this.servers.set(server.name,server),this.changeListener?.()}unregister(name,extensionPath){this.servers.get(name)?.extensionPath===extensionPath&&(this.servers.delete(name),this.changeListener?.())}get(name){return this.servers.get(name)}list(){return[...this.servers.values()].map(server=>({...server,config:structuredClone(server.config)}))}setChangeListener(listener){this.changeListener=listener}};var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,join as join2}from"node:path";import{lstatSync,realpathSync}from"node:fs";import{homedir}from"node:os";import{isAbsolute,join,parse}from"node:path";var realpathNative=realpathSync.native;function errorCode(error){return typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0}function resolveRealSegment(prefix,segment){let candidate=join(prefix,segment);if(candidate.includes("\\"))try{return lstatSync(candidate).isSymbolicLink()?{ok:!1,missing:!1,reason:`refusing to follow ${JSON.stringify(candidate)}: a symbolic link named through a backslash cannot be resolved on every runtime`}:{ok:!0,path:candidate}}catch(error){return{ok:!1,missing:errorCode(error)==="ENOENT",reason:`${error.message}`}}try{return{ok:!0,path:realpathNative(candidate)}}catch(error){return{ok:!1,missing:errorCode(error)==="ENOENT",reason:`${error.message}`}}}function resolveRealPrefix(path){let normalized=normalizePath(path,{expandTilde:!1}),expanded=normalized==="~"||normalized.startsWith("~/")?homedir()+normalized.slice(1):normalized,root=isAbsolute(expanded)?parse(expanded).root:"",real=root||process.cwd(),unresolved=[],failed=!1;for(let segment of expanded.slice(root.length).split("/")){if(segment===""||segment===".")continue;if(unresolved.length>0){segment===".."?unresolved.pop():unresolved.push(segment);continue}let resolved=resolveRealSegment(real,segment);resolved.ok?real=resolved.path:(failed=!0,unresolved.push(segment))}return{real,unresolved,failed}}function spellRealPrefix({real,unresolved}){return unresolved.length===0?real:join(real,...unresolved)}function realPathStrict(path){let{real,failed}=resolveRealPrefix(path);return failed?void 0:real}function trustKeyPath(path){return spellRealPrefix(resolveRealPrefix(path))}function comparablePath(path){return spellRealPrefix(resolveRealPrefix(path))}function realHomeDir(){return realPathStrict(process.env.HOME||homedir())}var TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES=["settings.json","mcp.json","permissions.yml","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES=[join2(".agents","skills"),join2(CONFIG_DIR_NAME,"agents"),join2(CONFIG_DIR_NAME,"workflows")];function trustKeyEscapesProjectConfigDir(cwd){let lexicalCwd=resolvePath(cwd);return hasProjectConfigResources(lexicalCwd)&&realPathStrict(lexicalCwd)!==realPathStrict(cwd)}function findNearestTrustEntry(data,cwd){let prefix=resolveRealPrefix(cwd),trustBinds=!prefix.failed&&!trustKeyEscapesProjectConfigDir(cwd),currentDir=spellRealPrefix(prefix);for(;;){let value=data[currentDir];if(value===!1||value===!0&&trustBinds)return{path:currentDir,decision:value};let parentDir=dirname(currentDir);if(parentDir===currentDir)return null;currentDir=parentDir}}function getProjectTrustParentPath(cwd){let trustPath=trustKeyPath(cwd),parentDir=dirname(trustPath);return parentDir===trustPath?void 0:parentDir}function getProjectTrustOptions(cwd,options){let trustPath=trustKeyPath(cwd),trustOptions=[{label:"Trust",trusted:!0,updates:[{path:trustPath,decision:!0}],savedPath:trustPath}],parentPath=getProjectTrustParentPath(cwd);return parentPath!==void 0&&trustOptions.push({label:`Trust parent folder (${parentPath})`,trusted:!0,updates:[{path:parentPath,decision:!0},{path:trustPath,decision:null}],savedPath:parentPath}),options?.includeSessionOnly&&trustOptions.push({label:"Trust (this session only)",trusted:!0,updates:[]}),trustOptions.push({label:"Do not trust",trusted:!1,updates:[{path:trustPath,decision:!1}],savedPath:trustPath}),options?.includeSessionOnly&&trustOptions.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),trustOptions}function readTrustFile(path){if(!existsSync(path))return{};let parsed;try{parsed=JSON.parse(stripBom(readFileSync(path,"utf-8")))}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Failed to read trust store ${path}: ${message}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`Invalid trust store ${path}: expected an object`);let data={};for(let[key,value]of Object.entries(parsed)){if(value!==!0&&value!==!1&&value!==null)throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);data[key]=value}return data}function writeTrustFile(path,data){let sorted={};for(let key of Object.keys(data).sort()){let value=data[key];(value===!0||value===!1||value===null)&&(sorted[key]=value)}mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(sorted,null,2)}
3
3
  `,"utf-8")}function acquireTrustLockSync(path){let trustDir=dirname(path);mkdirSync(trustDir,{recursive:!0});let maxAttempts=10,delayMs=20,lastError;for(let attempt=1;attempt<=maxAttempts;attempt++)try{return import_proper_lockfile.default.lockSync(trustDir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<delayMs;);}throw lastError instanceof Error?lastError:new Error("Failed to acquire trust store lock")}function withTrustFileLock(path,fn){let release=acquireTrustLockSync(path);try{return fn()}finally{release()}}function hasTrustRequiringProjectResources(cwd){let realCwd=realPathStrict(cwd);if(realCwd===void 0)return!0;let realHome=realHomeDir(),userAgentsSkillsDir=realHome===void 0?void 0:join2(realHome,".agents","skills");if(hasProjectResourcesAtOrAbove(realCwd,userAgentsSkillsDir))return!0;let lexicalCwd=resolvePath(cwd);return lexicalCwd!==realCwd&&hasProjectConfigResources(lexicalCwd)}function hasProjectConfigResources(dir){let configDir=join2(dir,CONFIG_DIR_NAME);return TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some(entry=>existsSync(join2(configDir,entry)))}function hasProjectResourcesAtOrAbove(startDir,userAgentsSkillsDir){if(hasProjectConfigResources(startDir))return!0;let currentDir=startDir;for(;;){for(let entry of TRUST_REQUIRING_ANCESTOR_PROJECT_RESOURCES){let resourceDir=join2(currentDir,entry);if(resourceDir!==userAgentsSkillsDir&&existsSync(resourceDir))return!0}let parentDir=dirname(currentDir);if(parentDir===currentDir)return!1;currentDir=parentDir}}var ProjectTrustStore=class{trustPath;constructor(agentDir){this.trustPath=join2(resolvePath(agentDir),"trust.json")}get(cwd){return this.getEntry(cwd)?.decision??null}getEntry(cwd){return withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);return findNearestTrustEntry(data,cwd)})}set(cwd,decision){this.setMany([{path:cwd,decision}])}setMany(decisions){withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);for(let{path,decision}of decisions){let key=trustKeyPath(path);decision===null?delete data[key]:data[key]=decision}writeTrustFile(this.trustPath,data)})}};import{spawn}from"node:child_process";function openBrowser(target){let[cmd,args]=process.platform==="darwin"?["open",[target]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",target]]:["xdg-open",[target]];spawn(cmd,args,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname2,join as join3}from"node:path";function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readConfigFile(path,scope,state){let{servers,errors}=state;if(!existsSync2(path))return;let parsed;try{parsed=JSON.parse(readFileSync2(path,"utf8"))}catch(error){errors.push(`${path}: ${error instanceof Error?error.message:String(error)}`);return}if(!isRecord2(parsed)||parsed.mcpServers!==void 0&&!isRecord2(parsed.mcpServers)){errors.push(`${path}: expected an object with an "mcpServers" object`);return}typeof parsed.autoEnableCodemode=="boolean"?state.autoEnableCodemode=parsed.autoEnableCodemode:parsed.autoEnableCodemode!==void 0&&errors.push(`${path}: autoEnableCodemode must be a boolean`);for(let[name,value]of Object.entries(parsed.mcpServers??{})){let config=validateMcpServerConfig(name,value);if(typeof config=="string"){errors.push(`${path}: ${config}`);continue}let clash=[...servers.keys()].find(other=>other!==name&&mcpNamespace(other)===mcpNamespace(name));if(clash){errors.push(`${path}: server "${name}" conflicts with "${clash}"`);continue}if(scope==="project"&&"url"in config&&config.auth){errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);continue}servers.set(name,{name,config,source:path,scope})}}function loadMcpConfig(options){let state={servers:new Map,errors:[]};return readConfigFile(join3(options.agentDir,"mcp.json"),"global",state),options.projectTrusted&&readConfigFile(join3(options.cwd,CONFIG_DIR_NAME,"mcp.json"),"project",state),{servers:[...state.servers.values()],...state.autoEnableCodemode===void 0?{}:{autoEnableCodemode:state.autoEnableCodemode},errors:state.errors}}function updateMcpServerConfig(path,name,patch){editMcpServers(path,servers=>{let server=servers?.[name];if(!isRecord2(server))throw new Error(`${path} does not define MCP server "${name}"`);return patch.enabled!==void 0&&(patch.enabled?delete server.enabled:server.enabled=!1),patch.exposure!==void 0&&(patch.exposure==="codemode"?delete server.exposure:server.exposure=patch.exposure),!0})}function addMcpServerConfig(path,name,config){let replaced=!1;return editMcpServers(path,(servers,parsed)=>{let target=servers??{};return replaced=target[name]!==void 0,target[name]=config,parsed.mcpServers=target,!0}),replaced}function removeMcpServerConfig(path,name){if(!existsSync2(path))return!1;let removed=!1;return editMcpServers(path,servers=>!servers||servers[name]===void 0?!1:(delete servers[name],removed=!0,!0)),removed}function editMcpServers(path,edit){let text=existsSync2(path)?readFileSync2(path,"utf8"):void 0,parsed=text===void 0?{}:JSON.parse(text);if(!isRecord2(parsed)||parsed.mcpServers!==void 0&&!isRecord2(parsed.mcpServers))throw new Error(`${path}: expected an object with an "mcpServers" object`);let servers=isRecord2(parsed.mcpServers)?parsed.mcpServers:void 0;if(!edit(servers,parsed))return;let indent=text&&/^([ \t]+)\S/m.exec(text)?.[1]||" ";mkdirSync2(dirname2(path),{recursive:!0}),writeFileSync2(path,`${JSON.stringify(parsed,null,indent)}
4
4
  `)}export{realPathStrict,comparablePath,realHomeDir,mcpNamespace,getMcpToolExposure,validateMcpServerConfig,McpServerRegistry,getProjectTrustOptions,hasTrustRequiringProjectResources,ProjectTrustStore,openBrowser,loadMcpConfig,updateMcpServerConfig,addMcpServerConfig,removeMcpServerConfig};