zidane 7.2.4 → 8.0.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 (376) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +34 -6
  3. package/dist/{acp-D-tVyUjw.js → acp-DQDhi2dj.js} +230 -77
  4. package/dist/acp-DQDhi2dj.js.map +1 -0
  5. package/dist/acp-cli.d.ts +1 -1
  6. package/dist/acp-cli.js +9 -66
  7. package/dist/acp-cli.js.map +1 -1
  8. package/dist/acp.d.ts +10 -590
  9. package/dist/acp.d.ts.map +1 -1
  10. package/dist/acp.js +3 -3
  11. package/dist/{agent-D0zZnGbt.js → agent-DSLNmBp0.js} +14401 -13214
  12. package/dist/agent-DSLNmBp0.js.map +1 -0
  13. package/dist/agent.d.ts +1 -1
  14. package/dist/agent.js +3 -2
  15. package/dist/aliasing-lVFbm81n.js +217 -0
  16. package/dist/aliasing-lVFbm81n.js.map +1 -0
  17. package/dist/{anthropic-C2aole0G.js → anthropic-CD00LhUP.js} +1442 -1264
  18. package/dist/anthropic-CD00LhUP.js.map +1 -0
  19. package/dist/artifacts-CV2hUKnL.js.map +1 -1
  20. package/dist/{atomic-write-B7zr1ddF.js → atomic-write-Ijgf2Mhc.js} +13 -3
  21. package/dist/atomic-write-Ijgf2Mhc.js.map +1 -0
  22. package/dist/call-tool-dHlbGOIY.js +70 -0
  23. package/dist/call-tool-dHlbGOIY.js.map +1 -0
  24. package/dist/chat/pure.d.ts +372 -6
  25. package/dist/chat/pure.d.ts.map +1 -1
  26. package/dist/chat/pure.js +35 -244
  27. package/dist/chat/pure.js.map +1 -1
  28. package/dist/{approvals-DKaJZYlm.js → chat-JPJJ8uu5.js} +15879 -14631
  29. package/dist/chat-JPJJ8uu5.js.map +1 -0
  30. package/dist/chat.d.ts +4 -6
  31. package/dist/chat.js +23 -12
  32. package/dist/cli-shared-C-YCaglL.js +159 -0
  33. package/dist/cli-shared-C-YCaglL.js.map +1 -0
  34. package/dist/client-core-BQSyDALT.d.ts +2115 -0
  35. package/dist/client-core-BQSyDALT.d.ts.map +1 -0
  36. package/dist/codemode-worker.d.ts +1 -0
  37. package/dist/codemode-worker.js +155 -0
  38. package/dist/codemode-worker.js.map +1 -0
  39. package/dist/codemode.d.ts +352 -0
  40. package/dist/codemode.d.ts.map +1 -0
  41. package/dist/codemode.js +5 -0
  42. package/dist/connection-Dr-Js4yZ.d.ts +28 -0
  43. package/dist/connection-Dr-Js4yZ.d.ts.map +1 -0
  44. package/dist/connection-loop-gdh22LTI.js +112 -0
  45. package/dist/connection-loop-gdh22LTI.js.map +1 -0
  46. package/dist/context-segments-BHKlagL6.js +1016 -0
  47. package/dist/context-segments-BHKlagL6.js.map +1 -0
  48. package/dist/{context-transport-T_6AYIvy.js → context-transport-DSMTUsK1.js} +3 -3
  49. package/dist/{context-transport-T_6AYIvy.js.map → context-transport-DSMTUsK1.js.map} +1 -1
  50. package/dist/contexts/daytona.d.ts +19 -8
  51. package/dist/contexts/daytona.d.ts.map +1 -1
  52. package/dist/contexts/daytona.js +1 -440
  53. package/dist/contexts/docker.d.ts +36 -7
  54. package/dist/contexts/docker.d.ts.map +1 -1
  55. package/dist/contexts/docker.js +1 -456
  56. package/dist/contexts/e2b.d.ts +68 -13
  57. package/dist/contexts/e2b.d.ts.map +1 -1
  58. package/dist/contexts/e2b.js +1 -382
  59. package/dist/contexts/sandbox.d.ts +1 -1
  60. package/dist/contexts/sandbox.js +5 -0
  61. package/dist/contexts/sandbox.js.map +1 -1
  62. package/dist/{contexts-CRE9pw07.js → contexts-d7UolYot.js} +1059 -524
  63. package/dist/contexts-d7UolYot.js.map +1 -0
  64. package/dist/contexts.d.ts +3 -3
  65. package/dist/contexts.js +1 -1
  66. package/dist/cred-keys-GpBg71cP.js +105 -0
  67. package/dist/cred-keys-GpBg71cP.js.map +1 -0
  68. package/dist/{auth-BG2rVKSt.js → credentials-JttEuRON.js} +55 -206
  69. package/dist/credentials-JttEuRON.js.map +1 -0
  70. package/dist/{cursor-iojRXHF9.js → cursor-CdjaQTBW.js} +3 -3
  71. package/dist/{cursor-iojRXHF9.js.map → cursor-CdjaQTBW.js.map} +1 -1
  72. package/dist/daemon-cli.d.ts +1 -1
  73. package/dist/daemon-cli.js +3 -2
  74. package/dist/daemon-cli.js.map +1 -1
  75. package/dist/daytona-DG3omipZ.js +513 -0
  76. package/dist/daytona-DG3omipZ.js.map +1 -0
  77. package/dist/defaults-Cx3zvDOV.js +23 -0
  78. package/dist/defaults-Cx3zvDOV.js.map +1 -0
  79. package/dist/dispatcher-BMlu2BmZ.js +4941 -0
  80. package/dist/dispatcher-BMlu2BmZ.js.map +1 -0
  81. package/dist/docker-BZhMMJUp.js +727 -0
  82. package/dist/docker-BZhMMJUp.js.map +1 -0
  83. package/dist/e2b-CEVOdRib.js +480 -0
  84. package/dist/e2b-CEVOdRib.js.map +1 -0
  85. package/dist/edit-utils-EGosADZq.js +234 -0
  86. package/dist/edit-utils-EGosADZq.js.map +1 -0
  87. package/dist/environment-8wsKE2Ln.js +214 -0
  88. package/dist/environment-8wsKE2Ln.js.map +1 -0
  89. package/dist/eval-BNcvle_J.js +1595 -0
  90. package/dist/eval-BNcvle_J.js.map +1 -0
  91. package/dist/eval.d.ts +2 -2
  92. package/dist/eval.js +1 -1489
  93. package/dist/executor-Cx5-8yqi.js +621 -0
  94. package/dist/executor-Cx5-8yqi.js.map +1 -0
  95. package/dist/extension-authoring-DyGGmq9V.js +385 -0
  96. package/dist/extension-authoring-DyGGmq9V.js.map +1 -0
  97. package/dist/extensions.d.ts +2 -2
  98. package/dist/extensions.js +3 -3
  99. package/dist/{fetch-url-DX75gpL0.js → fetch-url-Ct2TjDWt.js} +4 -4
  100. package/dist/{fetch-url-DX75gpL0.js.map → fetch-url-Ct2TjDWt.js.map} +1 -1
  101. package/dist/{format-BF745pLL.js → format-C2NQEVUH.js} +39 -2
  102. package/dist/format-C2NQEVUH.js.map +1 -0
  103. package/dist/format-bytes-C7tfc3Zm.js +55 -0
  104. package/dist/format-bytes-C7tfc3Zm.js.map +1 -0
  105. package/dist/headless-C_rNUuYC.js +960 -0
  106. package/dist/headless-C_rNUuYC.js.map +1 -0
  107. package/dist/headless.d.ts +1 -1
  108. package/dist/headless.js +1 -413
  109. package/dist/{history-search-C4bk1Wz_.js → history-search-CcYzF8-0.js} +7 -3
  110. package/dist/history-search-CcYzF8-0.js.map +1 -0
  111. package/dist/history-search-worker.d.ts +1 -1
  112. package/dist/history-search-worker.js +1 -1
  113. package/dist/host-D7NrI03V.js +378 -0
  114. package/dist/host-D7NrI03V.js.map +1 -0
  115. package/dist/host-signals-BcP5QKUD.js +118 -0
  116. package/dist/host-signals-BcP5QKUD.js.map +1 -0
  117. package/dist/identity-CwfO8K-t.js +26 -0
  118. package/dist/identity-CwfO8K-t.js.map +1 -0
  119. package/dist/{index-BgN1T3lk.d.ts → index-BGe1fQT7.d.ts} +10987 -9320
  120. package/dist/index-BGe1fQT7.d.ts.map +1 -0
  121. package/dist/index-BVQsIKGn.d.ts +448 -0
  122. package/dist/index-BVQsIKGn.d.ts.map +1 -0
  123. package/dist/{index-C6NEd5y_.d.ts → index-CHABJd-L.d.ts} +3386 -502
  124. package/dist/index-CHABJd-L.d.ts.map +1 -0
  125. package/dist/{index-C37_ppWv.d.ts → index-D6a7qXpg.d.ts} +2 -3
  126. package/dist/index-D6a7qXpg.d.ts.map +1 -0
  127. package/dist/index.d.ts +6 -6
  128. package/dist/index.js +27 -23
  129. package/dist/{completion-core-BRo86R_L.js → inline-ghost-BVRQeGoL.js} +50 -2
  130. package/dist/inline-ghost-BVRQeGoL.js.map +1 -0
  131. package/dist/ipc/remote.d.ts +313 -0
  132. package/dist/ipc/remote.d.ts.map +1 -0
  133. package/dist/ipc/remote.js +4 -0
  134. package/dist/ipc.d.ts +6 -964
  135. package/dist/ipc.js +403 -4
  136. package/dist/ipc.js.map +1 -0
  137. package/dist/{isolation-Kfoof0MM.d.ts → isolation-D9L650W5.d.ts} +100 -15
  138. package/dist/isolation-D9L650W5.d.ts.map +1 -0
  139. package/dist/json-rpc--HXQti1E.js +350 -0
  140. package/dist/json-rpc--HXQti1E.js.map +1 -0
  141. package/dist/links-j8rED1sR.js +603 -0
  142. package/dist/links-j8rED1sR.js.map +1 -0
  143. package/dist/local-terminal-D8QThwo_.js +252 -0
  144. package/dist/local-terminal-D8QThwo_.js.map +1 -0
  145. package/dist/{logger--C1VQjwJ.js → logger-Gtqlayx8.js} +199 -173
  146. package/dist/logger-Gtqlayx8.js.map +1 -0
  147. package/dist/logs-view-CWG8aUAG.js.map +1 -1
  148. package/dist/{mcp-CgNd-f3F.js → mcp-_wecH9Qe.js} +608 -562
  149. package/dist/mcp-_wecH9Qe.js.map +1 -0
  150. package/dist/mcp.d.ts +2 -2
  151. package/dist/mcp.js +2 -2
  152. package/dist/media-sniff-UKijEaiQ.js.map +1 -1
  153. package/dist/{messages-2jcOA_5R.js → messages-BqiwcD2Q.js} +1017 -1014
  154. package/dist/messages-BqiwcD2Q.js.map +1 -0
  155. package/dist/{oauth-DxHO17JE.js → oauth-Px_pBB9W.js} +5 -5
  156. package/dist/{oauth-DxHO17JE.js.map → oauth-Px_pBB9W.js.map} +1 -1
  157. package/dist/{openai-compat-Dy56weK8.js → openai-compat-CFrpH7uq.js} +432 -589
  158. package/dist/openai-compat-CFrpH7uq.js.map +1 -0
  159. package/dist/orchestration-BCGmB8Ps.js +511 -0
  160. package/dist/orchestration-BCGmB8Ps.js.map +1 -0
  161. package/dist/output/stream-json.d.ts +1 -2
  162. package/dist/output/stream-json.d.ts.map +1 -1
  163. package/dist/output/stream-json.js +1 -1
  164. package/dist/output/terminal.d.ts +1 -2
  165. package/dist/output/terminal.d.ts.map +1 -1
  166. package/dist/output/terminal.js +13 -7
  167. package/dist/output/terminal.js.map +1 -1
  168. package/dist/{plugins-gbI7SBA6.js → plugins-DS7mahzZ.js} +20 -101
  169. package/dist/plugins-DS7mahzZ.js.map +1 -0
  170. package/dist/plugins.d.ts +1 -1
  171. package/dist/plugins.js +1 -2
  172. package/dist/prelude-Cxo4t74B.js +517 -0
  173. package/dist/prelude-Cxo4t74B.js.map +1 -0
  174. package/dist/presets.d.ts +1 -1
  175. package/dist/presets.js +1 -2
  176. package/dist/project-root-B8zADr4o.js +167 -0
  177. package/dist/project-root-B8zADr4o.js.map +1 -0
  178. package/dist/project-user-paths-BSgtrRxl.js +58 -0
  179. package/dist/project-user-paths-BSgtrRxl.js.map +1 -0
  180. package/dist/{prompts-Pqc3JdW_.d.ts → prompts-DYcvqShf.d.ts} +14 -11
  181. package/dist/prompts-DYcvqShf.d.ts.map +1 -0
  182. package/dist/protocol-DnhqqSmE.js +13 -0
  183. package/dist/protocol-DnhqqSmE.js.map +1 -0
  184. package/dist/providers/anthropic.d.ts +2 -2
  185. package/dist/providers/anthropic.js +1 -2
  186. package/dist/providers/arcee.d.ts +1 -1
  187. package/dist/providers/arcee.js +1 -1
  188. package/dist/providers/baseten.d.ts +1 -1
  189. package/dist/providers/baseten.js +1 -1
  190. package/dist/providers/cerebras.d.ts +1 -1
  191. package/dist/providers/cerebras.js +3 -2
  192. package/dist/providers/cerebras.js.map +1 -1
  193. package/dist/providers/local.d.ts +1 -1
  194. package/dist/providers/local.js +1 -1
  195. package/dist/providers/openai-compat.d.ts +1 -1
  196. package/dist/providers/openai-compat.js +1 -2
  197. package/dist/providers/openai.d.ts +1 -1
  198. package/dist/providers/openai.js +15 -12
  199. package/dist/providers/openai.js.map +1 -1
  200. package/dist/providers/openrouter.d.ts +1 -1
  201. package/dist/providers/openrouter.js +3 -2
  202. package/dist/providers/openrouter.js.map +1 -1
  203. package/dist/providers/xai.d.ts +1 -1
  204. package/dist/providers/xai.js +3 -3
  205. package/dist/{providers-BVhnFyiY.js → providers-XUR7F4Hi.js} +4 -4
  206. package/dist/{providers-BVhnFyiY.js.map → providers-XUR7F4Hi.js.map} +1 -1
  207. package/dist/providers.d.ts +1 -1
  208. package/dist/providers.js +4 -4
  209. package/dist/registry-D6ShBWJU.js +5234 -0
  210. package/dist/registry-D6ShBWJU.js.map +1 -0
  211. package/dist/remote-hosts-BtA_9ZGp.js +97 -0
  212. package/dist/remote-hosts-BtA_9ZGp.js.map +1 -0
  213. package/dist/restate.d.ts +2 -3
  214. package/dist/restate.d.ts.map +1 -1
  215. package/dist/restate.js +631 -572
  216. package/dist/restate.js.map +1 -1
  217. package/dist/run-summary-CklLiZ4y.js +288 -0
  218. package/dist/run-summary-CklLiZ4y.js.map +1 -0
  219. package/dist/{sandbox-BH0WQkXn.d.ts → sandbox-C5dR5DwQ.d.ts} +6 -3
  220. package/dist/sandbox-C5dR5DwQ.d.ts.map +1 -0
  221. package/dist/session/sqlite.d.ts +1 -2
  222. package/dist/session/sqlite.d.ts.map +1 -1
  223. package/dist/session/sqlite.js +1 -616
  224. package/dist/session-factory-BUGY5P40.js +1576 -0
  225. package/dist/session-factory-BUGY5P40.js.map +1 -0
  226. package/dist/{session-BqRP1hS7.js → session-xh9JXu6i.js} +94 -52
  227. package/dist/session-xh9JXu6i.js.map +1 -0
  228. package/dist/session.d.ts +1 -1
  229. package/dist/session.js +2 -2
  230. package/dist/settings-keys-Ckf29NeM.js +677 -0
  231. package/dist/settings-keys-Ckf29NeM.js.map +1 -0
  232. package/dist/shell-path-Dqaoow2J.js +412 -0
  233. package/dist/shell-path-Dqaoow2J.js.map +1 -0
  234. package/dist/{skills-BC3dodWp.js → skills-DKqZJm4X.js} +430 -470
  235. package/dist/skills-DKqZJm4X.js.map +1 -0
  236. package/dist/skills.d.ts +2 -2
  237. package/dist/skills.js +1 -2
  238. package/dist/source-mPExaUm8.js +381 -0
  239. package/dist/source-mPExaUm8.js.map +1 -0
  240. package/dist/sqlite-DV1DQzN2.js +698 -0
  241. package/dist/sqlite-DV1DQzN2.js.map +1 -0
  242. package/dist/{src-CkNQKFKr.js → src-BRMYRJib.js} +903 -1121
  243. package/dist/src-BRMYRJib.js.map +1 -0
  244. package/dist/{stdio-DPpBDPx5.js → stdio-C6YyoW3I.js} +4 -4
  245. package/dist/{stdio-DPpBDPx5.js.map → stdio-C6YyoW3I.js.map} +1 -1
  246. package/dist/{stdio-loader-Bbx19dMZ.js → stdio-loader-C830Vg-Z.js} +4 -4
  247. package/dist/{stdio-loader-Bbx19dMZ.js.map → stdio-loader-C830Vg-Z.js.map} +1 -1
  248. package/dist/system-prompt-MNVHatSD.d.ts.map +1 -1
  249. package/dist/timeout-DEaqslLO.d.ts.map +1 -1
  250. package/dist/todo-edits-Dn251YUP.js +1790 -0
  251. package/dist/todo-edits-Dn251YUP.js.map +1 -0
  252. package/dist/{turn-operations-DrbJlpq9.js → tool-formatters-IQFDrdrs.js} +1456 -2120
  253. package/dist/tool-formatters-IQFDrdrs.js.map +1 -0
  254. package/dist/tool-state-Dku6YqAB.js +989 -0
  255. package/dist/tool-state-Dku6YqAB.js.map +1 -0
  256. package/dist/tools/fetch-url.d.ts +1 -2
  257. package/dist/tools/fetch-url.d.ts.map +1 -1
  258. package/dist/tools/fetch-url.js +1 -2
  259. package/dist/tools/prompts.d.ts +1 -1
  260. package/dist/tools/prompts.js +7 -7
  261. package/dist/tools/prompts.js.map +1 -1
  262. package/dist/tools/web-search.d.ts +1 -2
  263. package/dist/tools/web-search.d.ts.map +1 -1
  264. package/dist/tools/web-search.js +2 -2
  265. package/dist/tools/web-search.js.map +1 -1
  266. package/dist/tools-_DnT3AGM.js +578 -0
  267. package/dist/tools-_DnT3AGM.js.map +1 -0
  268. package/dist/tools.d.ts +3 -3
  269. package/dist/tools.js +4 -2
  270. package/dist/tui.d.ts +534 -517
  271. package/dist/tui.d.ts.map +1 -1
  272. package/dist/tui.js +34933 -27242
  273. package/dist/tui.js.map +1 -1
  274. package/dist/turn-operations-B8sokwi5.js +333 -0
  275. package/dist/turn-operations-B8sokwi5.js.map +1 -0
  276. package/dist/turn-operations-DQX5ZZni.d.ts +3089 -0
  277. package/dist/turn-operations-DQX5ZZni.d.ts.map +1 -0
  278. package/dist/types-C7ZFOztE.d.ts +132 -0
  279. package/dist/types-C7ZFOztE.d.ts.map +1 -0
  280. package/dist/types-CH5XpIHw.js +114 -0
  281. package/dist/types-CH5XpIHw.js.map +1 -0
  282. package/dist/{types-CWgENVLY.js → types-Cu0ZGDu9.js} +10 -6
  283. package/dist/types-Cu0ZGDu9.js.map +1 -0
  284. package/dist/types-IqegbJEE.d.ts +624 -0
  285. package/dist/types-IqegbJEE.d.ts.map +1 -0
  286. package/dist/types.d.ts +4 -4
  287. package/dist/types.js +1 -1
  288. package/dist/url-D8HCl65b.js +1259 -0
  289. package/dist/url-D8HCl65b.js.map +1 -0
  290. package/dist/wasm-BVT-j5cl.js +33 -0
  291. package/dist/wasm-BVT-j5cl.js.map +1 -0
  292. package/dist/workspace-exec-stream-SV2R9d5S.js +355 -0
  293. package/dist/workspace-exec-stream-SV2R9d5S.js.map +1 -0
  294. package/dist/ws-CIHMvlSh.js +952 -0
  295. package/dist/ws-CIHMvlSh.js.map +1 -0
  296. package/dist/ws-client-N7NxzvQp.js +230 -0
  297. package/dist/ws-client-N7NxzvQp.js.map +1 -0
  298. package/dist/{xai-CazjStOK.js → xai-CvJTeLrI.js} +165 -5
  299. package/dist/xai-CvJTeLrI.js.map +1 -0
  300. package/dist/xdg-zweed0-t.js +117 -0
  301. package/dist/xdg-zweed0-t.js.map +1 -0
  302. package/docs/ACP.md +52 -0
  303. package/docs/ARCHITECTURE.md +103 -6
  304. package/docs/ARTIFACTS.md +8 -4
  305. package/docs/CHAT.md +165 -14
  306. package/docs/EXECUTION_CONTEXT.md +8 -0
  307. package/docs/EXTENSIONS.md +123 -2
  308. package/docs/HEADLESS.md +2 -0
  309. package/docs/IPC.md +775 -64
  310. package/docs/MACHINES.md +456 -0
  311. package/docs/PANELS.md +3 -0
  312. package/docs/README.md +4 -0
  313. package/docs/RESTATE.md +3 -2
  314. package/docs/RUN_IN_BACKGROUND.md +10 -2
  315. package/docs/SERVER.md +1085 -0
  316. package/docs/SKILL.md +6 -1
  317. package/docs/TERMINAL.md +75 -0
  318. package/docs/TUI.md +65 -14
  319. package/package.json +58 -26
  320. package/scripts/eval.ts +4 -0
  321. package/dist/acp-D-tVyUjw.js.map +0 -1
  322. package/dist/agent-D0zZnGbt.js.map +0 -1
  323. package/dist/anthropic-C2aole0G.js.map +0 -1
  324. package/dist/approvals-DKaJZYlm.js.map +0 -1
  325. package/dist/atomic-write-B7zr1ddF.js.map +0 -1
  326. package/dist/auth-BG2rVKSt.js.map +0 -1
  327. package/dist/completion-core-BRo86R_L.js.map +0 -1
  328. package/dist/contexts/daytona.js.map +0 -1
  329. package/dist/contexts/docker.js.map +0 -1
  330. package/dist/contexts/e2b.js.map +0 -1
  331. package/dist/contexts-CRE9pw07.js.map +0 -1
  332. package/dist/eval.js.map +0 -1
  333. package/dist/format-BF745pLL.js.map +0 -1
  334. package/dist/glob-DluQFSw1.js +0 -270
  335. package/dist/glob-DluQFSw1.js.map +0 -1
  336. package/dist/headless.js.map +0 -1
  337. package/dist/history-search-C4bk1Wz_.js.map +0 -1
  338. package/dist/index-BgN1T3lk.d.ts.map +0 -1
  339. package/dist/index-C37_ppWv.d.ts.map +0 -1
  340. package/dist/index-C6NEd5y_.d.ts.map +0 -1
  341. package/dist/ipc-zVSyo6K1.js +0 -331
  342. package/dist/ipc-zVSyo6K1.js.map +0 -1
  343. package/dist/ipc.d.ts.map +0 -1
  344. package/dist/isolation-Kfoof0MM.d.ts.map +0 -1
  345. package/dist/json-rpc-rSWMUh9b.js +0 -192
  346. package/dist/json-rpc-rSWMUh9b.js.map +0 -1
  347. package/dist/logger--C1VQjwJ.js.map +0 -1
  348. package/dist/mcp-CgNd-f3F.js.map +0 -1
  349. package/dist/messages-2jcOA_5R.js.map +0 -1
  350. package/dist/openai-compat-Dy56weK8.js.map +0 -1
  351. package/dist/output-cap-C9zukcCj.js +0 -100
  352. package/dist/output-cap-C9zukcCj.js.map +0 -1
  353. package/dist/panels-B6gRk4bf.js +0 -789
  354. package/dist/panels-B6gRk4bf.js.map +0 -1
  355. package/dist/plugins-gbI7SBA6.js.map +0 -1
  356. package/dist/prompts-Pqc3JdW_.d.ts.map +0 -1
  357. package/dist/run-summary-BU_NgwUT.js +0 -269
  358. package/dist/run-summary-BU_NgwUT.js.map +0 -1
  359. package/dist/sandbox-BH0WQkXn.d.ts.map +0 -1
  360. package/dist/session/sqlite.js.map +0 -1
  361. package/dist/session-BqRP1hS7.js.map +0 -1
  362. package/dist/shell-path-h5czzllR.js +0 -1549
  363. package/dist/shell-path-h5czzllR.js.map +0 -1
  364. package/dist/skills-BC3dodWp.js.map +0 -1
  365. package/dist/src-CkNQKFKr.js.map +0 -1
  366. package/dist/todo-edits-UOwgxGKu.js +0 -528
  367. package/dist/todo-edits-UOwgxGKu.js.map +0 -1
  368. package/dist/tool-formatters-DoRLnfuD.d.ts +0 -759
  369. package/dist/tool-formatters-DoRLnfuD.d.ts.map +0 -1
  370. package/dist/transcript-anchors-BeudMbXx.d.ts +0 -1762
  371. package/dist/transcript-anchors-BeudMbXx.d.ts.map +0 -1
  372. package/dist/turn-operations-C8bMBDl_.d.ts +0 -1258
  373. package/dist/turn-operations-C8bMBDl_.d.ts.map +0 -1
  374. package/dist/turn-operations-DrbJlpq9.js.map +0 -1
  375. package/dist/types-CWgENVLY.js.map +0 -1
  376. package/dist/xai-CazjStOK.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"panels-B6gRk4bf.js","names":[],"sources":["../src/tools/edit-utils.ts","../src/chat/context-breakdown.ts","../src/chat/context-segments.ts","../src/chat/cred-keys.ts","../src/extensions/panels.ts"],"sourcesContent":["/**\n * Internal helpers shared between the `edit` and `multi_edit` tools.\n *\n * Not part of the public API — intentionally not re-exported from `tools/index.ts`\n * or the package barrel.\n */\n\n/**\n * Count exact (non-overlapping) occurrences of `needle` in `haystack`.\n * Returns 0 for an empty needle — both edit tools reject empty `old_string`\n * up front, so this branch is defensive rather than semantic.\n */\nexport function countExactMatches(haystack: string, needle: string): number {\n if (needle.length === 0)\n return 0\n let count = 0\n let idx = 0\n while (true) {\n const next = haystack.indexOf(needle, idx)\n if (next === -1)\n break\n count++\n idx = next + needle.length\n }\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Curly-quote normalization + SDK-sanitization fallbacks\n// ---------------------------------------------------------------------------\n//\n// Models can't reliably emit Unicode curly quotes, and the Anthropic API\n// silently sanitizes a handful of XML-like tags before they hit the model\n// (`<name>` → `<n>`, etc.). When `old_string` doesn't match exactly, we retry\n// against the same content with both transforms applied so an \"old_string not\n// found\" failure that's only typographical resolves on the second pass.\n//\n// Mirrors the Claude Code Edit tool's recovery strategy. Verbatim port of the\n// quote constants and the desanitization table; the resolve loop below is\n// reorganized to share state between exact / quote-normalized / desanitized.\n\nexport const LEFT_SINGLE_CURLY_QUOTE = '\\u2018'\nexport const RIGHT_SINGLE_CURLY_QUOTE = '\\u2019'\nexport const LEFT_DOUBLE_CURLY_QUOTE = '\\u201C'\nexport const RIGHT_DOUBLE_CURLY_QUOTE = '\\u201D'\n\n/** Map curly quotes (any of the four) to their straight ASCII equivalents. */\nexport function normalizeQuotes(str: string): string {\n return str\n .replaceAll(LEFT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(RIGHT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '\"')\n .replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '\"')\n}\n\n/**\n * Substitutions Anthropic's API applies to assistant output before the model\n * sees it. The model emits the sanitized form; the file on disk contains the\n * unsanitized form. We undo the substitutions on `old_string` so the search\n * lands on the actual file contents.\n *\n * Verbatim from `claude-code/tools/FileEditTool/utils.ts`.\n */\nconst DESANITIZATIONS: ReadonlyArray<readonly [string, string]> = [\n ['<fnr>', '<function_results>'],\n ['<n>', '<name>'],\n ['</n>', '</name>'],\n ['<o>', '<output>'],\n ['</o>', '</output>'],\n ['<e>', '<error>'],\n ['</e>', '</error>'],\n ['<s>', '<system>'],\n ['</s>', '</system>'],\n ['<r>', '<result>'],\n ['</r>', '</result>'],\n ['< META_START >', '<META_START>'],\n ['< META_END >', '<META_END>'],\n ['< EOT >', '<EOT>'],\n ['< META >', '<META>'],\n ['< SOS >', '<SOS>'],\n ['\\n\\nH:', '\\n\\nHuman:'],\n ['\\n\\nA:', '\\n\\nAssistant:'],\n]\n\n/**\n * Apply the SDK desanitization table to a string. Exported so the edit tools\n * can apply it to `new_string` whenever `old_string` matched via a\n * desanitize-class fallback — keeps the file's unsanitized form on disk\n * instead of writing the model's abbreviated form back.\n */\nexport function desanitize(s: string): string {\n let out = s\n for (const [from, to] of DESANITIZATIONS)\n out = out.replaceAll(from, to)\n return out\n}\n\n/**\n * Strip line-number prefixes from each line of a needle, used as a recovery\n * fallback when the model pastes a `read_file` chunk verbatim into\n * `old_string` — the on-disk file doesn't carry the metadata prefix.\n *\n * Accepts three separator characters so a model that learned on a different\n * agent stack still works here: `\\t` (Claude Code compact, our default),\n * `|`, and `→`. Pattern: optional leading whitespace, 1-9 digits, then one\n * of `\\t | →`. The 9-digit ceiling covers files up to ~1B lines without\n * overshooting into legitimate `\\d{N}<sep>` content like Markdown table\n * cells with long numeric IDs.\n */\nconst LINE_NUMBER_PREFIX_RE = /^[ \\t]*\\d{1,9}[\\t|\\u2192]/gm\nexport function stripLineNumberPrefixes(s: string): string {\n return s.replace(LINE_NUMBER_PREFIX_RE, '')\n}\n\n/**\n * Locate the actual substring in `haystack` that corresponds to `needle`,\n * recovering from typographical mismatch on six escalating fallbacks:\n *\n * 1. Exact substring match (the happy path — no transformation).\n * 2. Curly-quote normalization on both sides — when the model emits straight\n * quotes but the file has curly ones (or vice versa), the slice of the\n * file at the matched position carries the file's actual typography.\n * 3. Anthropic-sanitization undo on the needle — the model's `<n>` becomes\n * the file's `<name>`, etc.\n * 4. Combined: desanitize + quote normalization on the needle.\n * 5. Line-number-prefix strip — when the model pasted a numbered `read_file`\n * chunk verbatim into `old_string` and the file carries no such prefix.\n * 6. Combined: line-number strip + quote normalization — paste-back of a\n * numbered chunk against a file whose typography differs from the model's.\n *\n * Returns `{ actual, occurrences }` — `actual` is the string that exists in\n * the file (use this to do the actual replace; preserves the file's\n * typography). `occurrences` is the count of those matches in the file.\n *\n * Fallbacks 3-4 (desanitize-class) only fire when the transformed needle is\n * UNIQUE in the file — they rewrite the needle's meaning rather than its\n * typography, so an ambiguous match risks silently retargeting the wrong\n * text (see the inline comment at step 3).\n *\n * Returns `null` when no recovery worked.\n */\nexport interface ResolvedMatch {\n actual: string\n occurrences: number\n /** Recovery path — `'exact'` when no transformation was applied. */\n via: 'exact' | 'quotes' | 'desanitize' | 'quotes+desanitize' | 'line-numbers' | 'quotes+line-numbers'\n}\n\n/**\n * Search `target` in `normFile` and slice the matching span out of the\n * original `haystack`, counting all non-overlapping occurrences. `normFile`\n * is the haystack with whatever transform (quotes / desanitize / combined)\n * was applied to make the indices align — slicing the original haystack\n * preserves the file's actual typography so `replace_all` writes back the\n * file's form, not the model's.\n *\n * Pre-condition: `normFile.length === haystack.length` (every transform\n * we use is one-to-one). Returns null on miss.\n */\nfunction locateAndCount(\n haystack: string,\n normFile: string,\n target: string,\n via: ResolvedMatch['via'],\n): ResolvedMatch | null {\n const idx = normFile.indexOf(target)\n if (idx === -1)\n return null\n const actual = haystack.slice(idx, idx + target.length)\n let occ = 0\n let cursor = 0\n while (true) {\n const next = normFile.indexOf(target, cursor)\n if (next === -1)\n break\n occ++\n cursor = next + target.length\n }\n return { actual, occurrences: occ, via }\n}\n\nexport function resolveOldString(haystack: string, needle: string): ResolvedMatch | null {\n // 1. Exact match — happy path.\n const exact = countExactMatches(haystack, needle)\n if (exact > 0)\n return { actual: needle, occurrences: exact, via: 'exact' }\n\n // 2. Curly-quote normalization. Either side can carry curly quotes:\n // model emitted straight + file has curly, OR model emitted curly +\n // file has straight. Normalize both and look there. Slice the original\n // haystack to recover the actual file-side typography.\n const normNeedle = normalizeQuotes(needle)\n const normFile = normalizeQuotes(haystack)\n if (normNeedle !== needle || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, normNeedle, 'quotes')\n if (m)\n return m\n }\n\n // 3. Desanitize the needle — model-side substitution undo (`<n>` → `<name>`,\n // etc.) The file always has the unsanitized form; only the model emits\n // the abbreviated version.\n //\n // Desanitize-class fallbacks additionally require a UNIQUE transformed\n // match. Unlike the quote / line-number transforms (typography-only /\n // verbatim paste-back), this one rewrites the needle's meaning — a model\n // that genuinely meant the literal `<n>` against a file full of `<name>`\n // would otherwise silently retarget every occurrence under `replace_all`.\n // A unique hit bounds the blast radius to one visible replacement.\n const desan = desanitize(needle)\n if (desan !== needle) {\n const desanCount = countExactMatches(haystack, desan)\n if (desanCount === 1)\n return { actual: desan, occurrences: desanCount, via: 'desanitize' }\n }\n\n // 4. Combined: desanitize + quote normalization. Hit when the model\n // emitted both sanitized tokens and straight quotes, but the file has\n // the unsanitized form with curly quotes. Same uniqueness requirement\n // as #3.\n const combo = desanitize(normNeedle)\n if (combo !== needle) {\n const m = locateAndCount(haystack, normFile, combo, 'quotes+desanitize')\n if (m && m.occurrences === 1)\n return m\n }\n\n // 5. Line-number-prefix strip. When `read_file` returns line-numbered\n // output and the model pasted the chunk verbatim into `old_string`,\n // the on-disk file doesn't carry those prefixes. Strip them and\n // retry; the file-side `actual` is the prefix-free needle so the\n // replacement lands on real bytes.\n //\n // Guard against a needle that strips down to whitespace-only (e.g.\n // `1\\t\\n2\\t\\n3\\t` → `\\n\\n`). Searching for `\\n\\n` would match arbitrary\n // blank-line patterns anywhere in the file — a high false-positive risk.\n // Require the stripped needle to carry at least one non-whitespace\n // character before we trust the result.\n const stripped = stripLineNumberPrefixes(needle)\n if (stripped !== needle && stripped.trim().length > 0) {\n const count = countExactMatches(haystack, stripped)\n if (count > 0)\n return { actual: stripped, occurrences: count, via: 'line-numbers' }\n\n // 6. Combined: line-number strip + curly-quote normalization. The\n // typography mismatch may live in the file, the needle, or both.\n const strippedNorm = normalizeQuotes(stripped)\n if (strippedNorm !== stripped || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, strippedNorm, 'quotes+line-numbers')\n if (m)\n return m\n }\n }\n\n return null\n}\n\n/**\n * Short human-readable label for a recovery path, used by `edit` /\n * `multi_edit` to flag non-exact matches in their result messages — when a\n * fallback mistargets, the model (and the user reading the transcript) can\n * see WHICH transform fired instead of silently trusting the edit.\n */\nexport function describeVia(via: ResolvedMatch['via']): string {\n switch (via) {\n case 'exact': return 'exact match'\n case 'quotes': return 'curly-quote normalization'\n case 'desanitize': return 'sanitization recovery (e.g. <n> → <name>)'\n case 'quotes+desanitize': return 'sanitization recovery + curly-quote normalization'\n case 'line-numbers': return 'line-number-prefix stripping'\n case 'quotes+line-numbers': return 'line-number-prefix stripping + curly-quote normalization'\n }\n}\n\n/**\n * Apply the same recovery transforms used to find `old_string` to\n * `new_string`, so the file gets back its native form: desanitize when\n * the model emitted `<n>` for `<name>`, strip line-number prefixes when\n * the match required them, then re-curlify when the match required\n * quote normalization. Shared between `edit` and `multi_edit`.\n */\nexport function styleReplacementForVia(\n replacement: string,\n via: ResolvedMatch['via'],\n actual: string,\n): string {\n let out = replacement\n if (via === 'desanitize' || via === 'quotes+desanitize')\n out = desanitize(out)\n if (via === 'line-numbers' || via === 'quotes+line-numbers')\n out = stripLineNumberPrefixes(out)\n if (via === 'quotes' || via === 'quotes+desanitize' || via === 'quotes+line-numbers')\n out = preserveQuoteStyle(actual, out)\n return out\n}\n\n/**\n * When `old_string` matched via curly-quote normalization, re-style\n * `new_string` so the file's typography is preserved across the edit.\n * Detects whether the matched file region had curly singles, doubles, or\n * both, and applies the matching curlification to the replacement.\n *\n * Apostrophes in contractions (`don't`, `it's`) get the right-single curly\n * quote regardless of opening context — that's the canonical typographer's\n * convention for English. Other quotes use a simple\n * preceded-by-whitespace-or-opening-punctuation heuristic.\n */\nexport function preserveQuoteStyle(actual: string, replacement: string): string {\n const hasDouble = actual.includes(LEFT_DOUBLE_CURLY_QUOTE) || actual.includes(RIGHT_DOUBLE_CURLY_QUOTE)\n const hasSingle = actual.includes(LEFT_SINGLE_CURLY_QUOTE) || actual.includes(RIGHT_SINGLE_CURLY_QUOTE)\n if (!hasDouble && !hasSingle)\n return replacement\n\n let out = replacement\n if (hasDouble)\n out = applyCurly(out, '\"', LEFT_DOUBLE_CURLY_QUOTE, RIGHT_DOUBLE_CURLY_QUOTE, false)\n if (hasSingle)\n out = applyCurly(out, '\\'', LEFT_SINGLE_CURLY_QUOTE, RIGHT_SINGLE_CURLY_QUOTE, true)\n return out\n}\n\nfunction applyCurly(\n s: string,\n straight: string,\n left: string,\n right: string,\n contractionAware: boolean,\n): string {\n const chars = [...s]\n const result: string[] = []\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] !== straight) {\n result.push(chars[i])\n continue\n }\n if (contractionAware) {\n const prev = i > 0 ? chars[i - 1] : ''\n const next = i < chars.length - 1 ? chars[i + 1] : ''\n // Letter-quote-letter is a contraction, not a quote — always right.\n if (/\\p{L}/u.test(prev) && /\\p{L}/u.test(next)) {\n result.push(right)\n continue\n }\n }\n result.push(isOpeningContext(chars, i) ? left : right)\n }\n return result.join('')\n}\n\nfunction isOpeningContext(chars: string[], i: number): boolean {\n if (i === 0)\n return true\n const prev = chars[i - 1]\n return prev === ' ' || prev === '\\t' || prev === '\\n' || prev === '\\r'\n || prev === '(' || prev === '[' || prev === '{'\n || prev === '\\u2014' || prev === '\\u2013' // em / en dash\n}\n","/**\n * Context-usage breakdown — pure transforms.\n *\n * Turns a {@link ContextSnapshot} (the raw pieces the agent assembled for a\n * run: system prompt, wire tools, deferred tools, MCP tools/instructions,\n * skills catalog, ...) plus the real last-turn token total into a categorized\n * {@link ContextBreakdown} the TUI panel / GUI popover render.\n *\n * No React, no node — a browser-context renderer imports these via\n * `zidane/chat/pure`. The snapshot is captured main-side (TUI direct, GUI in\n * `main/chat`) because building it reads provider/agent state; only the pure\n * shaping lives here.\n *\n * Accuracy: per-category counts are estimates when no provider `countTokens`\n * is available — the heuristic ({@link estimateTokens}, ~4 bytes/token) sizes\n * each static segment and the bar is reconciled so it always sums to the real\n * last-turn total (`conversation = realTotal - sum(static)`). When a provider\n * exposes exact counts (Anthropic, OpenAI), the caller passes them in via\n * {@link ContextSnapshot.exact} and the corresponding categories drop their\n * `estimated` flag. Exact buckets (free space, autocompact buffer) are never\n * estimated.\n */\n\nimport type { SessionTurn } from '../types'\nimport { estimateTokens } from '../compact/utils'\n\n/**\n * Stable identifiers for each breakdown category. Drives swatch color +\n * ordering in both UIs. `*Deferred` buckets are tools/MCP that exist but are\n * NOT currently on the wire (lazy disclosure); `autocompactBuffer` is the\n * reserved output headroom; `freeSpace` is the remaining window.\n */\nexport type ContextCategoryId\n = | 'systemPrompt'\n | 'rules'\n | 'tools'\n | 'mcpTools'\n | 'mcpInstructions'\n | 'skills'\n | 'subagentDefs'\n | 'conversation'\n | 'mcpToolsDeferred'\n | 'toolsDeferred'\n | 'autocompactBuffer'\n | 'freeSpace'\n\n/**\n * Exact last-turn token usage split (provider-reported — always exact). Drives\n * the cache breakdown shown below the categories. `cacheRead + cacheCreation +\n * input` equals the live context total (`used`).\n */\nexport interface ContextUsageSplit {\n /** Fresh, uncached input tokens this turn. */\n input: number\n /** Tokens served from the prompt cache (the cached prefix). */\n cacheRead: number\n /** Tokens written to the cache this turn. */\n cacheCreation: number\n /** Assistant output tokens (not part of the input window; informational). */\n output: number\n}\n\n/** One display row contributed by an extension to the context panel. */\nexport interface ContextExtensionRow {\n label: string\n value: string\n}\n\n/** Extension-owned context panel section. Core treats rows as opaque display data. */\nexport interface ContextExtensionSection {\n id: string\n label: string\n /** Optional section-title foreground color. UIs fall back to their theme accent. */\n accentColor?: string\n rows: readonly ContextExtensionRow[]\n}\n\n/** Data exposed to extension context-breakdown contributors. */\nexport interface ContextBreakdownContributionContext {\n turns: readonly SessionTurn[]\n}\n\n/** Extension hook for adding opaque rows to the context panel. */\nexport type ContextBreakdownContributor\n = (ctx: ContextBreakdownContributionContext) =>\n | ContextExtensionSection\n | readonly ContextExtensionSection[]\n | null\n | undefined\n | Promise<ContextExtensionSection | readonly ContextExtensionSection[] | null | undefined>\n\n/** One expandable child row under a category (e.g. a single MCP tool / memory file). */\nexport interface ContextItem {\n /** Stable-ish key for rendering (tool name, file path). */\n id: string\n /** Display label. */\n label: string\n /** Token count for this item. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n /** Tool description (tool items only) — what a UI shows on hover. */\n description?: string\n /** Owning group when the category flattens several (MCP server name). */\n group?: string\n}\n\n/** One category row in the breakdown. */\nexport interface ContextCategory {\n id: ContextCategoryId\n /** Display label (e.g. \"Tool definitions\"). */\n label: string\n /** Token count for the category. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n /**\n * True for buckets that are NOT counted against the live window total\n * (deferred tools, free space, autocompact buffer) — the UI renders these\n * dimmed / below a divider, mirroring Claude Code's layout.\n */\n deferred?: boolean\n /** Optional expandable child rows (per MCP tool, per memory file, ...). */\n items?: ContextItem[]\n}\n\n/** The shaped, render-ready breakdown. */\nexport interface ContextBreakdown {\n /** Model id the snapshot was built for. */\n modelId: string\n /**\n * Real last-turn context size (provider-reported `input + cacheRead +\n * cacheCreation`) — the SAME number the footer/orb shows. The non-deferred\n * categories always sum to this.\n */\n used: number\n /** Effective window (raw - output reserve), the bar's denominator. */\n effectiveWindow: number\n /** `used / effectiveWindow`, clamped to [0, 1]. */\n fraction: number\n /** Live categories (sum to `used`) followed by deferred + free-space buckets. */\n categories: ContextCategory[]\n /** True when ANY live category is estimated (drives the panel's footnote). */\n hasEstimates: boolean\n /**\n * Exact last-turn usage split (cache read / write / fresh input / output),\n * when the host supplied it. Always exact — rendered as an informational\n * section below the categories. Absent when no usage is available yet.\n */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /**\n * Names of currently-active skills. Informational — an activated skill's body\n * lands in the conversation (tool-results), so its tokens are already counted\n * under Conversation; this just surfaces \"which skills are loaded\". Empty/absent\n * when none are active.\n */\n activeSkills?: string[]\n}\n\n/** Host-supplied options for `agent.getContextBreakdown`. */\nexport interface ContextBreakdownOptions {\n /**\n * Effective context window (`rawWindow - outputReserve`) for the active\n * model, resolved by the host via the chat model registry. Drives free-space\n * + fraction. When omitted, defaults to `used` (no headroom shown).\n */\n effectiveWindow?: number\n /**\n * Active model id — used for the exact `countTokens` call + the header label.\n * Only consulted on the PRE-RUN path (no snapshot yet); once a run has fired,\n * the snapshot's own model wins. When omitted, the provider default is used.\n */\n model?: string\n /** Tokens reserved for output (autocompact buffer). Defaults to 0. */\n autocompactBuffer?: number\n /**\n * Auto-compact threshold as a fraction of the window (0–1), when enabled.\n * When set, the \"Autocompact buffer\" bucket represents the ENTIRE tail from\n * the threshold to the end of the window (`(1 − threshold) × window`) rather\n * than just the reserved-output tokens — so the bar/row show exactly where\n * compaction fires. When omitted, `autocompactBuffer` is used as-is.\n */\n compactThreshold?: number\n /** Abort signal forwarded to the provider's `countTokens`. */\n signal?: AbortSignal\n}\n\n/** Tools grouped by MCP server, for the expandable per-server rows. */\nexport interface ContextMcpGroup {\n server: string\n /** Wire tool specs for this server (their JSON size is measured). */\n tools: { name: string, json: string, description?: string }[]\n}\n\n/**\n * Exact per-segment counts from a provider's `countTokens`, when available.\n * Each field is the count of the cumulative payload up to and including that\n * segment, so categories are derived by differencing (see\n * {@link buildContextBreakdown}). Any subset may be present; missing fields\n * fall back to the heuristic for that category.\n */\nexport interface ContextExactCounts {\n /** Tokens for system prompt alone. */\n system?: number\n /** Tokens for system + tools (so tools = systemAndTools - system). */\n systemAndTools?: number\n /** Tokens for the full payload (system + tools + messages) = the real total. */\n full?: number\n}\n\n/**\n * Raw inputs captured at agent prompt-assembly time. Everything here is what\n * actually went on (or was withheld from) the wire for the last run.\n */\nexport interface ContextSnapshot {\n modelId: string\n /** Full rendered system prompt (marker-stripped, as sent). */\n system: string\n /**\n * Host-composed base system BEFORE the agent appended skills / searchable /\n * MCP-instructions catalogs. Includes the rules block. The \"System prompt\"\n * (base doctrine) bucket = base − rules − env-noise. Defaults to `system`\n * when not provided (back-compat).\n */\n baseSystem?: string\n /** Rendered AGENTS.md/CLAUDE.md rules block (a substring of `baseSystem`). */\n rulesBlock?: string\n /** Source files behind the rules block, for per-file rows. */\n rulesFiles?: { path: string, source: string }[]\n /** Wire tool specs currently disclosed to the model, as JSON strings. */\n toolsJson: string[]\n /**\n * Per-tool detail for `toolsJson`, same order, when the host has it —\n * lets the breakdown list native tools like it lists MCP tools. Optional so\n * SDK callers assembling a snapshot by hand are unaffected.\n */\n toolItems?: { name: string, json: string, description?: string }[]\n /** Lazy tool entries NOT currently disclosed (deferred), as JSON strings. */\n deferredToolsJson: string[]\n /** MCP tools grouped by server (disclosed ones). */\n mcpGroups: ContextMcpGroup[]\n /** Deferred (undisclosed) MCP tools grouped by server. */\n deferredMcpGroups: ContextMcpGroup[]\n /** Rendered MCP instructions block, if any. */\n mcpInstructions?: string\n /** Rendered skills catalog text, if any. */\n skillsCatalog?: string\n /** Searchable / subagent (spawn) tool definitions text, if any. */\n subagentDefs?: string\n /** Memory / rules files in context. */\n /** Real last-turn total (input + cacheRead + cacheCreation). */\n used: number\n /** Effective window (raw - output reserve). */\n effectiveWindow: number\n /** Tokens reserved for output (autocompact buffer). */\n autocompactBuffer: number\n /** Exact per-segment counts from the provider, when available. */\n exact?: ContextExactCounts\n /** Exact last-turn usage split, when available (passed straight through). */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /** Names of currently-active skills (passed straight through). */\n activeSkills?: string[]\n}\n\nconst LABELS: Record<ContextCategoryId, string> = {\n systemPrompt: 'System prompt',\n rules: 'Rules (AGENTS.md)',\n tools: 'Tool definitions',\n mcpTools: 'MCP tools',\n mcpInstructions: 'MCP instructions',\n skills: 'Skills',\n subagentDefs: 'Subagent definitions',\n conversation: 'Conversation',\n mcpToolsDeferred: 'MCP tools (deferred)',\n toolsDeferred: 'System tools (deferred)',\n autocompactBuffer: 'Autocompact buffer',\n freeSpace: 'Free space',\n}\n\n/** Sum the heuristic token sizes of a list of strings. */\nfunction sumEstimate(parts: readonly string[]): number {\n let total = 0\n for (const p of parts)\n total += estimateTokens(p)\n return total\n}\n\nfunction mcpGroupTokens(group: ContextMcpGroup): { total: number, items: ContextItem[] } {\n const items: ContextItem[] = group.tools.map(t => ({\n id: `${group.server}:${t.name}`,\n label: t.name,\n tokens: estimateTokens(t.json),\n estimated: true,\n ...(t.description ? { description: t.description } : {}),\n group: group.server,\n }))\n let total = 0\n for (const it of items)\n total += it.tokens\n return { total, items }\n}\n\n/**\n * Shape a {@link ContextSnapshot} into a render-ready {@link ContextBreakdown}.\n *\n * Live categories (system prompt, tools, MCP tools/instructions, skills,\n * memory, subagent defs, conversation) sum to `snapshot.used` — `conversation`\n * absorbs the remainder so the bar matches the provider-reported total exactly.\n * Deferred + autocompact + free-space buckets follow.\n *\n * When `snapshot.exact` carries provider counts, the matching categories use\n * them (system, tools) and drop their `estimated` flag; everything else stays\n * on the heuristic.\n */\nexport function buildContextBreakdown(snapshot: ContextSnapshot): ContextBreakdown {\n const exact = snapshot.exact\n const systemExact = typeof exact?.system === 'number'\n\n // --- System-embedded sub-sections (heuristic) ----------------------------\n // The exact `count_tokens` system number covers the WHOLE system text. The\n // appended catalogs (rules / skills / MCP instructions / subagent defs) all\n // live inside it, so we size each heuristically and let the \"System prompt\"\n // (base doctrine) bucket absorb the remainder — keeping the system group's\n // sum exact while still attributing each section.\n const rulesTokens = snapshot.rulesBlock ? estimateTokens(snapshot.rulesBlock) : 0\n const rulesItems: ContextItem[] = (snapshot.rulesFiles ?? []).map(f => ({\n id: f.path,\n label: f.path,\n // Per-file size isn't separable from the rendered block; show the path only\n // (tokens 0, not estimated — there's nothing to estimate) so the row lists\n // sources without implying a per-file count or a `~` marker.\n tokens: 0,\n estimated: false,\n }))\n const skillsTokens = snapshot.skillsCatalog ? estimateTokens(snapshot.skillsCatalog) : 0\n const mcpInstructionsTokens = snapshot.mcpInstructions ? estimateTokens(snapshot.mcpInstructions) : 0\n const subagentTokens = snapshot.subagentDefs ? estimateTokens(snapshot.subagentDefs) : 0\n const embeddedSubsections = rulesTokens + skillsTokens + mcpInstructionsTokens + subagentTokens\n\n // System TOTAL (whole system text) — exact when available.\n const systemTotal = systemExact ? exact!.system! : estimateTokens(snapshot.system)\n // Base doctrine = system total minus the attributed sub-sections.\n const baseSystemTokens = Math.max(0, systemTotal - embeddedSubsections)\n\n // --- Native tool definitions (non-MCP, disclosed) ------------------------\n // When exact `systemAndTools` is available it covers BOTH native + MCP tools,\n // so we split that combined number proportionally by heuristic weight rather\n // than claiming exactness per sub-bucket.\n const nativeToolsEst = sumEstimate(snapshot.toolsJson)\n const mcpDisclosed = snapshot.mcpGroups.map(mcpGroupTokens)\n const mcpToolsEst = mcpDisclosed.reduce((a, g) => a + g.total, 0)\n\n let nativeToolsTokens = nativeToolsEst\n let mcpToolsTokens = mcpToolsEst\n let toolsEstimated = true\n if (systemExact && typeof exact?.systemAndTools === 'number') {\n const exactToolsTotal = Math.max(0, exact.systemAndTools - exact.system!)\n const estTotal = nativeToolsEst + mcpToolsEst\n if (estTotal > 0) {\n nativeToolsTokens = Math.round(exactToolsTotal * (nativeToolsEst / estTotal))\n mcpToolsTokens = exactToolsTotal - nativeToolsTokens\n }\n else {\n nativeToolsTokens = exactToolsTotal\n mcpToolsTokens = 0\n }\n toolsEstimated = false\n }\n\n // --- Live categories -----------------------------------------------------\n // Detailed split. The system-embedded sub-sections (rules / skills / MCP\n // instructions / subagent defs) are heuristic; the \"System prompt\" base\n // bucket carries the exact remainder so the whole system group still sums to\n // the exact system count. Tools/MCP-tools/conversation are split as before.\n const live: ContextCategory[] = []\n const push = (id: ContextCategoryId, tokens: number, estimated: boolean, items?: ContextItem[]) => {\n if (tokens <= 0 && !items?.length)\n return\n live.push({ id, label: LABELS[id], tokens: Math.max(0, tokens), estimated, ...(items?.length ? { items } : {}) })\n }\n\n // System group: base doctrine (exact remainder) + attributed sub-sections.\n push('systemPrompt', baseSystemTokens, !systemExact)\n push('rules', rulesTokens, true, rulesItems)\n push('skills', skillsTokens, true)\n push('mcpInstructions', mcpInstructionsTokens, true)\n push('subagentDefs', subagentTokens, true)\n // Tools.\n push('tools', nativeToolsTokens, toolsEstimated, snapshot.toolItems?.map(t => ({\n id: t.name,\n label: t.name,\n tokens: estimateTokens(t.json),\n estimated: true,\n ...(t.description ? { description: t.description } : {}),\n })))\n push('mcpTools', mcpToolsTokens, toolsEstimated, mcpDisclosed.flatMap(g => g.items))\n\n // --- Conversation = remainder (keeps the bar summing to `used`) ----------\n const accountedStatic = live.reduce((a, c) => a + c.tokens, 0)\n const conversationTokens = Math.max(0, snapshot.used - accountedStatic)\n // Exact when both system AND tools were exactly counted — then the remainder\n // (used − exactSystem − exactTools) is itself exact, since `used` is the\n // provider-reported total.\n const conversationEstimated = !(systemExact && !toolsEstimated)\n push('conversation', conversationTokens, conversationEstimated)\n\n // --- Deferred buckets (not counted against `used`) -----------------------\n const deferred: ContextCategory[] = []\n const deferredNativeTools = sumEstimate(snapshot.deferredToolsJson)\n if (deferredNativeTools > 0) {\n deferred.push({ id: 'toolsDeferred', label: LABELS.toolsDeferred, tokens: deferredNativeTools, estimated: true, deferred: true })\n }\n const deferredMcp = snapshot.deferredMcpGroups.map(mcpGroupTokens)\n const deferredMcpTotal = deferredMcp.reduce((a, g) => a + g.total, 0)\n if (deferredMcpTotal > 0) {\n deferred.push({\n id: 'mcpToolsDeferred',\n label: LABELS.mcpToolsDeferred,\n tokens: deferredMcpTotal,\n estimated: true,\n deferred: true,\n items: deferredMcp.flatMap(g => g.items),\n })\n }\n\n // --- Autocompact buffer + free space (exact) -----------------------------\n if (snapshot.autocompactBuffer > 0) {\n deferred.push({ id: 'autocompactBuffer', label: LABELS.autocompactBuffer, tokens: snapshot.autocompactBuffer, estimated: false, deferred: true })\n }\n const free = Math.max(0, snapshot.effectiveWindow - snapshot.used)\n deferred.push({ id: 'freeSpace', label: LABELS.freeSpace, tokens: free, estimated: false, deferred: true })\n\n const categories = [...live, ...deferred]\n const hasEstimates = live.some(c => c.estimated && c.tokens > 0)\n const fraction = snapshot.effectiveWindow > 0\n ? Math.max(0, Math.min(1, snapshot.used / snapshot.effectiveWindow))\n : 0\n\n return {\n modelId: snapshot.modelId,\n used: snapshot.used,\n effectiveWindow: snapshot.effectiveWindow,\n fraction,\n categories,\n hasEstimates,\n ...(snapshot.usage ? { usage: snapshot.usage } : {}),\n ...(snapshot.extensionSections?.length ? { extensionSections: snapshot.extensionSections } : {}),\n ...(snapshot.activeSkills?.length ? { activeSkills: snapshot.activeSkills } : {}),\n }\n}\n","/**\n * Context segments — pure transforms.\n *\n * Sibling to `context-breakdown.ts`: where that module answers \"how many\n * tokens is each part of my context\", this one answers \"what IS each part,\n * and where did it come from\". It turns the same assembled-prompt pieces into\n * a flat list of {@link ContextSegment}s carrying the actual TEXT plus its\n * provenance, so a UI can list every chunk loaded by default in a session,\n * let the user read it, and open the file behind it when there is one.\n *\n * No React, no node — a browser-context renderer imports these via\n * `zidane/chat/pure`.\n *\n * Provenance is honest about what can and can't be opened:\n * - `'file'` — a real path on disk (AGENTS.md / CLAUDE.md / ruler md).\n * The only origin that carries `path`, hence the only one\n * a host can hand to `$EDITOR`.\n * - `'built-in'` — compiled into the binary (base doctrine, subagent defs).\n * - `'generated'` — assembled at prompt time from discovered state (the\n * skills catalog is rendered from the skill manifests).\n * - `'mcp'` — served by a remote MCP server at connect time.\n */\n\nimport { estimateTokens } from '../compact/utils'\n\n/** Where a segment's text came from. Only `'file'` segments carry a `path`. */\nexport type ContextSegmentOrigin = 'built-in' | 'file' | 'generated' | 'mcp'\n\n/** One chunk of text present in the session's default context. */\nexport interface ContextSegment {\n /** Stable key for rendering (`'system'`, `'rules:<path>'`, `'skills'`, ...). */\n id: string\n /** Display label (e.g. \"System prompt\", or the file's basename). */\n label: string\n origin: ContextSegmentOrigin\n /**\n * Short right-hand qualifier — the instruction scope for files, the server\n * list for MCP, a count for the skills catalog. Absent when there's nothing\n * useful to add beyond the origin badge.\n */\n detail?: string\n /** The text itself, as it sits in the prompt. Empty segments are dropped. */\n text: string\n /**\n * Absolute path of the file backing this segment. Present only for\n * `origin: 'file'` — a host uses it as the \"open in $EDITOR\" target.\n */\n path?: string\n /**\n * Heuristic token size (~4 bytes/token). Always an estimate: exact\n * per-segment counts aren't separable from the single system-prompt string\n * the provider counts, which is why {@link ContextSegment} carries no\n * `estimated` flag — every value here is one.\n */\n tokens: number\n}\n\n/**\n * A host-discovered instruction file. Structurally compatible with\n * `AgentsMdFile` from `./agents-md` (whose `source` field is the SCOPE, not\n * the text — `contents` is the text), so callers can pass those straight in.\n */\nexport interface ContextSegmentFile {\n path: string\n /** Instruction scope — `'project'` / `'user'`, surfaced as the row detail. */\n source?: string\n contents: string\n}\n\n/**\n * The assembled-prompt pieces {@link buildContextSegments} shapes. Mirrors the\n * subset of the agent's `ContextAssembly` that carries text, plus host-side\n * instruction files (which the assembly only knows as paths).\n */\nexport interface ContextSegmentsInput {\n /**\n * Host-composed base system BEFORE the agent appended its catalogs. The\n * rules block is a substring of this; the \"System prompt\" segment is the\n * remainder. Falls back to `system` when absent, which over-attributes the\n * appended catalogs into the base row rather than losing them.\n */\n baseSystem?: string\n /** Full rendered system prompt as sent. Used as the `baseSystem` fallback. */\n system?: string\n /**\n * Rendered instruction block (a substring of `baseSystem`). Subtracted from\n * the base so its text isn't reported twice — once as doctrine and once as\n * per-file rows.\n */\n rulesBlock?: string\n /** The files behind `rulesBlock`, each with its own text. */\n rulesFiles?: readonly ContextSegmentFile[]\n /**\n * Absolute path of a `SYSTEM.md` override backing the base prompt. When set,\n * the \"System prompt\" segment reports `origin: 'file'` and becomes openable\n * — the doctrine is the user's file, not compiled-in text.\n */\n systemPath?: string\n /** Rendered skills catalog (the per-skill blurbs, not skill bodies). */\n skillsCatalog?: string\n /** Rendered MCP instructions block. */\n mcpInstructions?: string\n /** Searchable / subagent (spawn) tool catalog text. */\n subagentDefs?: string\n}\n\n/**\n * Remove the first occurrence of `part` from `whole`, collapsing the blank-line\n * run left AT THE JOIN.\n *\n * Used to carve the rules block out of the base system so the \"System prompt\"\n * segment reports only doctrine + env. Substring-based because that's the\n * contract the assembly documents (`rulesBlock` IS a substring of\n * `baseSystem`); a miss leaves `whole` untouched, which degrades to\n * over-reporting the base row rather than dropping text on the floor.\n *\n * The collapse is deliberately scoped to the seam. An earlier version ran\n * `/\\n{3,}/g` over the whole result, which rewrote blank-line runs ANYWHERE in\n * the doctrine — and this tab exists precisely so the user can read what is in\n * context, not a reflowed approximation of it. Interior bytes now survive\n * verbatim; only the newlines that met when `part` was excised are normalized,\n * plus a `trim()` so a segment can't open or close on blank lines.\n */\nfunction removeFirst(whole: string, part: string): string {\n if (!part)\n return whole\n const at = whole.indexOf(part)\n if (at < 0)\n return whole\n const before = whole.slice(0, at)\n const after = whole.slice(at + part.length)\n const trailing = /\\n*$/.exec(before)?.[0] ?? ''\n const leading = /^\\n*/.exec(after)?.[0] ?? ''\n // Two newlines (one blank line) is the separator the prompt builder uses\n // between sections, so that's what the seam becomes when either side had any.\n const seam = trailing.length + leading.length >= 2 ? '\\n\\n' : `${trailing}${leading}`\n const head = before.slice(0, before.length - trailing.length)\n return `${head}${seam}${after.slice(leading.length)}`.trim()\n}\n\n/**\n * Best-effort display name for an instruction file: its basename, with the\n * parent directory prefixed when the basename alone would be ambiguous\n * (`AGENTS.md` appears at up to four paths per scope). Path-separator handling\n * covers both POSIX and Windows so this stays node-free.\n */\nfunction fileLabel(path: string): string {\n const parts = path.split(/[/\\\\]/).filter(Boolean)\n const base = parts.at(-1) ?? path\n const parent = parts.at(-2)\n // A dotted parent (`.agents`, `.zidane`, `.claude`, `.ruler`) is the\n // meaningful discriminator between same-named instruction files.\n return parent?.startsWith('.') ? `${parent}/${base}` : base\n}\n\n/**\n * Shape assembled-prompt pieces into a flat, render-ready segment list.\n *\n * Order is prompt order — base doctrine, then instruction files (broadest\n * scope first, as `discoverAgentsMd` returns them), then the appended\n * catalogs. Empty / whitespace-only pieces are dropped so the list never\n * shows a zero-byte row.\n */\nexport function buildContextSegments(input: ContextSegmentsInput): ContextSegment[] {\n const segments: ContextSegment[] = []\n const push = (seg: Omit<ContextSegment, 'tokens'>) => {\n if (!seg.text.trim())\n return\n segments.push({ ...seg, tokens: estimateTokens(seg.text) })\n }\n\n // --- Base doctrine -------------------------------------------------------\n // `baseSystem` minus the rules block. The per-file rows below carry the\n // instruction text, so leaving the block in would double-report it.\n const base = input.baseSystem ?? input.system ?? ''\n const overridden = input.systemPath !== undefined\n push({\n id: 'system',\n label: 'System prompt',\n // An override makes this a real file on disk; without one it's compiled in.\n origin: overridden ? 'file' : 'built-in',\n detail: overridden ? 'SYSTEM.md override + environment' : 'doctrine + environment',\n text: input.rulesBlock ? removeFirst(base, input.rulesBlock) : base,\n ...(input.systemPath !== undefined ? { path: input.systemPath } : {}),\n })\n\n // --- Instruction files ---------------------------------------------------\n // The only file-backed segments, and so the only openable ones.\n for (const file of input.rulesFiles ?? []) {\n push({\n id: `rules:${file.path}`,\n label: fileLabel(file.path),\n origin: 'file',\n ...(file.source ? { detail: file.source } : {}),\n text: file.contents,\n path: file.path,\n })\n }\n\n // --- Appended catalogs ---------------------------------------------------\n push({\n id: 'skills',\n label: 'Skills catalog',\n origin: 'generated',\n detail: 'name + description per skill (bodies load on activation)',\n text: input.skillsCatalog ?? '',\n })\n push({\n id: 'mcp-instructions',\n label: 'MCP instructions',\n origin: 'mcp',\n detail: 'served by the connected servers',\n text: input.mcpInstructions ?? '',\n })\n push({\n id: 'subagent-defs',\n label: 'Subagent definitions',\n origin: 'built-in',\n text: input.subagentDefs ?? '',\n })\n\n return segments\n}\n","/**\n * Credential-file key arithmetic, split from `./credentials` so the rules can\n * be enforced where credentials themselves must not be pulled in.\n *\n * `./credentials` reaches the provider registry (and through it the pi-ai\n * factories) for `credKeyOf`; the extension loader — an edge entrypoint that\n * validates descriptor keys at registration time — must stay clear of that\n * graph. This module is string arithmetic with no imports.\n */\n\n/**\n * Separator between a provider's canonical key and a slot qualifier. Every\n * non-canonical slot (`#alt`, `#account:N`) starts with it, so the character is\n * reserved in descriptor credential keys outright.\n */\nexport const CRED_KEY_SLOT_SEPARATOR = '#'\n\n/**\n * Reserved suffix marking a provider's SECOND credential slot.\n *\n * Not usable as (or as the tail of) a descriptor's credential key: `foo#alt`\n * holds `foo`'s alternate credential, so a provider claiming that name would\n * share storage with it.\n */\nexport const ALTERNATE_CRED_KEY_SUFFIX = '#alt'\n\n/**\n * Reserved infix marking one of a provider's ADDITIONAL OAuth accounts:\n * `foo#account:1`, `foo#account:2`, …\n */\nexport const ACCOUNT_CRED_KEY_INFIX = '#account:'\n\n/**\n * File key holding a provider's second credential, when it has one of each kind.\n *\n * The canonical key always holds the credential the user prefers; this sibling\n * holds the other. That one invariant is what makes preference selection free:\n * every existing reader (`applyApiKeyEnv`, the harness provider factories)\n * already resolves the canonical key, so \"switch priority\" is just moving two\n * objects between two keys — no precedence flag to interpret, no resolution\n * order to keep in sync across layers.\n *\n * A sibling key rather than a nested field because the canonical entry gets\n * REPLACED wholesale on token refresh; anything nested inside it would be\n * dropped by the next rotation. And older zidane versions look credentials up\n * by `credKeyOf`, so a suffixed key is simply invisible to them — they read the\n * preferred credential and behave exactly as before, which is why this needs no\n * migration or schema version.\n */\nexport function alternateCredKey(fileKey: string): string {\n return `${fileKey}${ALTERNATE_CRED_KEY_SUFFIX}`\n}\n\n/**\n * File key holding one of a provider's non-active OAuth accounts.\n *\n * Same sibling-key reasoning as {@link alternateCredKey}: the canonical key is\n * the active one, so a provider with three OAuth grants stores the active one\n * canonically and the other two under `#account:N`. `#alt` stays dedicated to\n * the other-kind (API key) alternate so files written by builds that predate\n * multi-account keep meaning the same thing.\n */\nexport function accountCredKey(fileKey: string, n: number): string {\n return `${fileKey}${ACCOUNT_CRED_KEY_INFIX}${n}`\n}\n\n/** True when `key` is one of `fileKey`'s `#account:N` slots. */\nexport function isAccountCredKey(fileKey: string, key: string): boolean {\n const prefix = `${fileKey}${ACCOUNT_CRED_KEY_INFIX}`\n return key.startsWith(prefix) && /^\\d+$/.test(key.slice(prefix.length))\n}\n\n/**\n * Smallest `#account:N` key of `fileKey` not present in `existing`.\n *\n * Deterministic rather than random so a file hand-edited or written by two\n * processes in sequence stays readable; the write lock keeps it collision-free.\n */\nexport function nextAccountCredKey(fileKey: string, existing: Iterable<string>): string {\n const taken = new Set(existing)\n for (let n = 1; ; n++) {\n const key = accountCredKey(fileKey, n)\n if (!taken.has(key))\n return key\n }\n}\n\n/**\n * Name shown for an OAuth account that was never given one.\n *\n * Also what a first OAuth login is stored under, so a second account has\n * something to be told apart from. Pre-multi-account files hold unnamed\n * grants; {@link oauthAccountLabel} makes them read the same.\n */\nexport const DEFAULT_OAUTH_ACCOUNT_LABEL = 'Default'\n\n/** Trimmed user-given account name, or {@link DEFAULT_OAUTH_ACCOUNT_LABEL}. */\nexport function oauthAccountLabel(credential: { label?: unknown }): string {\n const label = typeof credential.label === 'string' ? credential.label.trim() : ''\n return label || DEFAULT_OAUTH_ACCOUNT_LABEL\n}\n\n/**\n * True when a key claims a reserved slot namespace.\n *\n * Built-in keys are plain identifiers (`anthropic`, `openai-codex`), but\n * `ProviderDescriptor.key` / `credentialFileKey` are open strings — so the\n * reservation is checked, not assumed.\n */\nexport function isReservedCredKey(fileKey: string): boolean {\n return fileKey.includes(CRED_KEY_SLOT_SEPARATOR)\n}\n","/**\n * Panels: renderer-agnostic side-panel contributions.\n *\n * A panel is a tab in the host's side rail (TUI) / side panel (GUI). The\n * extension supplies DATA, never UI: `load()` returns a JSON-safe\n * `PanelContent` the host paints with its own components, so one\n * registration works in-process (TUI) and across the Electron IPC boundary\n * (GUI, where extensions run in the main process and the panel paints in\n * the renderer). `custom` items carry a mandatory markdown `fallback` for\n * hosts without the named renderer, the same invariant transcript custom\n * blocks follow.\n *\n * Interaction flows back as ids: rows and buttons name an `actionId`; the\n * host calls `onAction(actionId, payload)` where the extension runs.\n */\nimport type { JsonValue } from '../types'\nimport type { ExtensionArtifactRow } from './types'\n\n/**\n * Per-surface icon: an iconify class for the GUI, a single glyph for the\n * TUI. The GUI ships Phosphor only (`i-ph-<name>`, `-fill` for a filled\n * weight); other collections are not registered and paint nothing.\n */\nexport interface PanelIcon {\n gui?: string\n tui?: string\n}\n\nexport interface PanelAction {\n id: string\n label: string\n /** `danger` renders in the destructive tint. */\n tone?: 'default' | 'danger'\n}\n\n/** One line in a panel, same presentation as an artifact row. */\nexport interface PanelRowItem extends ExtensionArtifactRow {\n kind: 'row'\n /** Stable key for the host; defaults to the title. */\n id?: string\n /** Fired via `onAction` on click / Enter. `href` opens externally when no action is set. */\n actionId?: string\n /** Extra data handed back with the action. */\n payload?: JsonValue\n}\n\nexport interface PanelMarkdownItem {\n kind: 'markdown'\n text: string\n}\n\nexport interface PanelKeyValueItem {\n kind: 'kv'\n rows: readonly { label: string, value: string }[]\n}\n\n/**\n * Host-specific rich view. The TUI resolves `renderer` against\n * `ctx.tui.registerRenderer` ids (`<extension>/<id>`, bare ids are\n * prefixed at registration); the GUI, and any host without the renderer,\n * paints `fallback` as markdown.\n */\nexport interface PanelCustomItem {\n kind: 'custom'\n renderer: string\n data?: JsonValue\n fallback: string\n}\n\nexport type PanelItem = PanelRowItem | PanelMarkdownItem | PanelKeyValueItem | PanelCustomItem\n\nexport interface PanelSection {\n id: string\n title?: string\n items: readonly PanelItem[]\n /** Collapsed by default when true. */\n collapsed?: boolean\n}\n\nexport interface PanelContent {\n /** Overrides the tab label inside the panel header. */\n title?: string\n /** Count / short tag shown on the tab. `0` and `''` hide it. */\n badge?: number | string\n sections: readonly PanelSection[]\n /** Buttons in the panel footer. */\n actions?: readonly PanelAction[]\n /** Shown when `sections` are empty. */\n empty?: string\n}\n\nexport interface PanelLoadContext {\n /** Active session id, when a session is attached. */\n sessionId?: string\n cwd?: string\n}\n\nexport interface ExtensionPanel {\n /** Stable id; namespaced `<extension>/<id>` at registration. */\n id: string\n label: string\n icon?: PanelIcon\n /** Produce the current content. Called on open, on `subscribe` emits, and on explicit refresh. */\n load: (ctx: PanelLoadContext) => PanelContent | Promise<PanelContent>\n /**\n * Live updates: call `emit()` whenever `load()` would return something\n * new. Return an unsubscribe. Hosts debounce emits and only reload while\n * the panel is visible.\n */\n subscribe?: (emit: () => void) => () => void\n /** Row / button callbacks. Runs where the extension runs. */\n onAction?: (actionId: string, payload: JsonValue | undefined, ctx: PanelLoadContext) => void | Promise<void>\n}\n\n/** Registry entry: the definition plus its owning extension. */\nexport interface ExtensionPanelEntry extends ExtensionPanel {\n owner: string\n}\n\n// ---------------------------------------------------------------------------\n// Normalisation\n// ---------------------------------------------------------------------------\n\n/** Caps applied before content crosses IPC or reaches a renderer. */\nexport const PANEL_CONTENT_LIMITS = {\n sections: 32,\n itemsPerSection: 200,\n actions: 8,\n /** Per string field. */\n textChars: 20_000,\n /** Whole payload, JSON-serialised. */\n bytes: 512 * 1024,\n} as const\n\nfunction str(v: unknown, max: number = PANEL_CONTENT_LIMITS.textChars): string | undefined {\n return typeof v === 'string' ? (v.length > max ? `${v.slice(0, max - 1)}…` : v) : undefined\n}\n\n/**\n * Coerce whatever `load()` returned into a well-formed `PanelContent`:\n * unknown item kinds and malformed entries are dropped, strings are\n * trimmed to the caps, and the whole thing is size-bounded. Never throws.\n */\nexport function normalizePanelContent(input: unknown): PanelContent {\n const empty: PanelContent = { sections: [] }\n if (!input || typeof input !== 'object')\n return empty\n const o = input as Record<string, unknown>\n\n const sections: PanelSection[] = []\n if (Array.isArray(o.sections)) {\n for (const raw of o.sections.slice(0, PANEL_CONTENT_LIMITS.sections)) {\n const s = normalizeSection(raw, sections.length)\n if (s)\n sections.push(s)\n }\n }\n\n const actions: PanelAction[] = []\n if (Array.isArray(o.actions)) {\n for (const raw of o.actions.slice(0, PANEL_CONTENT_LIMITS.actions)) {\n if (raw && typeof raw === 'object') {\n const a = raw as Record<string, unknown>\n const id = str(a.id, 200)\n const label = str(a.label, 200)\n if (id && label)\n actions.push({ id, label, ...(a.tone === 'danger' ? { tone: 'danger' as const } : {}) })\n }\n }\n }\n\n const out: PanelContent = { sections }\n const title = str(o.title, 200)\n if (title)\n out.title = title\n if (typeof o.badge === 'number' && Number.isFinite(o.badge))\n out.badge = o.badge\n else if (typeof o.badge === 'string' && o.badge)\n out.badge = o.badge.slice(0, 12)\n if (actions.length > 0)\n out.actions = actions\n const emptyText = str(o.empty, 500)\n if (emptyText)\n out.empty = emptyText\n\n return enforceBytes(out)\n}\n\nfunction normalizeSection(raw: unknown, index: number): PanelSection | null {\n if (!raw || typeof raw !== 'object')\n return null\n const s = raw as Record<string, unknown>\n const items: PanelItem[] = []\n if (Array.isArray(s.items)) {\n for (const item of s.items.slice(0, PANEL_CONTENT_LIMITS.itemsPerSection)) {\n const n = normalizeItem(item)\n if (n)\n items.push(n)\n }\n }\n const out: PanelSection = { id: str(s.id, 200) ?? `section-${index}`, items }\n const title = str(s.title, 200)\n if (title)\n out.title = title\n if (s.collapsed === true)\n out.collapsed = true\n return out\n}\n\nfunction normalizeItem(raw: unknown): PanelItem | null {\n if (!raw || typeof raw !== 'object')\n return null\n const i = raw as Record<string, unknown>\n switch (i.kind) {\n case 'row': {\n const title = str(i.title, 500)\n if (!title)\n return null\n const out: PanelRowItem = { kind: 'row', title }\n const id = str(i.id, 200)\n const subtitle = str(i.subtitle, 1000)\n const href = str(i.href, 2000)\n const status = str(i.status, 60)\n const actionId = str(i.actionId, 200)\n if (id)\n out.id = id\n if (subtitle)\n out.subtitle = subtitle\n if (href)\n out.href = href\n if (status)\n out.status = status\n if (actionId)\n out.actionId = actionId\n if (Array.isArray(i.badges))\n out.badges = i.badges.filter(isBadge).slice(0, 8)\n if (i.payload !== undefined && isJsonValue(i.payload))\n out.payload = i.payload\n return out\n }\n case 'markdown': {\n const text = str(i.text)\n return text === undefined ? null : { kind: 'markdown', text }\n }\n case 'kv': {\n if (!Array.isArray(i.rows))\n return null\n const rows = i.rows\n .map((r) => {\n if (!r || typeof r !== 'object')\n return null\n const row = r as Record<string, unknown>\n const label = str(row.label, 200)\n const value = str(row.value, 2000)\n return label !== undefined && value !== undefined ? { label, value } : null\n })\n .filter((r): r is { label: string, value: string } => r !== null)\n .slice(0, PANEL_CONTENT_LIMITS.itemsPerSection)\n return { kind: 'kv', rows }\n }\n case 'custom': {\n const renderer = str(i.renderer, 200)\n const fallback = str(i.fallback)\n if (!renderer || fallback === undefined)\n return null\n const out: PanelCustomItem = { kind: 'custom', renderer, fallback }\n if (i.data !== undefined && isJsonValue(i.data))\n out.data = i.data\n return out\n }\n default:\n return null\n }\n}\n\nfunction isBadge(v: unknown): v is NonNullable<ExtensionArtifactRow['badges']>[number] {\n return Boolean(v && typeof v === 'object' && typeof (v as { text?: unknown }).text === 'string')\n}\n\nfunction isJsonValue(v: unknown): v is JsonValue {\n try {\n JSON.stringify(v)\n return v !== undefined && typeof v !== 'function' && typeof v !== 'symbol'\n }\n catch {\n return false\n }\n}\n\n/**\n * Trim sections from the end until the payload fits the byte budget. A\n * panel that overflows keeps its first sections and gets an `empty`-style\n * note appended so the truncation is visible.\n */\nfunction enforceBytes(content: PanelContent): PanelContent {\n const size = (c: PanelContent) => JSON.stringify(c).length\n if (size(content) <= PANEL_CONTENT_LIMITS.bytes)\n return content\n const sections = [...content.sections]\n while (sections.length > 0 && size({ ...content, sections }) > PANEL_CONTENT_LIMITS.bytes)\n sections.pop()\n return {\n ...content,\n sections: [\n ...sections,\n { id: 'truncated', items: [{ kind: 'markdown', text: '_Panel content truncated (too large)._' }] },\n ],\n }\n}\n\n/** Tab badge as shown next to the label; `undefined` when nothing to show. */\nexport function panelBadgeText(badge: PanelContent['badge']): string | undefined {\n if (badge === undefined || badge === 0 || badge === '')\n return undefined\n if (typeof badge === 'number')\n return badge > 99 ? '99+' : String(badge)\n return badge\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,kBAAkB,UAAkB,QAAwB;CAC1E,IAAI,OAAO,WAAW,GACp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O,KAAK,qBAAqB,OACxC,OAAO;CACT,MAAM,WAAW,CAAC,GAAG,QAAQ,QAAQ;CACrC,OAAO,SAAS,SAAS,KAAK,KAAK;EAAE,GAAG;EAAS;CAAS,CAAC,IAAI,qBAAqB,OAClF,SAAS,IAAI;CACf,OAAO;EACL,GAAG;EACH,UAAU,CACR,GAAG,UACH;GAAE,IAAI;GAAa,OAAO,CAAC;IAAE,MAAM;IAAY,MAAM;GAAyC,CAAC;EAAE,CACnG;CACF;AACF;;AAGA,SAAgB,eAAe,OAAkD;CAC/E,IAAI,UAAU,KAAA,KAAa,UAAU,KAAK,UAAU,IAClD,OAAO,KAAA;CACT,IAAI,OAAO,UAAU,UACnB,OAAO,QAAQ,KAAK,QAAQ,OAAO,KAAK;CAC1C,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"plugins-gbI7SBA6.js","names":[],"sources":["../src/chat/xdg.ts","../src/plugins/boundary.ts","../src/plugins/types.ts","../src/plugins/manifest.ts","../src/plugins/mcp.ts","../src/plugins/skills.ts","../src/plugins/load.ts"],"sourcesContent":["/**\n * XDG Base Directory resolution for zidane.\n *\n * The user's storage spreads across four logical slots:\n *\n * - **config** — credentials, mcp-credentials, keybindings, config.json,\n * mcps.json, skills (user-editable surface).\n * - **data** — sessions.db (long-lived chat history).\n * - **state** — state.json (per-machine UI bookkeeping: last provider,\n * last model, last agent, settings).\n * - **cache** — persisted tool results, background-task logs,\n * auto-update registry cache (regenerable, safe to wipe).\n *\n * Historically all four collapsed to `~/.zidane/`. This module adds\n * XDG-Base-Directory-aware defaults so a Linux user with no existing\n * `~/.zidane/` lands in the conventional `~/.config/zidane/`,\n * `~/.local/share/zidane/`, `~/.local/state/zidane/`, `~/.cache/zidane/`\n * trio. Existing setups (anyone with a `~/.zidane/` directory or\n * `ZIDANE_STORAGE_DIR` set) keep the single-dir layout unchanged.\n *\n * Resolution flow — applied in this order:\n *\n * 1. Caller passed an explicit `storageDir` (`ChatOptions.storageDir`)\n * OR `ZIDANE_STORAGE_DIR` is set → **legacy-explicit** single-dir\n * layout under `<storageDir>/<prefix>`. The four slots collapse to\n * the same directory.\n * 2. `~/<prefix>/` already exists on disk → **legacy-existing**\n * single-dir layout under that directory. Upgrades never silently\n * shift files around.\n * 3. Any `XDG_*_HOME` env var is set OR `process.platform === 'linux'`\n * → **XDG split**. Each slot lands in its own dir. Per-slot\n * `ZIDANE_{CONFIG,DATA,CACHE,STATE}_DIR` overrides beat the XDG\n * vars for surgical tweaks.\n * 4. Otherwise (macOS/Windows, no XDG signal, no existing dir) →\n * **default** single-dir layout at `~/<prefix>/`. Day-one behavior\n * on these platforms is unchanged.\n *\n * The `userDir` legacy alias always equals `configDir` so existing code\n * that still references `paths.userDir` keeps reading credentials, mcps,\n * etc. from the right place.\n */\n\nimport { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { resolve } from 'node:path'\n\n/** The four slot kinds we resolve. Names match the XDG spec. */\nexport type StorageSlot = 'config' | 'data' | 'state' | 'cache'\n\n/** Which resolution branch produced the layout — surfaced for debugging + tests. */\nexport type StorageMode = 'legacy-explicit' | 'legacy-existing' | 'xdg' | 'default'\n\n/**\n * Per-slot directories. In legacy / default modes the four fields all\n * point at the same path; in XDG mode they fan out into their\n * spec-conventional locations.\n *\n * `mode` carries the resolution branch so a host that wants to print\n * a startup banner (\"zidane is using XDG paths\") can detect the\n * layout without re-running the logic.\n */\nexport interface StorageDirs {\n configDir: string\n dataDir: string\n stateDir: string\n cacheDir: string\n mode: StorageMode\n}\n\nexport interface ResolveStorageDirsOptions {\n /** Storage prefix. Leading dot tolerated. Default: `'.zidane'`. */\n prefix?: string\n /**\n * Explicit storage root (`ChatOptions.storageDir`). When set, forces\n * legacy-explicit mode regardless of the platform / XDG signals.\n */\n storageDir?: string\n /** Override `os.homedir()` for tests. */\n home?: string\n /** Override `process.platform` for tests. */\n platform?: NodeJS.Platform\n /** Override `process.env` for tests. */\n env?: Readonly<Record<string, string | undefined>>\n}\n\n/**\n * Resolve the four storage slots according to the precedence above.\n *\n * Pure aside from one filesystem probe (`existsSync(home/<prefix>)`)\n * — the same probe `resolveStoragePaths` would do anyway when\n * computing `paths.userDir`. No directories are created here; the\n * relevant write paths (state store, credentials writer, persist\n * dir) handle their own lazy `mkdirSync` already.\n */\nexport function resolveStorageDirs(opts: ResolveStorageDirsOptions = {}): StorageDirs {\n const env = opts.env ?? process.env\n const home = opts.home ?? homedir()\n const platform = opts.platform ?? process.platform\n // Two prefix forms — legacy mode preserves whatever the caller\n // passed (no implicit dot insertion, so `prefix: 'myapp'` lands at\n // `<storageDir>/myapp` not `<storageDir>/.myapp` — matches the\n // pre-XDG behavior tests already rely on). XDG mode uses the de-\n // dotted form (`'.zidane'` → `'zidane'`) because the XDG dir itself\n // is already the dotfile container — `~/.config/.zidane/` would be\n // a double-dot offense.\n const rawPrefix = opts.prefix ?? '.zidane'\n const prefixBare = rawPrefix.replace(/^\\./, '')\n\n // Branch 1 — explicit storage root → legacy-explicit.\n // Host-supplied `storageDir` beats env so SDK callers can pin a\n // location for embedded usage; otherwise `ZIDANE_STORAGE_DIR` wins.\n const explicitStorageDir = opts.storageDir ?? env.ZIDANE_STORAGE_DIR\n if (explicitStorageDir) {\n const base = resolve(explicitStorageDir, rawPrefix)\n return single(base, 'legacy-explicit')\n }\n\n // Branch 2 — `~/<prefix>/` already exists → legacy-existing.\n // Detect ANY of the legacy locations the user might have:\n // - `~/.zidane/` (default prefix)\n // - `~/.<prefix>/` (custom prefix)\n // The probe is a single existsSync (cheap) and skipping it for a\n // user with a customized prefix would leak their data into XDG dirs\n // on next launch.\n const legacyHomeDir = resolve(home, rawPrefix)\n if (existsSync(legacyHomeDir))\n return single(legacyHomeDir, 'legacy-existing')\n\n // Branch 3 — XDG signals present → split layout.\n // The signal is generous: Linux always qualifies, any platform\n // where the user has set any `XDG_*_HOME` var opts in (a savvy\n // mac user can put zidane in their XDG hierarchy too), AND any\n // `ZIDANE_{CONFIG,DATA,STATE,CACHE}_DIR` per-slot override also\n // opts in — otherwise a user pinning JUST `ZIDANE_CACHE_DIR` on\n // macOS would have it silently ignored because none of the\n // `XDG_*_HOME` vars are set.\n const hasXdgSignal = platform === 'linux'\n || !!env.XDG_CONFIG_HOME\n || !!env.XDG_DATA_HOME\n || !!env.XDG_CACHE_HOME\n || !!env.XDG_STATE_HOME\n || !!env.ZIDANE_CONFIG_DIR\n || !!env.ZIDANE_DATA_DIR\n || !!env.ZIDANE_STATE_DIR\n || !!env.ZIDANE_CACHE_DIR\n\n if (hasXdgSignal) {\n return {\n configDir: env.ZIDANE_CONFIG_DIR\n ?? resolve(env.XDG_CONFIG_HOME || resolve(home, '.config'), prefixBare),\n dataDir: env.ZIDANE_DATA_DIR\n ?? resolve(env.XDG_DATA_HOME || resolve(home, '.local', 'share'), prefixBare),\n stateDir: env.ZIDANE_STATE_DIR\n ?? resolve(env.XDG_STATE_HOME || resolve(home, '.local', 'state'), prefixBare),\n cacheDir: env.ZIDANE_CACHE_DIR\n ?? resolve(env.XDG_CACHE_HOME || resolve(home, '.cache'), prefixBare),\n mode: 'xdg',\n }\n }\n\n // Branch 4 — default (mac/windows, no XDG signal, no existing dir).\n // Same as the day-one experience: everything under `~/<prefix>/`.\n return single(legacyHomeDir, 'default')\n}\n\nfunction single(base: string, mode: StorageMode): StorageDirs {\n return {\n configDir: base,\n dataDir: base,\n stateDir: base,\n cacheDir: base,\n mode,\n }\n}\n","/**\n * The Agent Plugins package boundary.\n *\n * The spec's central filesystem rule: \"Every package file a client\n * discovers, reads, or executes must remain inside the filesystem-resolved\n * root after resolving symlinks, junctions, reparse points, and equivalent\n * mechanisms.\"\n *\n * Lexical containment (`../skills/validate.ts`'s `validateResourcePath`) is\n * NOT sufficient here — a `skills` symlink pointing at `~/.ssh` passes every\n * lexical check. So each package path is resolved through `realpath` and\n * re-tested against the realpath-resolved root, and the required filesystem\n * kind is asserted with a symlink-FOLLOWING `stat` (the spec wants\n * `SKILL.md` to be a regular file, not a fifo or a directory wearing the\n * name).\n *\n * Containment is tested with `path.relative` rather than a string prefix so\n * `/plugin-root` vs `/plugin-root-evil` can't be confused and Windows\n * separators are handled by the platform.\n */\n\nimport { realpath, stat } from 'node:fs/promises'\nimport { isAbsolute, relative, resolve } from 'node:path'\n\n/**\n * A resolved plugin root. Hold one of these for the lifetime of a load and\n * pass it to every path check, so `realpath(root)` is paid once rather than\n * per package file.\n */\nexport interface PluginBoundary {\n /** Plugin root as requested, made absolute (symlinks NOT resolved). */\n dir: string\n /** Symlink-resolved plugin root. The boundary every package path is tested against. */\n root: string\n}\n\n/**\n * Why a package path is unusable.\n *\n * - `missing` the path does not exist. Often benign (a missing fixed\n * location is valid per spec), so callers decide severity.\n * - `escaped` the path resolved outside the plugin root.\n * - `wrong-kind` the path exists but is not the required filesystem kind.\n */\nexport type PackagePathFailure = 'missing' | 'escaped' | 'wrong-kind'\n\nexport type PackagePathResult\n = | { ok: true, real: string }\n | { ok: false, reason: PackagePathFailure }\n\n/** Filesystem kind a package path is required to have. */\nexport type PackagePathKind = 'file' | 'directory'\n\n/**\n * Resolve the plugin root itself. Returns `null` when the root does not\n * exist or is not a directory — the caller turns that into a plugin-level\n * rejection, since there is nothing to load.\n */\nexport async function resolvePluginBoundary(dir: string): Promise<PluginBoundary | null> {\n const absolute = resolve(dir)\n try {\n const root = await realpath(absolute)\n if (!(await stat(root)).isDirectory())\n return null\n return { dir: absolute, root }\n }\n catch {\n return null\n }\n}\n\n/**\n * True when `real` (an already symlink-resolved path) lives at or under\n * `root` (likewise resolved).\n */\nexport function isWithin(root: string, real: string): boolean {\n const rel = relative(root, real)\n // `''` is the root itself; a `..` lead or an absolute result means the\n // target sits outside (the latter happens across Windows drives).\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))\n}\n\n/**\n * Symlink-resolve `target` and confirm it stays inside the boundary.\n *\n * Use this for paths whose filesystem kind doesn't matter or that may not\n * exist yet (Phase 3's `cwd` handling); otherwise prefer\n * {@link resolvePackagePath}, which also asserts the kind.\n */\nexport async function realPathWithin(\n boundary: PluginBoundary,\n target: string,\n): Promise<PackagePathResult> {\n let real: string\n try {\n real = await realpath(target)\n }\n catch {\n return { ok: false, reason: 'missing' }\n }\n if (!isWithin(boundary.root, real))\n return { ok: false, reason: 'escaped' }\n return { ok: true, real }\n}\n\n/**\n * Resolve a package path and assert its filesystem kind.\n *\n * `stat` (not `lstat`) is deliberate: a symlink to a regular file INSIDE the\n * root is legitimate packaging, and containment is already enforced against\n * the resolved target. What we reject is the kind mismatch the spec calls\n * out — `skills` as a regular file, `SKILL.md` as a directory or a fifo.\n */\nexport async function resolvePackagePath(\n boundary: PluginBoundary,\n target: string,\n kind: PackagePathKind,\n): Promise<PackagePathResult> {\n const within = await realPathWithin(boundary, target)\n if (!within.ok)\n return within\n try {\n const info = await stat(within.real)\n const matches = kind === 'directory' ? info.isDirectory() : info.isFile()\n if (!matches)\n return { ok: false, reason: 'wrong-kind' }\n }\n catch {\n // Raced away between realpath and stat.\n return { ok: false, reason: 'missing' }\n }\n return within\n}\n","/**\n * Types for the Agent Plugins loader.\n *\n * Implements the Agent Plugins open standard (agent-plugins.org) — a\n * portable package format that places reusable agent components at fixed\n * locations inside a plugin root:\n *\n * plugin.json the closed manifest (identity + metadata)\n * skills/ immediate child dirs holding an Agent Skills `SKILL.md`\n * mcp.json one MCP server configuration document\n *\n * Agent Plugins deliberately does NOT redefine either component format —\n * skills are Agent Skills, MCP config is MCP config. So this module owns\n * only the packaging contract: manifest validation, the filesystem\n * boundary, fixed-location discovery, and the failure-isolation ladder.\n * The component formats themselves route through the existing loaders\n * (`../skills/discovery`, `../mcp`), which is why `LoadedPlugin` hands\n * back plain `SkillConfig` / `McpServerConfig` values that every\n * downstream consumer already understands.\n *\n * Validation here is STRICT, unlike `../skills/discovery` (lenient by\n * design) and `normalizeMcpServers` (heuristic by design). The spec\n * mandates closed schemas with narrow failure boundaries; a plugin is a\n * third-party package, so \"guess what the author meant\" is the wrong\n * default. Leniency is reserved for the two violations the spec\n * explicitly marks non-fatal (see `./manifest`).\n */\n\nimport type { McpServerConfig } from '../mcp'\nimport type { SkillConfig, SkillSource } from '../skills'\n\n// ---------------------------------------------------------------------------\n// Spec versions\n// ---------------------------------------------------------------------------\n\n/**\n * Agent Plugins spec versions this loader implements, newest first.\n *\n * The spec requires clients to select validation rules from the manifest's\n * `$schema` WITHOUT retrieving it, and to let plugins keep targeting older\n * versions under a locally supported compatibility policy. Our policy: a\n * version is supported iff it appears in this list. Adding `1.1.0` later\n * means adding it here plus any rule deltas in `./manifest` — never\n * reinterpreting an already-published identifier, which the spec forbids.\n */\nexport const SUPPORTED_AGENT_PLUGINS_VERSIONS = ['1.0.0'] as const\n\nexport type AgentPluginsVersion = typeof SUPPORTED_AGENT_PLUGINS_VERSIONS[number]\n\n/** Which canonical schema a `$schema` identifier selects. */\nexport type PluginSchemaKind = 'plugin' | 'mcp'\n\n/**\n * Canonical schema identifier for a given document kind + version. Built\n * rather than hardcoded so the two call sites (manifest, mcp.json) can't\n * drift, and so the version cross-check the spec requires between\n * `plugin.json` and `mcp.json` is a plain string comparison.\n */\nexport function agentPluginsSchemaId(kind: PluginSchemaKind, version: string): string {\n return `https://agent-plugins.org/schemas/${version}/${kind}.schema.json`\n}\n\n/**\n * Canonical schema identifier grammar. Anchored and exact — a `$schema`\n * that merely looks similar (http, a trailing slash, a different host) is\n * not the canonical identifier and must not select the contract.\n */\nconst SCHEMA_ID_RE = /^https:\\/\\/agent-plugins\\.org\\/schemas\\/([^/]+)\\/(plugin|mcp)\\.schema\\.json$/\n\n/**\n * Split a canonical `$schema` identifier into its document kind + version.\n * Returns `null` for anything that isn't a canonical identifier; the caller\n * decides whether that's fatal (manifest) or component-scoped (mcp.json).\n *\n * Purely syntactic: it never fetches. The spec forbids retrieving a schema\n * during load, so version support is a lookup against\n * {@link SUPPORTED_AGENT_PLUGINS_VERSIONS}, not a download.\n */\nexport function parseSchemaId(value: string): { kind: PluginSchemaKind, version: string } | null {\n const match = SCHEMA_ID_RE.exec(value)\n if (!match)\n return null\n return { kind: match[2] as PluginSchemaKind, version: match[1]! }\n}\n\n/** True when this loader implements the given Agent Plugins version. */\nexport function isSupportedAgentPluginsVersion(version: string): version is AgentPluginsVersion {\n return (SUPPORTED_AGENT_PLUGINS_VERSIONS as readonly string[]).includes(version)\n}\n\n/**\n * Type label for a rejected JSON value, for diagnostic messages.\n *\n * `typeof` alone is useless in a validator that has to tell an author what\n * they got wrong: `null` and `[]` both report `'object'`, and those are two of\n * the most common mistakes in a hand-written manifest. Shared by the manifest\n * and `mcp.json` validators, which produce the same class of message.\n *\n * Internal — not re-exported from the module barrel.\n */\nexport function describeJsonType(value: unknown): string {\n if (value === null)\n return 'null'\n if (Array.isArray(value))\n return 'array'\n return typeof value\n}\n\n// ---------------------------------------------------------------------------\n// Manifest\n// ---------------------------------------------------------------------------\n\n/** Optional author block. Closed: only these three keys, all strings. */\nexport interface PluginAuthor {\n name?: string\n email?: string\n url?: string\n}\n\n/**\n * A validated `plugin.json`. Only spec fields survive validation —\n * unknown top-level keys are reported and dropped, so consumers can\n * never accidentally depend on a non-portable field.\n *\n * `version` here is the PLUGIN's own version string; the spec version\n * selected by `$schema` lands on {@link PluginManifest.specVersion}.\n */\nexport interface PluginManifest {\n /** Agent Plugins version selected by the manifest's `$schema`. */\n specVersion: AgentPluginsVersion\n /** Plugin name + package identifier (1-64 chars, see `./manifest`). */\n name: string\n version?: string\n description?: string\n author?: PluginAuthor\n homepage?: string\n repository?: string\n license?: string\n keywords?: string[]\n /**\n * Client-owned data keyed by reverse-domain namespace. Values are\n * deliberately `unknown`: the spec says to ignore namespaces the client\n * does not implement WITHOUT validating their contents, so this loader\n * never inspects a member it doesn't own.\n */\n extensions?: Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------\n// Diagnostics\n// ---------------------------------------------------------------------------\n\n/**\n * A load-time finding. Mirrors `SkillDiagnostic`'s shape (severity + stable\n * code + message) so host UIs already rendering skill diagnostics can\n * render these with no new plumbing.\n *\n * `severity: 'error'` on a returned plugin means a narrow boundary fired\n * (a component type disabled, a skill skipped) — NOT that the whole plugin\n * failed. Plugin-level rejection is signalled by `LoadedPlugin.ok === false`.\n */\nexport interface PluginDiagnostic {\n severity: 'warning' | 'error'\n /** Stable machine-readable code (e.g. `manifest-unknown-field`). */\n code: string\n message: string\n /** Manifest field the finding relates to, when applicable. */\n field?: string\n /** Filesystem path the finding relates to, when applicable. */\n path?: string\n}\n\n// ---------------------------------------------------------------------------\n// Component status\n// ---------------------------------------------------------------------------\n\n/**\n * Per-component-type outcome. The spec insists a missing fixed location is\n * NOT an error, and that an invalid one disables only its own component\n * type — so these four states are load-bearing, not cosmetic:\n *\n * - `absent` fixed location not present. Valid.\n * - `loaded` discovered (possibly zero entries, e.g. an empty `skills/`).\n * - `invalid` wrong filesystem kind, or the location escaped the root.\n * - `unsupported` never discovered — not implemented by this client,\n * disabled by the caller, or the plugin was rejected\n * before component discovery ran.\n */\nexport type PluginComponentStatus = 'absent' | 'loaded' | 'invalid' | 'unsupported'\n\n// ---------------------------------------------------------------------------\n// Loaded plugin\n// ---------------------------------------------------------------------------\n\n/**\n * Result of {@link loadAgentPlugin}. Never thrown — a rejected plugin comes\n * back as `ok: false` with the reason in `diagnostics`, because one bad\n * plugin must not take down a host that's loading several.\n */\nexport interface LoadedPlugin {\n /**\n * `false` when a fatal manifest or boundary violation rejected the whole\n * plugin. Components are empty in that case and were never discovered —\n * the spec requires rejection to happen BEFORE component discovery.\n */\n ok: boolean\n /** Plugin root as requested, resolved to an absolute path. */\n dir: string\n /**\n * Symlink-resolved plugin root. Every package path a caller touches must\n * stay under this — it's the boundary the spec defines. Falls back to\n * `dir` when the root itself could not be resolved.\n */\n root: string\n /** Validated manifest. Absent iff `ok === false`. */\n manifest?: PluginManifest\n /** Skills discovered under `skills/`. */\n skills: SkillConfig[]\n /** MCP servers declared by `mcp.json`. */\n mcpServers: McpServerConfig[]\n /** Per-component-type outcome — see {@link PluginComponentStatus}. */\n components: {\n skills: PluginComponentStatus\n mcp: PluginComponentStatus\n }\n /** Everything worth reporting: rejections, disabled components, skipped skills. */\n diagnostics: PluginDiagnostic[]\n}\n\n// ---------------------------------------------------------------------------\n// Load options\n// ---------------------------------------------------------------------------\n\nexport interface LoadAgentPluginOptions {\n /**\n * Source tag stamped onto every discovered skill, driving collision\n * precedence and the `trustProjectSkills` gate downstream. Defaults to\n * `'project'` — the conservative choice, since a plugin sitting in a\n * repo is exactly the untrusted-input case that gate exists for.\n */\n source?: SkillSource\n /**\n * Prefix applied to discovered skill names as `<prefix>-<name>`.\n *\n * Agent Plugins leaves naming to the client, and zidane's skill catalog\n * is a single flat namespace (`discoverSkills` dedupes by name), so two\n * plugins shipping a `deploy` skill would silently shadow one another.\n * Opt in to prefixing when loading untrusted or multiple plugins.\n */\n namePrefix?: string\n /** Discover `skills/`. Default `true`. */\n skills?: boolean\n /** Discover `mcp.json`. Default `true`. */\n mcp?: boolean\n /**\n * Exact directory exposed to MCP servers as `${PLUGIN_DATA}`.\n *\n * Must live outside the plugin root: the spec requires this directory to\n * persist across plugin updates, and an update replaces the package tree.\n * Prefer {@link LoadAgentPluginOptions.dataRoot} unless you need to pin one\n * specific plugin's directory.\n */\n dataDir?: string\n /**\n * Parent directory under which `${PLUGIN_DATA}` is created as\n * `<dataRoot>/<plugin-name>/`.\n *\n * Exists because the plugin name comes from the manifest, which the caller\n * hasn't read yet — a host that wants its own namespace (the extensions\n * seam puts plugin data inside the loading extension's storage root) can\n * supply the parent and let the loader append the name.\n *\n * Defaults to `<dataDir>/plugin-data` from `resolveStorageDirs`. Ignored\n * when {@link LoadAgentPluginOptions.dataDir} is set.\n */\n dataRoot?: string\n}\n","/**\n * `plugin.json` validation.\n *\n * The manifest schema is CLOSED and validated locally — the spec is explicit\n * that a client selects its rules from `$schema` and must not retrieve a\n * schema while loading. So the 1.0.0 contract is encoded here as code rather\n * than fetched or bundled as JSON Schema (the repo has no schema validator,\n * and the document is small and closed enough that hand-rolling it stays\n * honest — same call as the hand-rolled frontmatter parser in\n * `../skills/discovery.ts`).\n *\n * Exactly two violations are non-fatal, per spec:\n *\n * 1. an unknown top-level field → report, ignore, continue\n * 2. a non-object `extensions` → report, ignore, continue\n *\n * Every other schema violation rejects the whole plugin, and rejection\n * happens BEFORE component discovery — a plugin with a broken manifest never\n * gets its skills read or its MCP servers spawned.\n */\n\nimport type { PluginAuthor, PluginDiagnostic, PluginManifest } from './types'\nimport {\n agentPluginsSchemaId,\n describeJsonType,\n isSupportedAgentPluginsVersion,\n parseSchemaId,\n SUPPORTED_AGENT_PLUGINS_VERSIONS,\n} from './types'\n\n/**\n * Plugin name grammar, lifted from the canonical schema: 1-64 chars,\n * lowercase alphanumerics plus `-` and `.`, alphanumeric at both ends, and\n * no `--` or `..` anywhere (the negative lookahead).\n *\n * Length is checked separately so an over-long name gets a message about\n * length instead of a generic \"doesn't match the grammar\".\n */\nconst PLUGIN_NAME_RE = /^(?!.*(?:--|\\.\\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/\n\nconst NAME_MAX = 64\n\n/** Top-level fields the 1.0.0 manifest permits. Anything else is unknown. */\nconst KNOWN_FIELDS = new Set([\n '$schema',\n 'name',\n 'version',\n 'description',\n 'author',\n 'homepage',\n 'repository',\n 'license',\n 'keywords',\n 'extensions',\n])\n\n/** Optional top-level fields whose value must be a string when present. */\nconst STRING_FIELDS = ['version', 'description', 'homepage', 'repository', 'license'] as const\n\n/** Keys the closed `author` object permits. */\nconst AUTHOR_FIELDS = new Set(['name', 'email', 'url'])\n\nexport type ManifestValidation\n = | { ok: true, manifest: PluginManifest, diagnostics: PluginDiagnostic[] }\n | { ok: false, diagnostics: PluginDiagnostic[] }\n\n/**\n * Parse manifest text, then validate it.\n *\n * A JSON syntax error is fatal — unlike `mcps.json` (where\n * `parseJsonTolerant` repairs copy-paste whitespace artifacts), a plugin\n * manifest is a package file produced by a build or an author's editor, not\n * pasted into a settings box. Repairing it would mean guessing at the\n * contents of a third-party package.\n */\nexport function parsePluginManifest(text: string): ManifestValidation {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n }\n catch (err) {\n return {\n ok: false,\n diagnostics: [{\n severity: 'error',\n code: 'manifest-invalid-json',\n message: `plugin.json is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n }],\n }\n }\n return validatePluginManifest(raw)\n}\n\n/**\n * Validate an already-parsed manifest value against the closed 1.0.0 schema.\n *\n * Fatal violations short-circuit: `$schema` and `name` are checked first\n * because without them there is no contract to validate against and no\n * identity to report problems under.\n */\nexport function validatePluginManifest(raw: unknown): ManifestValidation {\n const diagnostics: PluginDiagnostic[] = []\n\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return {\n ok: false,\n diagnostics: [{\n severity: 'error',\n code: 'manifest-not-object',\n message: `plugin.json must be a JSON object (got ${Array.isArray(raw) ? 'array' : typeof raw}).`,\n }],\n }\n }\n\n const obj = raw as Record<string, unknown>\n\n // --- $schema: selects the contract. No contract, no plugin. ------------\n const schema = obj.$schema\n if (typeof schema !== 'string' || schema.length === 0) {\n return fatal(diagnostics, {\n code: 'manifest-schema-missing',\n message: `plugin.json is missing the required \"$schema\" field. Expected \"${agentPluginsSchemaId('plugin', SUPPORTED_AGENT_PLUGINS_VERSIONS[0])}\".`,\n field: '$schema',\n })\n }\n const parsed = parseSchemaId(schema)\n if (!parsed || parsed.kind !== 'plugin') {\n return fatal(diagnostics, {\n code: 'manifest-schema-unsupported',\n message: `plugin.json \"$schema\" is not a canonical Agent Plugins manifest schema identifier: \"${schema}\".`,\n field: '$schema',\n })\n }\n if (!isSupportedAgentPluginsVersion(parsed.version)) {\n return fatal(diagnostics, {\n code: 'manifest-schema-unsupported',\n message: `plugin.json targets Agent Plugins ${parsed.version}, which this client does not support (supported: ${SUPPORTED_AGENT_PLUGINS_VERSIONS.join(', ')}).`,\n field: '$schema',\n })\n }\n\n // --- name: identity. --------------------------------------------------\n const name = obj.name\n if (typeof name !== 'string') {\n return fatal(diagnostics, {\n code: 'manifest-name-missing',\n message: `plugin.json is missing the required \"name\" field${name === undefined ? '' : ` (got ${typeof name})`}.`,\n field: 'name',\n })\n }\n if (name.length === 0 || name.length > NAME_MAX) {\n return fatal(diagnostics, {\n code: 'manifest-name-invalid',\n message: `Plugin name must be 1-${NAME_MAX} characters (got ${name.length}).`,\n field: 'name',\n })\n }\n if (!PLUGIN_NAME_RE.test(name)) {\n return fatal(diagnostics, {\n code: 'manifest-name-invalid',\n message: `Plugin name \"${name}\" is invalid — use lowercase letters, digits, hyphens and periods, starting and ending alphanumeric, with no \"--\" or \"..\".`,\n field: 'name',\n })\n }\n\n const manifest: PluginManifest = { specVersion: parsed.version, name }\n\n // --- optional strings -------------------------------------------------\n for (const field of STRING_FIELDS) {\n const value = obj[field]\n if (value === undefined)\n continue\n if (typeof value !== 'string') {\n return fatal(diagnostics, {\n code: 'manifest-field-wrong-type',\n message: `plugin.json \"${field}\" must be a string (got ${describeJsonType(value)}).`,\n field,\n })\n }\n manifest[field] = value\n }\n\n // --- keywords ---------------------------------------------------------\n if (obj.keywords !== undefined) {\n if (!Array.isArray(obj.keywords)) {\n return fatal(diagnostics, {\n code: 'manifest-field-wrong-type',\n message: `plugin.json \"keywords\" must be an array of strings (got ${describeJsonType(obj.keywords)}).`,\n field: 'keywords',\n })\n }\n const bad = obj.keywords.findIndex(entry => typeof entry !== 'string')\n if (bad !== -1) {\n return fatal(diagnostics, {\n code: 'manifest-field-wrong-type',\n message: `plugin.json \"keywords[${bad}]\" must be a string (got ${describeJsonType(obj.keywords[bad])}).`,\n field: 'keywords',\n })\n }\n manifest.keywords = [...obj.keywords as string[]]\n }\n\n // --- author (closed object) -------------------------------------------\n if (obj.author !== undefined) {\n const author = obj.author\n if (typeof author !== 'object' || author === null || Array.isArray(author)) {\n return fatal(diagnostics, {\n code: 'manifest-field-wrong-type',\n message: `plugin.json \"author\" must be an object (got ${describeJsonType(author)}).`,\n field: 'author',\n })\n }\n const out: PluginAuthor = {}\n for (const [key, value] of Object.entries(author as Record<string, unknown>)) {\n // `author` is closed by the schema, and an unknown key here is NOT one\n // of the two non-fatal cases (which are scoped to TOP-LEVEL unknown\n // fields) — so this rejects the plugin.\n if (!AUTHOR_FIELDS.has(key)) {\n return fatal(diagnostics, {\n code: 'manifest-author-unknown-field',\n message: `plugin.json \"author.${key}\" is not a permitted field (allowed: ${[...AUTHOR_FIELDS].join(', ')}).`,\n field: 'author',\n })\n }\n if (typeof value !== 'string') {\n return fatal(diagnostics, {\n code: 'manifest-field-wrong-type',\n message: `plugin.json \"author.${key}\" must be a string (got ${describeJsonType(value)}).`,\n field: 'author',\n })\n }\n out[key as keyof PluginAuthor] = value\n }\n manifest.author = out\n }\n\n // --- extensions (non-fatal when not an object) ------------------------\n if (obj.extensions !== undefined) {\n const ext = obj.extensions\n if (typeof ext !== 'object' || ext === null || Array.isArray(ext)) {\n diagnostics.push({\n severity: 'warning',\n code: 'manifest-extensions-not-object',\n message: `plugin.json \"extensions\" must be an object (got ${describeJsonType(ext)}) — ignoring it and continuing to load components.`,\n field: 'extensions',\n })\n }\n else {\n // Member VALUES are intentionally not validated: the spec says to\n // ignore namespaces the client does not implement without validating\n // them, and the normative text governs over the machine-readable\n // schema (which types members as objects). A client that implements a\n // namespace validates its own member at the point of use.\n manifest.extensions = { ...ext as Record<string, unknown> }\n }\n }\n\n // --- unknown top-level fields (non-fatal) -----------------------------\n for (const key of Object.keys(obj)) {\n if (KNOWN_FIELDS.has(key))\n continue\n diagnostics.push({\n severity: 'warning',\n code: 'manifest-unknown-field',\n message: `plugin.json has unknown top-level field \"${key}\" — ignoring it. Client-specific data belongs under \"extensions\".`,\n field: key,\n })\n }\n\n return { ok: true, manifest, diagnostics }\n}\n\nfunction fatal(\n diagnostics: PluginDiagnostic[],\n detail: Omit<PluginDiagnostic, 'severity'>,\n): { ok: false, diagnostics: PluginDiagnostic[] } {\n diagnostics.push({ severity: 'error', ...detail })\n return { ok: false, diagnostics }\n}\n","/**\n * The `mcp.json` component type.\n *\n * This does NOT route through `normalizeMcpServers`. That function is\n * deliberately heuristic — it infers a transport from the presence of\n * `command` / `url`, accepts `httpUrl` / `sseUrl` / `type: 'http'` aliases,\n * and tolerates unknown keys — because its job is making a config pasted\n * from Cursor or Claude Desktop Just Work. The plugin spec wants the exact\n * opposite: a closed document, a closed entry per declared transport, and an\n * unknown field invalidating that ONE entry. Guessing on behalf of a\n * third-party package is how you spawn a command the author didn't write.\n *\n * Three spec rules carry real security weight and are implemented here:\n *\n * 1. **Placeholders.** Only `${PLUGIN_ROOT}` and `${PLUGIN_DATA}`, only in\n * `args`, `env` values and `cwd`. Single-pass and non-recursive, so an\n * expansion can't produce another placeholder. Everything else —\n * `command`, `url`, `headers` — keeps its literal text, which is why\n * the produced configs carry `preExpanded` (see\n * `McpServerConfig.preExpanded`).\n * 2. **stdio resolution.** `command` is ONE executable token: a bare name\n * goes to PATH lookup, a `./`-relative path resolves inside the plugin\n * root. No shell, no argv splitting. `cwd` defaults to the plugin root\n * and must stay within the root or the data directory.\n * 3. **Remote URLs.** HTTPS unless loopback, no userinfo, no fragment, and\n * headers pinned to the configured origin across redirects.\n */\n\nimport type { McpServerConfig } from '../mcp'\nimport type { PluginBoundary } from './boundary'\nimport type { PluginComponentStatus, PluginDiagnostic } from './types'\nimport { readFile, realpath } from 'node:fs/promises'\nimport { isAbsolute, resolve } from 'node:path'\n// Deep import: `../mcp` is a large module and this is a dependency-free leaf,\n// so `zidane/plugins` shouldn't pull the whole MCP runtime for one predicate.\nimport { isAllowedRemoteUrl } from '../mcp/origin-pinned-fetch'\nimport { isWithin, realPathWithin } from './boundary'\nimport { agentPluginsSchemaId, describeJsonType, parseSchemaId } from './types'\n\n/** Fixed location for the MCP component type. */\nexport const PLUGIN_MCP_FILE = 'mcp.json'\n\n/** The only placeholders the spec defines. */\nconst PLUGIN_ROOT_VAR = 'PLUGIN_ROOT'\nconst PLUGIN_DATA_VAR = 'PLUGIN_DATA'\n\n/**\n * Placeholder grammar — deliberately narrower than\n * `expandEnvPlaceholders`'s: exactly the two reserved names, no\n * `:-default` form, no `${env:…}` form. Anything else stays literal.\n */\nconst PLUGIN_VAR_RE = /\\$\\{(PLUGIN_ROOT|PLUGIN_DATA)\\}/g\n\n/** Closed top-level key set for the document. */\nconst DOCUMENT_FIELDS = new Set(['$schema', 'mcpServers'])\n\n/**\n * Closed key set per declared transport.\n *\n * A `Map` rather than an object literal: the keys are attacker-controlled\n * (`type` comes straight out of a third-party `mcp.json`), and `'constructor'\n * in objectLiteral` is `true`, which would sail past the membership check and\n * then blow up on `Object.prototype.constructor.has(...)`.\n */\nconst ENTRY_FIELDS = new Map<string, Set<string>>([\n ['stdio', new Set(['type', 'command', 'args', 'env', 'cwd'])],\n ['streamable-http', new Set(['type', 'url', 'headers'])],\n ['sse', new Set(['type', 'url', 'headers'])],\n])\n\n/**\n * Server-name grammar.\n *\n * `connectMcpServers` namespaces tools as `mcp_<server>_<tool>`, and providers\n * reject a tool name outside the letters / digits / underscore / hyphen shape\n * — rejecting the whole REQUEST, not just the offending tool. A user-authored\n * `mcps.json` has the same sharp edge, but there the user owns the file; a\n * plugin is untrusted input, so an unusable name is rejected per-entry instead\n * of poisoning every run.\n */\nconst SERVER_NAME_RE = /^[a-z0-9][\\w-]{0,63}$/i\n\n/**\n * Keys that hit a prototype setter instead of creating an own property.\n * Same guard the extension registration paths apply to untrusted keys — see\n * `isSafeRecordKey` in `../extensions/register.ts`. Assigning `__proto__` on\n * an object literal silently DISCARDS the value, so without this an env var\n * would just never reach the child process with nothing explaining why.\n */\nconst DANGEROUS_RECORD_KEYS = new Set(['__proto__', 'prototype', 'constructor'])\n\nexport interface PluginMcpResult {\n status: PluginComponentStatus\n servers: McpServerConfig[]\n diagnostics: PluginDiagnostic[]\n}\n\nexport interface LoadPluginMcpOptions {\n boundary: PluginBoundary\n /** Plugin name — prefixes server names when `namePrefix` is set. */\n pluginName: string\n /**\n * Dedicated writable directory exposed as `${PLUGIN_DATA}`. Created on\n * demand, and only when a server actually references it. MUST live outside\n * the plugin root so a plugin update (which replaces the package) does not\n * wipe the data the spec says must persist.\n */\n dataDir: string\n /** Spec version the manifest declared — `mcp.json` must match it. */\n specVersion: string\n /** Prefix applied to server names as `<prefix>-<name>`. */\n namePrefix?: string\n}\n\n/**\n * Load and validate the plugin's `mcp.json`.\n *\n * Status semantics mirror `loadPluginSkills`: a missing file is `absent`\n * (valid), a wrong-kind / escaping / malformed document is `invalid` (this\n * component only), and anything else is `loaded` — even when individual\n * entries were rejected, because per-entry isolation is the point.\n */\nexport async function loadPluginMcp(opts: LoadPluginMcpOptions): Promise<PluginMcpResult> {\n const { boundary, pluginName, dataDir, specVersion, namePrefix } = opts\n const diagnostics: PluginDiagnostic[] = []\n const path = resolve(boundary.root, PLUGIN_MCP_FILE)\n\n const located = await realPathWithin(boundary, path)\n if (!located.ok) {\n if (located.reason === 'missing')\n return { status: 'absent', servers: [], diagnostics }\n diagnostics.push({\n severity: 'error',\n code: 'mcp-file-escapes-root',\n message: `\"${PLUGIN_MCP_FILE}\" resolves outside the plugin root — the MCP component is disabled for this plugin.`,\n path,\n })\n return { status: 'invalid', servers: [], diagnostics }\n }\n\n let raw: unknown\n try {\n raw = JSON.parse(await readFile(located.real, 'utf8'))\n }\n catch (err) {\n diagnostics.push({\n severity: 'error',\n code: 'mcp-invalid-json',\n message: `\"${PLUGIN_MCP_FILE}\" could not be read as JSON: ${err instanceof Error ? err.message : String(err)}`,\n path: located.real,\n })\n return { status: 'invalid', servers: [], diagnostics }\n }\n\n // --- stage 1: the closed top-level document ---------------------------\n const document = validateDocument(raw, specVersion)\n if (!document.ok) {\n diagnostics.push({ severity: 'error', ...document.diagnostic, path: located.real })\n return { status: 'invalid', servers: [], diagnostics }\n }\n\n // --- stage 2: each entry, independently -------------------------------\n //\n // Note what does NOT happen here: the `${PLUGIN_DATA}` directory is not\n // created. Loading resolves the path and stops there, because loading is not\n // consent. A host discovers every plugin on disk in order to learn its name\n // (identity lives in the manifest, so you cannot filter before loading), and\n // the user's `enabledPlugins` gate applies afterwards — so creating the\n // directory here would leave one behind for every plugin the user has\n // switched OFF, on every discovery pass. Creation happens at spawn time in\n // `mcp/index.ts`, the only place that knows a process is actually starting.\n const servers: McpServerConfig[] = []\n for (const [name, entry] of Object.entries(document.servers)) {\n const built = await buildServer({\n name,\n entry,\n boundary,\n dataDir,\n pluginName,\n ...(namePrefix !== undefined ? { namePrefix } : {}),\n })\n if (!built.ok) {\n // Per-entry isolation: one bad server never disables the component.\n diagnostics.push({ severity: 'error', ...built.diagnostic, path: located.real })\n continue\n }\n servers.push(built.config)\n }\n\n return { status: 'loaded', servers, diagnostics }\n}\n\n// ---------------------------------------------------------------------------\n// Stage 1 — document\n// ---------------------------------------------------------------------------\n\ntype DocumentValidation\n = | { ok: true, servers: Record<string, unknown> }\n | { ok: false, diagnostic: Omit<PluginDiagnostic, 'severity'> }\n\nfunction validateDocument(raw: unknown, specVersion: string): DocumentValidation {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return {\n ok: false,\n diagnostic: {\n code: 'mcp-not-object',\n message: `\"${PLUGIN_MCP_FILE}\" must be a JSON object (got ${describeJsonType(raw)}).`,\n },\n }\n }\n const obj = raw as Record<string, unknown>\n\n const schema = obj.$schema\n if (typeof schema !== 'string') {\n return {\n ok: false,\n diagnostic: {\n code: 'mcp-schema-missing',\n message: `\"${PLUGIN_MCP_FILE}\" is missing the required \"$schema\" field. Expected \"${agentPluginsSchemaId('mcp', specVersion)}\".`,\n field: '$schema',\n },\n }\n }\n const parsed = parseSchemaId(schema)\n if (!parsed || parsed.kind !== 'mcp') {\n return {\n ok: false,\n diagnostic: {\n code: 'mcp-schema-unsupported',\n message: `\"${PLUGIN_MCP_FILE}\" \"$schema\" is not a canonical Agent Plugins MCP schema identifier: \"${schema}\".`,\n field: '$schema',\n },\n }\n }\n // The spec requires matching Agent Plugins versions across the two\n // documents — a plugin declaring 1.0.0 rules in the manifest cannot opt a\n // single component into a different contract.\n if (parsed.version !== specVersion) {\n return {\n ok: false,\n diagnostic: {\n code: 'mcp-schema-version-mismatch',\n message: `\"${PLUGIN_MCP_FILE}\" targets Agent Plugins ${parsed.version} but plugin.json targets ${specVersion} — the versions must match.`,\n field: '$schema',\n },\n }\n }\n\n for (const key of Object.keys(obj)) {\n if (!DOCUMENT_FIELDS.has(key)) {\n return {\n ok: false,\n diagnostic: {\n code: 'mcp-unknown-field',\n message: `\"${PLUGIN_MCP_FILE}\" has unknown top-level field \"${key}\".`,\n field: key,\n },\n }\n }\n }\n\n const servers = obj.mcpServers\n if (typeof servers !== 'object' || servers === null || Array.isArray(servers)) {\n return {\n ok: false,\n diagnostic: {\n code: 'mcp-servers-wrong-type',\n message: `\"${PLUGIN_MCP_FILE}\" \"mcpServers\" must be an object (got ${describeJsonType(servers)}).`,\n field: 'mcpServers',\n },\n }\n }\n\n return { ok: true, servers: servers as Record<string, unknown> }\n}\n\n// ---------------------------------------------------------------------------\n// Stage 2 — one entry\n// ---------------------------------------------------------------------------\n\ntype EntryValidation\n = | { ok: true, config: McpServerConfig }\n | { ok: false, diagnostic: Omit<PluginDiagnostic, 'severity'> }\n\nasync function buildServer(opts: {\n name: string\n entry: unknown\n boundary: PluginBoundary\n dataDir: string\n pluginName: string\n namePrefix?: string\n}): Promise<EntryValidation> {\n const { name, entry, boundary, dataDir, namePrefix } = opts\n const reject = (code: string, message: string): EntryValidation => ({\n ok: false,\n diagnostic: { code, message: `Skipped MCP server \"${name}\" — ${message}` },\n })\n\n // Validated in the form it will actually take in the model's tool catalog\n // (`mcp_<serverName>_<tool>`), which means AFTER `namePrefix` is applied:\n // the prefix is part of that string, so a caller-supplied prefix can\n // invalidate a name the plugin itself got right. Catching it here rather\n // than at the provider boundary matters because there an unusable name\n // fails the whole REQUEST, not just the one tool.\n const serverName = namePrefix ? `${namePrefix}-${name}` : name\n if (!SERVER_NAME_RE.test(serverName)) {\n return reject('mcp-entry-name-invalid', namePrefix\n ? `its namespaced name \"${serverName}\" is not usable as a tool prefix — the \"${namePrefix}\" namePrefix must be letters, digits, underscores or hyphens, and the two together at most 64 characters.`\n : 'its name must be 1-64 characters of letters, digits, underscores or hyphens, starting alphanumeric.')\n }\n\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry))\n return reject('mcp-entry-not-object', `its value must be an object (got ${describeJsonType(entry)}).`)\n const obj = entry as Record<string, unknown>\n\n // The declared transport selects the closed key set AND the connection\n // attempt. It is never inferred: an entry without `type` is invalid, full\n // stop, because guessing is how a `url` typo becomes a spawned command.\n const type = typeof obj.type === 'string' ? obj.type : undefined\n const allowed = type === undefined ? undefined : ENTRY_FIELDS.get(type)\n if (type === undefined || !allowed)\n return reject('mcp-entry-transport-invalid', `\"type\" must be one of stdio, streamable-http, sse (got ${type === undefined ? describeJsonType(obj.type) : `\"${type}\"`}).`)\n\n for (const key of Object.keys(obj)) {\n if (!allowed.has(key))\n return reject('mcp-entry-unknown-field', `\"${key}\" is not a permitted field for a ${type} server (allowed: ${[...allowed].join(', ')}).`)\n }\n\n const vars = { [PLUGIN_ROOT_VAR]: boundary.root, [PLUGIN_DATA_VAR]: dataDir }\n\n if (type === 'stdio') {\n // --- command: exactly one executable token -------------------------\n const command = obj.command\n if (typeof command !== 'string' || command.length === 0)\n return reject('mcp-entry-command-invalid', 'a stdio server needs a non-empty \"command\".')\n // Placeholders are NOT expanded in `command`, so a `${PLUGIN_ROOT}` here\n // would be passed to the OS literally. Reject rather than spawn it.\n if (PLUGIN_VAR_RE.test(command)) {\n PLUGIN_VAR_RE.lastIndex = 0\n return reject('mcp-entry-command-invalid', 'placeholders are not expanded in \"command\" — use a \"./\"-relative path or a bare executable name.')\n }\n if (/\\s/.test(command))\n return reject('mcp-entry-command-invalid', `\"command\" must be a single executable token, not a command line (\"${command}\").`)\n const resolvedCommand = await resolveCommand(command, boundary)\n if (!resolvedCommand.ok)\n return reject('mcp-entry-command-invalid', resolvedCommand.error)\n\n // --- args ----------------------------------------------------------\n let args: string[] | undefined\n if (obj.args !== undefined) {\n if (!Array.isArray(obj.args) || obj.args.some(a => typeof a !== 'string'))\n return reject('mcp-entry-args-invalid', '\"args\" must be an array of strings.')\n args = (obj.args as string[]).map(a => expandPluginVars(a, vars))\n }\n\n // --- env -----------------------------------------------------------\n let env: Record<string, string> | undefined\n if (obj.env !== undefined) {\n if (typeof obj.env !== 'object' || obj.env === null || Array.isArray(obj.env))\n return reject('mcp-entry-env-invalid', '\"env\" must be an object of strings.')\n env = {}\n for (const [key, value] of Object.entries(obj.env as Record<string, unknown>)) {\n if (typeof value !== 'string')\n return reject('mcp-entry-env-invalid', `\"env.${key}\" must be a string (got ${describeJsonType(value)}).`)\n // The reserved names are supplied by the client, not the plugin.\n if (key === PLUGIN_ROOT_VAR || key === PLUGIN_DATA_VAR)\n return reject('mcp-entry-env-invalid', `\"env.${key}\" is reserved and cannot be set by a plugin.`)\n if (!isSafeRecordKey(key))\n return reject('mcp-entry-env-invalid', `\"env.${key}\" is not a usable variable name.`)\n env[key] = expandPluginVars(value, vars)\n }\n }\n\n // --- cwd -----------------------------------------------------------\n const cwdResult = await resolveCwd(obj.cwd, boundary, dataDir, vars)\n if (!cwdResult.ok)\n return reject('mcp-entry-cwd-invalid', cwdResult.error)\n\n const config: McpServerConfig = {\n name: serverName,\n transport: 'stdio',\n command: resolvedCommand.command,\n // Reserved variables are written LAST so a plugin cannot shadow them\n // through some other spelling, and so they always describe reality.\n env: { ...env, [PLUGIN_ROOT_VAR]: boundary.root, [PLUGIN_DATA_VAR]: dataDir },\n cwd: cwdResult.cwd,\n preExpanded: true,\n }\n if (args)\n config.args = args\n return { ok: true, config }\n }\n\n // --- remote transports ------------------------------------------------\n const url = obj.url\n if (typeof url !== 'string' || url.length === 0)\n return reject('mcp-entry-url-invalid', `a ${type} server needs a non-empty \"url\".`)\n const checked = validateRemoteUrl(url)\n if (!checked.ok)\n return reject('mcp-entry-url-invalid', checked.error)\n\n let headers: Record<string, string> | undefined\n if (obj.headers !== undefined) {\n if (typeof obj.headers !== 'object' || obj.headers === null || Array.isArray(obj.headers))\n return reject('mcp-entry-headers-invalid', '\"headers\" must be an object of strings.')\n headers = {}\n for (const [key, value] of Object.entries(obj.headers as Record<string, unknown>)) {\n if (!isSafeRecordKey(key))\n return reject('mcp-entry-headers-invalid', `\"headers.${key}\" is not a usable header name.`)\n if (typeof value !== 'string')\n return reject('mcp-entry-headers-invalid', `\"headers.${key}\" must be a string (got ${describeJsonType(value)}).`)\n // Not expanded — spec scopes placeholders to args/env/cwd.\n headers[key] = value\n }\n }\n\n const config: McpServerConfig = {\n name: serverName,\n transport: type === 'sse' ? 'sse' : 'streamable-http',\n url,\n preExpanded: true,\n pinHeaderOrigin: true,\n }\n if (headers)\n config.headers = headers\n return { ok: true, config }\n}\n\n// ---------------------------------------------------------------------------\n// Placeholders\n// ---------------------------------------------------------------------------\n\n/**\n * Substitute the two reserved placeholders in one string.\n *\n * Single-pass by construction (`String.replace` never re-scans its own\n * output), so a `${PLUGIN_ROOT}` whose value somehow contained\n * `${PLUGIN_DATA}` cannot expand twice. Unknown `${...}` text is left\n * verbatim: the spec defines exactly two placeholders, and silently\n * blanking anything else would corrupt legitimate literals.\n */\nexport function expandPluginVars(value: string, vars: Record<string, string>): string {\n return value.replace(PLUGIN_VAR_RE, (match, name: string) => vars[name] ?? match)\n}\n\n// ---------------------------------------------------------------------------\n// stdio resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the single `command` token.\n *\n * A bare name (`uvx`, `node`) is handed to the OS for PATH lookup — the\n * plugin declares a dependency on the host's toolchain, which is normal. A\n * `./`-relative token is a file the PACKAGE ships, so it resolves against\n * the plugin root and must survive the containment check. An absolute path\n * is refused: it is neither a PATH lookup nor a package file, and it is the\n * shape an escape attempt takes.\n */\nasync function resolveCommand(\n command: string,\n boundary: PluginBoundary,\n): Promise<{ ok: true, command: string } | { ok: false, error: string }> {\n if (isAbsolute(command))\n return { ok: false, error: `\"command\" must be a bare executable name or a \"./\"-relative path inside the plugin, not an absolute path (\"${command}\").` }\n\n // Bare token → PATH lookup by the OS. Note `foo/bar` (no leading `./`) is\n // also not a bare name; treat any separator as package-relative.\n if (!command.includes('/') && !command.includes('\\\\'))\n return { ok: true, command }\n\n const target = resolve(boundary.root, command)\n const within = await realPathWithin(boundary, target)\n if (!within.ok) {\n return {\n ok: false,\n error: within.reason === 'escaped'\n ? `\"command\" resolves outside the plugin root (\"${command}\").`\n : `\"command\" does not exist inside the plugin (\"${command}\").`,\n }\n }\n return { ok: true, command: within.real }\n}\n\n/**\n * Resolve `cwd`, defaulting to the plugin root.\n *\n * The authored form is constrained to `./…`, `${PLUGIN_ROOT}…` or\n * `${PLUGIN_DATA}…`, and containment is then verified against BOTH permitted\n * roots — the data directory legitimately sits outside the package.\n *\n * Both a lexical and a post-symlink check run, because neither alone is\n * sufficient: `cwd` may not exist yet (a server that creates its own working\n * directory on first run), so realpath cannot be the only gate; but the data\n * directory is writable BY the MCP server, so a server can plant a\n * `${PLUGIN_DATA}/work → /` symlink on one run and get `cwd=/` on the next\n * unless the resolved target is re-checked.\n */\nasync function resolveCwd(\n raw: unknown,\n boundary: PluginBoundary,\n dataDir: string,\n vars: Record<string, string>,\n): Promise<{ ok: true, cwd: string } | { ok: false, error: string }> {\n if (raw === undefined)\n return { ok: true, cwd: boundary.root }\n if (typeof raw !== 'string' || raw.length === 0)\n return { ok: false, error: '\"cwd\" must be a non-empty string.' }\n\n const startsWithVar = raw.startsWith(`\\${${PLUGIN_ROOT_VAR}}`) || raw.startsWith(`\\${${PLUGIN_DATA_VAR}}`)\n if (!raw.startsWith('./') && !startsWithVar)\n return { ok: false, error: `\"cwd\" must start with \"./\", \"\\${${PLUGIN_ROOT_VAR}}\" or \"\\${${PLUGIN_DATA_VAR}}\" (got \"${raw}\").` }\n\n const expanded = expandPluginVars(raw, vars)\n const absolute = isAbsolute(expanded) ? expanded : resolve(boundary.root, expanded)\n\n // Lexical, against the paths the placeholders actually produced.\n if (!isWithin(boundary.root, absolute) && !isWithin(dataDir, absolute))\n return { ok: false, error: `\"cwd\" escapes both the plugin root and the plugin data directory (\"${raw}\").` }\n\n // Post-symlink. `boundary.root` is already realpath-resolved; the data\n // directory is resolved here so a home path that itself traverses a symlink\n // (`/home` → `/usr/home`) doesn't make every comparison fail.\n const real = await realpathOrNull(absolute)\n if (real !== null) {\n const realDataDir = await realpathOrNull(dataDir) ?? dataDir\n if (!isWithin(boundary.root, real) && !isWithin(realDataDir, real))\n return { ok: false, error: `\"cwd\" resolves outside the plugin root and the plugin data directory via a symlink (\"${raw}\").` }\n }\n\n return { ok: true, cwd: absolute }\n}\n\n/** `realpath`, or `null` when the path doesn't exist yet. */\nasync function realpathOrNull(target: string): Promise<string | null> {\n try {\n return await realpath(target)\n }\n catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Remote URLs\n// ---------------------------------------------------------------------------\n\n/**\n * Enforce the spec's remote-endpoint requirements: parseable, HTTPS unless\n * loopback, no embedded credentials, no fragment.\n *\n * Reachability (scheme + host) is decided by {@link isAllowedRemoteUrl}, the\n * single encoding of that policy — `originPinnedFetch` applies the same\n * predicate per redirect hop, so a URL refused here can't be reached by\n * redirect either. Only the message selection lives here; the userinfo and\n * fragment rules are authoring-only and have no redirect equivalent.\n */\nfunction validateRemoteUrl(raw: string): { ok: true } | { ok: false, error: string } {\n let url: URL\n try {\n url = new URL(raw)\n }\n catch {\n return { ok: false, error: `\"url\" is not a valid absolute URL (\"${raw}\").` }\n }\n if (!isAllowedRemoteUrl(url)) {\n return {\n ok: false,\n error: url.protocol === 'http:'\n ? `\"url\" must use https for non-loopback hosts (\"${raw}\").`\n : `\"url\" must use http or https (got \"${url.protocol}\").`,\n }\n }\n if (url.username !== '' || url.password !== '')\n return { ok: false, error: '\"url\" must not embed userinfo credentials.' }\n if (url.hash !== '')\n return { ok: false, error: '\"url\" must not contain a fragment.' }\n return { ok: true }\n}\n\n/** Reject keys that would hit a prototype setter instead of the record. */\nfunction isSafeRecordKey(key: string): boolean {\n return key.length > 0 && !DANGEROUS_RECORD_KEYS.has(key)\n}\n","/**\n * The `skills/` component type.\n *\n * Agent Plugins does not redefine the skill format — it defines only WHERE\n * skills live and HOW failures are isolated. So the format itself routes\n * through `parseSkillFile`, the same lenient Agent Skills parser that reads\n * `~/.agents/skills`, and this module contributes exactly two things the\n * plugin spec adds on top:\n *\n * 1. Immediate children only. `findSkillDirs` in `../skills/discovery.ts`\n * recurses four levels deep (correct for a user's `skills/` tree, where\n * category subdirectories are idiomatic); the plugin spec forbids\n * searching nested descendants, so discovery here is strictly depth-1.\n * 2. Boundary + kind enforcement per entry, with per-skill isolation: one\n * invalid or escaping skill is skipped, its siblings still load.\n */\n\nimport type { SkillConfig, SkillSource } from '../skills'\nimport type { PluginBoundary } from './boundary'\nimport type { PluginComponentStatus, PluginDiagnostic } from './types'\nimport { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { parseSkillFile } from '../skills'\nimport { resolvePackagePath } from './boundary'\n\n/** Fixed location for the skills component type. */\nexport const PLUGIN_SKILLS_DIR = 'skills'\n\n/** Spec cap on a skill name, re-checked after a `namePrefix` is applied. */\nconst SKILL_NAME_MAX = 64\n\nexport interface PluginSkillsResult {\n status: PluginComponentStatus\n skills: SkillConfig[]\n diagnostics: PluginDiagnostic[]\n}\n\n/**\n * Discover every skill in the plugin's `skills/` directory.\n *\n * Status semantics follow the spec's failure ladder:\n * - `skills/` missing → `absent` (valid; not an error)\n * - `skills/` not a directory → `invalid` (this component type only)\n * - `skills/` escapes the root → `invalid` (this component type only)\n * - otherwise → `loaded`, possibly with zero skills\n */\nexport async function loadPluginSkills(opts: {\n boundary: PluginBoundary\n /** Plugin name, stamped on each skill as `metadata['zidane.plugin']`. */\n pluginName: string\n /** Source tag for the produced skills. Default `'project'`. */\n source?: SkillSource\n /** Optional `<prefix>-<name>` rename — see `LoadAgentPluginOptions.namePrefix`. */\n namePrefix?: string\n}): Promise<PluginSkillsResult> {\n const { boundary, pluginName, source = 'project', namePrefix } = opts\n const diagnostics: PluginDiagnostic[] = []\n const dir = join(boundary.root, PLUGIN_SKILLS_DIR)\n\n const located = await resolvePackagePath(boundary, dir, 'directory')\n if (!located.ok) {\n if (located.reason === 'missing')\n return { status: 'absent', skills: [], diagnostics }\n diagnostics.push({\n severity: 'error',\n code: located.reason === 'escaped' ? 'skills-dir-escapes-root' : 'skills-dir-wrong-kind',\n message: located.reason === 'escaped'\n ? `\"${PLUGIN_SKILLS_DIR}/\" resolves outside the plugin root — the skills component is disabled for this plugin.`\n : `\"${PLUGIN_SKILLS_DIR}\" exists but is not a directory — the skills component is disabled for this plugin.`,\n path: dir,\n })\n return { status: 'invalid', skills: [], diagnostics }\n }\n\n let entries: string[]\n try {\n entries = await readdir(located.real)\n }\n catch (err) {\n diagnostics.push({\n severity: 'error',\n code: 'skills-dir-unreadable',\n message: `Could not read \"${PLUGIN_SKILLS_DIR}/\": ${err instanceof Error ? err.message : String(err)}`,\n path: located.real,\n })\n return { status: 'invalid', skills: [], diagnostics }\n }\n\n const skills: SkillConfig[] = []\n // `readdir` order is filesystem-dependent; sort so a plugin's skills land\n // in the catalog deterministically (and so collision precedence between\n // two same-named skills in one plugin is stable rather than inode-order).\n for (const entry of entries.sort()) {\n const child = join(located.real, entry)\n const childDir = await resolvePackagePath(boundary, child, 'directory')\n if (!childDir.ok) {\n // A non-directory child (`README.md`, `.DS_Store`) simply isn't a\n // skill — silent. An ESCAPING child is the spec's \"deny access for\n // other escaping package paths\" boundary and worth surfacing.\n if (childDir.reason === 'escaped') {\n diagnostics.push({\n severity: 'warning',\n code: 'skill-dir-escapes-root',\n message: `Skipped \"${PLUGIN_SKILLS_DIR}/${entry}\" — it resolves outside the plugin root.`,\n path: child,\n })\n }\n continue\n }\n\n const skillFile = join(childDir.real, 'SKILL.md')\n const located2 = await resolvePackagePath(boundary, skillFile, 'file')\n if (!located2.ok) {\n // Missing SKILL.md means \"this directory is not a skill\" — per spec an\n // immediate child is a skill only when SKILL.md resolves to a regular\n // file. Silent, because bundling a non-skill directory is legal.\n if (located2.reason === 'escaped') {\n diagnostics.push({\n severity: 'error',\n code: 'skill-escapes-root',\n message: `Skipped skill \"${entry}\" — its SKILL.md resolves outside the plugin root.`,\n path: skillFile,\n })\n }\n else if (located2.reason === 'wrong-kind') {\n diagnostics.push({\n severity: 'warning',\n code: 'skill-file-wrong-kind',\n message: `Skipped \"${PLUGIN_SKILLS_DIR}/${entry}\" — its SKILL.md is not a regular file.`,\n path: skillFile,\n })\n }\n continue\n }\n\n // Parsed with the boundary-resolved path so `baseDir` (which gates\n // `skills_read` / `skills_run_script`) is anchored inside the root.\n //\n // `parseSkillFile` returns `null` for an invalid skill but still THROWS on\n // an unreadable file (permissions, a raced unlink, a device node). Both are\n // \"skip this skill\", never \"fail the plugin\".\n let parsed: SkillConfig | null\n try {\n parsed = await parseSkillFile(located2.real, { source })\n }\n catch (err) {\n diagnostics.push({\n severity: 'error',\n code: 'skill-unreadable',\n message: `Skipped skill \"${entry}\" — its SKILL.md could not be read: ${err instanceof Error ? err.message : String(err)}`,\n path: located2.real,\n })\n continue\n }\n if (!parsed) {\n diagnostics.push({\n severity: 'error',\n code: 'skill-invalid',\n message: `Skipped skill \"${entry}\" — its SKILL.md is not a valid Agent Skill (missing description, or unparseable frontmatter).`,\n path: located2.real,\n })\n continue\n }\n\n skills.push(stamp(parsed, { pluginName, namePrefix, entry, diagnostics }))\n }\n\n return { status: 'loaded', skills, diagnostics }\n}\n\n/**\n * Attach plugin provenance and apply the optional name prefix.\n *\n * Provenance goes in `metadata` under the `zidane.` prefix the Agent Skills\n * spec reserves for client-specific keys (see `../skills/types.ts`), so the\n * skill stays spec-conformant while a host UI can still say which plugin\n * shipped it.\n */\nfunction stamp(skill: SkillConfig, ctx: {\n pluginName: string\n namePrefix?: string\n entry: string\n diagnostics: PluginDiagnostic[]\n}): SkillConfig {\n const name = ctx.namePrefix ? `${ctx.namePrefix}-${skill.name}` : skill.name\n if (name.length > SKILL_NAME_MAX) {\n ctx.diagnostics.push({\n severity: 'warning',\n code: 'skill-name-too-long',\n message: `Prefixed skill name \"${name}\" exceeds the ${SKILL_NAME_MAX}-character spec limit. Loading anyway.`,\n })\n }\n return {\n ...skill,\n name,\n metadata: { ...skill.metadata, 'zidane.plugin': ctx.pluginName },\n }\n}\n","/**\n * Load one Agent Plugin from a directory.\n *\n * Order is mandated by the spec: establish the package boundary, load and\n * validate `plugin.json`, and only then discover components. A plugin whose\n * manifest is rejected never has its skills read or its MCP servers spawned.\n *\n * Nothing here throws for plugin-level problems. A host loading several\n * plugins must not lose the good ones to one bad package, so a rejection\n * comes back as `{ ok: false, diagnostics }`.\n */\n\nimport type { ResolveStorageDirsOptions } from '../chat/xdg'\nimport type { LoadAgentPluginOptions, LoadedPlugin, PluginDiagnostic } from './types'\nimport { readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { resolveStorageDirs } from '../chat/xdg'\nimport { resolvePackagePath, resolvePluginBoundary } from './boundary'\nimport { parsePluginManifest } from './manifest'\nimport { loadPluginMcp } from './mcp'\nimport { loadPluginSkills } from './skills'\n\n/** Fixed location of the plugin manifest. */\nexport const PLUGIN_MANIFEST_FILE = 'plugin.json'\n\n/**\n * Default parent of every plugin's `${PLUGIN_DATA}` directory.\n *\n * Deliberately OUTSIDE any plugin root: the spec requires the data directory\n * to persist across plugin updates, and an update replaces the package tree.\n * Keyed by plugin name so two copies of the same plugin (project + user)\n * share state, which is what an author storing a cache or a token expects.\n *\n * Routed through `resolveStorageDirs` rather than hardcoding `~/.zidane` so it\n * honours `ZIDANE_STORAGE_DIR` and the XDG dirs like every other persisted\n * location — otherwise an XDG-mode install would scatter plugin data into a\n * `~/.zidane` nothing else in the app touches.\n *\n * NB: `resolveStorageDirs` does NOT read `ZIDANE_PREFIX`; it defaults `prefix`\n * to `.zidane`. Callers with a configured prefix must pass it, or plugin data\n * lands beside a prefix the rest of the install doesn't use.\n */\nexport function defaultPluginDataRoot(opts: ResolveStorageDirsOptions = {}): string {\n return join(resolveStorageDirs(opts).dataDir, 'plugin-data')\n}\n\n/**\n * Load an Agent Plugin from `dir`.\n *\n * @returns A {@link LoadedPlugin}. Check `ok` before trusting `manifest`;\n * check `components` to tell \"the plugin ships no skills\" (`absent`) from\n * \"its skills were rejected\" (`invalid`).\n */\nexport async function loadAgentPlugin(\n dir: string,\n opts: LoadAgentPluginOptions = {},\n): Promise<LoadedPlugin> {\n const diagnostics: PluginDiagnostic[] = []\n\n const boundary = await resolvePluginBoundary(dir)\n if (!boundary) {\n return rejected(resolve(dir), resolve(dir), [{\n severity: 'error',\n code: 'plugin-root-unreadable',\n message: `Plugin root \"${dir}\" does not exist or is not a directory.`,\n path: resolve(dir),\n }])\n }\n\n // --- manifest ---------------------------------------------------------\n const manifestPath = join(boundary.root, PLUGIN_MANIFEST_FILE)\n const located = await resolvePackagePath(boundary, manifestPath, 'file')\n if (!located.ok) {\n return rejected(boundary.dir, boundary.root, [{\n severity: 'error',\n code: located.reason === 'escaped' ? 'manifest-escapes-root' : 'manifest-missing',\n message: located.reason === 'escaped'\n // Boundary ladder rung 1: a manifest resolving outside the root\n // rejects the plugin outright — we will not read a package file\n // from somewhere the package doesn't own.\n ? `${PLUGIN_MANIFEST_FILE} resolves outside the plugin root.`\n : located.reason === 'wrong-kind'\n ? `${PLUGIN_MANIFEST_FILE} exists but is not a regular file.`\n : `No ${PLUGIN_MANIFEST_FILE} at the plugin root — not an Agent Plugin.`,\n path: manifestPath,\n }])\n }\n\n let text: string\n try {\n text = await readFile(located.real, 'utf8')\n }\n catch (err) {\n return rejected(boundary.dir, boundary.root, [{\n severity: 'error',\n code: 'manifest-unreadable',\n message: `Could not read ${PLUGIN_MANIFEST_FILE}: ${err instanceof Error ? err.message : String(err)}`,\n path: located.real,\n }])\n }\n\n const validated = parsePluginManifest(text)\n diagnostics.push(...validated.diagnostics)\n if (!validated.ok)\n return rejected(boundary.dir, boundary.root, diagnostics)\n\n const { manifest } = validated\n const result: LoadedPlugin = {\n ok: true,\n dir: boundary.dir,\n root: boundary.root,\n manifest,\n skills: [],\n mcpServers: [],\n components: { skills: 'unsupported', mcp: 'unsupported' },\n diagnostics,\n }\n\n // --- components -------------------------------------------------------\n //\n // Each discovery pass is wrapped so the never-throws contract is ENFORCED\n // rather than merely intended. Both passes walk attacker-controlled JSON and\n // filesystem state, so an unexpected throw (an unreadable SKILL.md, a raced\n // unlink, a shape no validator anticipated) is a question of when, not if —\n // and it would otherwise escape into `setup()` and fail the whole extension.\n // The narrowest boundary that still holds is the component type.\n if (opts.skills !== false) {\n await guardComponent(result, 'skills', diagnostics, async () => {\n const skills = await loadPluginSkills({\n boundary,\n pluginName: manifest.name,\n ...(opts.source !== undefined ? { source: opts.source } : {}),\n ...(opts.namePrefix !== undefined ? { namePrefix: opts.namePrefix } : {}),\n })\n result.components.skills = skills.status\n result.skills = skills.skills\n diagnostics.push(...skills.diagnostics)\n })\n }\n\n if (opts.mcp !== false) {\n await guardComponent(result, 'mcp', diagnostics, async () => {\n const mcp = await loadPluginMcp({\n boundary,\n pluginName: manifest.name,\n dataDir: opts.dataDir ?? join(opts.dataRoot ?? defaultPluginDataRoot(), manifest.name),\n specVersion: manifest.specVersion,\n ...(opts.namePrefix !== undefined ? { namePrefix: opts.namePrefix } : {}),\n })\n result.components.mcp = mcp.status\n result.mcpServers = mcp.servers\n diagnostics.push(...mcp.diagnostics)\n })\n }\n\n return result\n}\n\n/**\n * Run one component-discovery pass, converting an unexpected throw into an\n * `invalid` component plus a diagnostic. Partial results the pass already\n * assigned are dropped, so a half-discovered component never looks loaded.\n *\n * No input reachable through this module's public API is known to trigger it:\n * both component loaders catch their own filesystem and parse failures, which\n * is exactly the property their tests assert. It is kept deliberately, not\n * abandoned — `loadAgentPlugin` promises never to throw for plugin-level\n * problems, and that promise should survive a future component type whose\n * loader forgets a `try`. The observable half IS tested: see the \"never throws\"\n * matrix in `test/plugins/load.test.ts`.\n */\nasync function guardComponent(\n result: LoadedPlugin,\n component: 'skills' | 'mcp',\n diagnostics: PluginDiagnostic[],\n run: () => Promise<void>,\n): Promise<void> {\n try {\n await run()\n }\n catch (err) {\n result.components[component] = 'invalid'\n if (component === 'skills')\n result.skills = []\n else\n result.mcpServers = []\n diagnostics.push({\n severity: 'error',\n code: `${component}-discovery-failed`,\n message: `Unexpected error while loading the ${component} component: ${err instanceof Error ? err.message : String(err)}`,\n path: result.root,\n })\n }\n}\n\nfunction rejected(dir: string, root: string, diagnostics: PluginDiagnostic[]): LoadedPlugin {\n return {\n ok: false,\n dir,\n root,\n skills: [],\n mcpServers: [],\n components: { skills: 'unsupported', mcp: 'unsupported' },\n diagnostics,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,mBAAmB,OAAkC,CAAC,GAAgB;CACpF,MAAM,MAAM,KAAK,OAAO,QAAQ;CAChC,MAAM,OAAO,KAAK,QAAQ,QAAQ;CAClC,MAAM,WAAW,KAAK,YAAY,QAAQ;CAQ1C,MAAM,YAAY,KAAK,UAAU;CACjC,MAAM,aAAa,UAAU,QAAQ,OAAO,EAAE;CAK9C,MAAM,qBAAqB,KAAK,cAAc,IAAI;CAClD,IAAI,oBAEF,OAAO,OADM,QAAQ,oBAAoB,SACxB,GAAG,iBAAiB;CAUvC,MAAM,gBAAgB,QAAQ,MAAM,SAAS;CAC7C,IAAI,WAAW,aAAa,GAC1B,OAAO,OAAO,eAAe,iBAAiB;CAoBhD,IAVqB,aAAa,WAC7B,CAAC,CAAC,IAAI,mBACN,CAAC,CAAC,IAAI,iBACN,CAAC,CAAC,IAAI,kBACN,CAAC,CAAC,IAAI,kBACN,CAAC,CAAC,IAAI,qBACN,CAAC,CAAC,IAAI,mBACN,CAAC,CAAC,IAAI,oBACN,CAAC,CAAC,IAAI,kBAGT,OAAO;EACL,WAAW,IAAI,qBACV,QAAQ,IAAI,mBAAmB,QAAQ,MAAM,SAAS,GAAG,UAAU;EACxE,SAAS,IAAI,mBACR,QA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