@draht/coding-agent 2026.7.30 → 2026.9.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (459) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +46 -2
  3. package/agents/debugger.md +12 -1
  4. package/agents/git-committer.md +1 -0
  5. package/agents/implementer.md +20 -0
  6. package/agents/investigator.md +75 -0
  7. package/agents/reviewer.md +7 -0
  8. package/agents/spec-reviewer.md +66 -0
  9. package/agents/verifier.md +4 -3
  10. package/bin/draht-tools.cjs +472 -41
  11. package/dist/agents/debugger.md +12 -1
  12. package/dist/agents/git-committer.md +1 -0
  13. package/dist/agents/implementer.md +20 -0
  14. package/dist/agents/investigator.md +75 -0
  15. package/dist/agents/reviewer.md +7 -0
  16. package/dist/agents/spec-reviewer.md +66 -0
  17. package/dist/agents/verifier.md +4 -3
  18. package/dist/cli/args.d.ts +10 -0
  19. package/dist/cli/args.d.ts.map +1 -1
  20. package/dist/cli/args.js +69 -2
  21. package/dist/cli/args.js.map +1 -1
  22. package/dist/cli/attach-mode.d.ts +61 -0
  23. package/dist/cli/attach-mode.d.ts.map +1 -1
  24. package/dist/cli/attach-mode.js +243 -5
  25. package/dist/cli/attach-mode.js.map +1 -1
  26. package/dist/cli/credential-print.d.ts +1 -1
  27. package/dist/cli/credential-print.d.ts.map +1 -1
  28. package/dist/cli/credential-print.js +5 -4
  29. package/dist/cli/credential-print.js.map +1 -1
  30. package/dist/config.d.ts +9 -0
  31. package/dist/config.d.ts.map +1 -1
  32. package/dist/config.js +31 -4
  33. package/dist/config.js.map +1 -1
  34. package/dist/core/agent-session-runtime.d.ts +17 -1
  35. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  36. package/dist/core/agent-session-runtime.js +87 -30
  37. package/dist/core/agent-session-runtime.js.map +1 -1
  38. package/dist/core/agent-session-services.d.ts +1 -1
  39. package/dist/core/agent-session-services.d.ts.map +1 -1
  40. package/dist/core/agent-session-services.js +1 -0
  41. package/dist/core/agent-session-services.js.map +1 -1
  42. package/dist/core/agent-session.d.ts +35 -16
  43. package/dist/core/agent-session.d.ts.map +1 -1
  44. package/dist/core/agent-session.js +149 -64
  45. package/dist/core/agent-session.js.map +1 -1
  46. package/dist/core/auth-storage.d.ts +5 -1
  47. package/dist/core/auth-storage.d.ts.map +1 -1
  48. package/dist/core/auth-storage.js +72 -15
  49. package/dist/core/auth-storage.js.map +1 -1
  50. package/dist/core/builtins/checkpoints.d.ts +20 -0
  51. package/dist/core/builtins/checkpoints.d.ts.map +1 -0
  52. package/dist/core/builtins/checkpoints.js +161 -0
  53. package/dist/core/builtins/checkpoints.js.map +1 -0
  54. package/dist/core/builtins/duet.d.ts +26 -0
  55. package/dist/core/builtins/duet.d.ts.map +1 -0
  56. package/dist/core/builtins/duet.js +660 -0
  57. package/dist/core/builtins/duet.js.map +1 -0
  58. package/dist/core/builtins/index.d.ts.map +1 -1
  59. package/dist/core/builtins/index.js +7 -1
  60. package/dist/core/builtins/index.js.map +1 -1
  61. package/dist/core/builtins/subagent.d.ts +24 -4
  62. package/dist/core/builtins/subagent.d.ts.map +1 -1
  63. package/dist/core/builtins/subagent.js +278 -35
  64. package/dist/core/builtins/subagent.js.map +1 -1
  65. package/dist/core/checkpoints/checkpoint-cli.d.ts +17 -0
  66. package/dist/core/checkpoints/checkpoint-cli.d.ts.map +1 -0
  67. package/dist/core/checkpoints/checkpoint-cli.js +78 -0
  68. package/dist/core/checkpoints/checkpoint-cli.js.map +1 -0
  69. package/dist/core/checkpoints/checkpoint-manager.d.ts +294 -0
  70. package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -0
  71. package/dist/core/checkpoints/checkpoint-manager.js +865 -0
  72. package/dist/core/checkpoints/checkpoint-manager.js.map +1 -0
  73. package/dist/core/checkpoints/rewind.d.ts +141 -0
  74. package/dist/core/checkpoints/rewind.d.ts.map +1 -0
  75. package/dist/core/checkpoints/rewind.js +246 -0
  76. package/dist/core/checkpoints/rewind.js.map +1 -0
  77. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  78. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  79. package/dist/core/compaction/branch-summarization.js +9 -4
  80. package/dist/core/compaction/branch-summarization.js.map +1 -1
  81. package/dist/core/compaction/compaction.d.ts +5 -0
  82. package/dist/core/compaction/compaction.d.ts.map +1 -1
  83. package/dist/core/compaction/compaction.js +25 -4
  84. package/dist/core/compaction/compaction.js.map +1 -1
  85. package/dist/core/extensions/index.d.ts +1 -1
  86. package/dist/core/extensions/index.d.ts.map +1 -1
  87. package/dist/core/extensions/index.js.map +1 -1
  88. package/dist/core/extensions/loader.d.ts.map +1 -1
  89. package/dist/core/extensions/loader.js +83 -20
  90. package/dist/core/extensions/loader.js.map +1 -1
  91. package/dist/core/extensions/runner.d.ts +13 -2
  92. package/dist/core/extensions/runner.d.ts.map +1 -1
  93. package/dist/core/extensions/runner.js +37 -2
  94. package/dist/core/extensions/runner.js.map +1 -1
  95. package/dist/core/extensions/types.d.ts +189 -6
  96. package/dist/core/extensions/types.d.ts.map +1 -1
  97. package/dist/core/extensions/types.js.map +1 -1
  98. package/dist/core/http-dispatcher.d.ts.map +1 -1
  99. package/dist/core/http-dispatcher.js +7 -0
  100. package/dist/core/http-dispatcher.js.map +1 -1
  101. package/dist/core/index.d.ts +1 -1
  102. package/dist/core/index.d.ts.map +1 -1
  103. package/dist/core/index.js.map +1 -1
  104. package/dist/core/keybindings.d.ts +5 -0
  105. package/dist/core/keybindings.d.ts.map +1 -1
  106. package/dist/core/keybindings.js +1 -0
  107. package/dist/core/keybindings.js.map +1 -1
  108. package/dist/core/model-registry.d.ts +3 -2
  109. package/dist/core/model-registry.d.ts.map +1 -1
  110. package/dist/core/model-registry.js +8 -8
  111. package/dist/core/model-registry.js.map +1 -1
  112. package/dist/core/model-resolver.d.ts.map +1 -1
  113. package/dist/core/model-resolver.js +34 -7
  114. package/dist/core/model-resolver.js.map +1 -1
  115. package/dist/core/model-runtime.d.ts +7 -1
  116. package/dist/core/model-runtime.d.ts.map +1 -1
  117. package/dist/core/model-runtime.js +30 -10
  118. package/dist/core/model-runtime.js.map +1 -1
  119. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  120. package/dist/core/multi-agent/permission-gate.js +4 -3
  121. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  122. package/dist/core/multi-agent/worktree.d.ts +2 -0
  123. package/dist/core/multi-agent/worktree.d.ts.map +1 -1
  124. package/dist/core/multi-agent/worktree.js +2 -2
  125. package/dist/core/multi-agent/worktree.js.map +1 -1
  126. package/dist/core/package-manager.d.ts +7 -1
  127. package/dist/core/package-manager.d.ts.map +1 -1
  128. package/dist/core/package-manager.js +21 -44
  129. package/dist/core/package-manager.js.map +1 -1
  130. package/dist/core/permission-relay/index.d.ts +19 -0
  131. package/dist/core/permission-relay/index.d.ts.map +1 -0
  132. package/dist/core/permission-relay/index.js +49 -0
  133. package/dist/core/permission-relay/index.js.map +1 -0
  134. package/dist/core/permission-relay/relay-ui-context.d.ts +39 -0
  135. package/dist/core/permission-relay/relay-ui-context.d.ts.map +1 -0
  136. package/dist/core/permission-relay/relay-ui-context.js +788 -0
  137. package/dist/core/permission-relay/relay-ui-context.js.map +1 -0
  138. package/dist/core/permission-relay/types.d.ts +222 -0
  139. package/dist/core/permission-relay/types.d.ts.map +1 -0
  140. package/dist/core/permission-relay/types.js +15 -0
  141. package/dist/core/permission-relay/types.js.map +1 -0
  142. package/dist/core/pi-manifest.d.ts +14 -0
  143. package/dist/core/pi-manifest.d.ts.map +1 -0
  144. package/dist/core/pi-manifest.js +35 -0
  145. package/dist/core/pi-manifest.js.map +1 -0
  146. package/dist/core/project-trust.js +2 -2
  147. package/dist/core/project-trust.js.map +1 -1
  148. package/dist/core/resource-loader.d.ts +21 -0
  149. package/dist/core/resource-loader.d.ts.map +1 -1
  150. package/dist/core/resource-loader.js +101 -24
  151. package/dist/core/resource-loader.js.map +1 -1
  152. package/dist/core/sandbox/bash-operations.d.ts +149 -0
  153. package/dist/core/sandbox/bash-operations.d.ts.map +1 -0
  154. package/dist/core/sandbox/bash-operations.js +163 -0
  155. package/dist/core/sandbox/bash-operations.js.map +1 -0
  156. package/dist/core/sandbox/env.d.ts +83 -0
  157. package/dist/core/sandbox/env.d.ts.map +1 -0
  158. package/dist/core/sandbox/env.js +123 -0
  159. package/dist/core/sandbox/env.js.map +1 -0
  160. package/dist/core/sandbox/executor.d.ts +104 -0
  161. package/dist/core/sandbox/executor.d.ts.map +1 -0
  162. package/dist/core/sandbox/executor.js +92 -0
  163. package/dist/core/sandbox/executor.js.map +1 -0
  164. package/dist/core/sandbox/index.d.ts +36 -0
  165. package/dist/core/sandbox/index.d.ts.map +1 -0
  166. package/dist/core/sandbox/index.js +36 -0
  167. package/dist/core/sandbox/index.js.map +1 -0
  168. package/dist/core/sandbox/linux.d.ts +121 -0
  169. package/dist/core/sandbox/linux.d.ts.map +1 -0
  170. package/dist/core/sandbox/linux.js +260 -0
  171. package/dist/core/sandbox/linux.js.map +1 -0
  172. package/dist/core/sandbox/policy.d.ts +142 -0
  173. package/dist/core/sandbox/policy.d.ts.map +1 -0
  174. package/dist/core/sandbox/policy.js +297 -0
  175. package/dist/core/sandbox/policy.js.map +1 -0
  176. package/dist/core/sandbox/real-path.d.ts +112 -0
  177. package/dist/core/sandbox/real-path.d.ts.map +1 -0
  178. package/dist/core/sandbox/real-path.js +158 -0
  179. package/dist/core/sandbox/real-path.js.map +1 -0
  180. package/dist/core/sandbox/seatbelt-profile.d.ts +95 -0
  181. package/dist/core/sandbox/seatbelt-profile.d.ts.map +1 -0
  182. package/dist/core/sandbox/seatbelt-profile.js +239 -0
  183. package/dist/core/sandbox/seatbelt-profile.js.map +1 -0
  184. package/dist/core/sandbox/seatbelt.d.ts +95 -0
  185. package/dist/core/sandbox/seatbelt.d.ts.map +1 -0
  186. package/dist/core/sandbox/seatbelt.js +154 -0
  187. package/dist/core/sandbox/seatbelt.js.map +1 -0
  188. package/dist/core/sandbox/self-test.d.ts +109 -0
  189. package/dist/core/sandbox/self-test.d.ts.map +1 -0
  190. package/dist/core/sandbox/self-test.js +369 -0
  191. package/dist/core/sandbox/self-test.js.map +1 -0
  192. package/dist/core/sandbox/spawn.d.ts +33 -0
  193. package/dist/core/sandbox/spawn.d.ts.map +1 -0
  194. package/dist/core/sandbox/spawn.js +87 -0
  195. package/dist/core/sandbox/spawn.js.map +1 -0
  196. package/dist/core/sdk.d.ts.map +1 -1
  197. package/dist/core/sdk.js +3 -1
  198. package/dist/core/sdk.js.map +1 -1
  199. package/dist/core/session-manager.d.ts +60 -1
  200. package/dist/core/session-manager.d.ts.map +1 -1
  201. package/dist/core/session-manager.js +53 -6
  202. package/dist/core/session-manager.js.map +1 -1
  203. package/dist/core/settings-manager.d.ts +21 -0
  204. package/dist/core/settings-manager.d.ts.map +1 -1
  205. package/dist/core/settings-manager.js +36 -16
  206. package/dist/core/settings-manager.js.map +1 -1
  207. package/dist/core/skills.d.ts +3 -1
  208. package/dist/core/skills.d.ts.map +1 -1
  209. package/dist/core/skills.js +19 -6
  210. package/dist/core/skills.js.map +1 -1
  211. package/dist/core/slash-commands.d.ts.map +1 -1
  212. package/dist/core/slash-commands.js +1 -0
  213. package/dist/core/slash-commands.js.map +1 -1
  214. package/dist/core/soak/soak-log.d.ts +298 -0
  215. package/dist/core/soak/soak-log.d.ts.map +1 -0
  216. package/dist/core/soak/soak-log.js +660 -0
  217. package/dist/core/soak/soak-log.js.map +1 -0
  218. package/dist/core/soak/soak-reader.d.ts +60 -0
  219. package/dist/core/soak/soak-reader.d.ts.map +1 -0
  220. package/dist/core/soak/soak-reader.js +106 -0
  221. package/dist/core/soak/soak-reader.js.map +1 -0
  222. package/dist/core/socket-server/discovery.d.ts +78 -1
  223. package/dist/core/socket-server/discovery.d.ts.map +1 -1
  224. package/dist/core/socket-server/discovery.js +356 -37
  225. package/dist/core/socket-server/discovery.js.map +1 -1
  226. package/dist/core/socket-server/index.d.ts +10 -4
  227. package/dist/core/socket-server/index.d.ts.map +1 -1
  228. package/dist/core/socket-server/index.js +6 -3
  229. package/dist/core/socket-server/index.js.map +1 -1
  230. package/dist/core/socket-server/permission-delivery.d.ts +125 -0
  231. package/dist/core/socket-server/permission-delivery.d.ts.map +1 -0
  232. package/dist/core/socket-server/permission-delivery.js +152 -0
  233. package/dist/core/socket-server/permission-delivery.js.map +1 -0
  234. package/dist/core/socket-server/permission-registry.d.ts +301 -0
  235. package/dist/core/socket-server/permission-registry.d.ts.map +1 -0
  236. package/dist/core/socket-server/permission-registry.js +410 -0
  237. package/dist/core/socket-server/permission-registry.js.map +1 -0
  238. package/dist/core/socket-server/permission-relay.d.ts +81 -0
  239. package/dist/core/socket-server/permission-relay.d.ts.map +1 -0
  240. package/dist/core/socket-server/permission-relay.js +528 -0
  241. package/dist/core/socket-server/permission-relay.js.map +1 -0
  242. package/dist/core/socket-server/safe-text.d.ts +83 -0
  243. package/dist/core/socket-server/safe-text.d.ts.map +1 -0
  244. package/dist/core/socket-server/safe-text.js +277 -0
  245. package/dist/core/socket-server/safe-text.js.map +1 -0
  246. package/dist/core/socket-server/session-integration.d.ts +65 -2
  247. package/dist/core/socket-server/session-integration.d.ts.map +1 -1
  248. package/dist/core/socket-server/session-integration.js +434 -32
  249. package/dist/core/socket-server/session-integration.js.map +1 -1
  250. package/dist/core/socket-server/socket-client.d.ts +21 -2
  251. package/dist/core/socket-server/socket-client.d.ts.map +1 -1
  252. package/dist/core/socket-server/socket-client.js +52 -1
  253. package/dist/core/socket-server/socket-client.js.map +1 -1
  254. package/dist/core/socket-server/socket-server.d.ts +152 -1
  255. package/dist/core/socket-server/socket-server.d.ts.map +1 -1
  256. package/dist/core/socket-server/socket-server.js +775 -26
  257. package/dist/core/socket-server/socket-server.js.map +1 -1
  258. package/dist/core/socket-server/types.d.ts +106 -2
  259. package/dist/core/socket-server/types.d.ts.map +1 -1
  260. package/dist/core/socket-server/types.js +13 -1
  261. package/dist/core/socket-server/types.js.map +1 -1
  262. package/dist/core/system-prompt.d.ts.map +1 -1
  263. package/dist/core/system-prompt.js +8 -9
  264. package/dist/core/system-prompt.js.map +1 -1
  265. package/dist/core/tools/bash.d.ts +1 -1
  266. package/dist/core/tools/bash.d.ts.map +1 -1
  267. package/dist/core/tools/bash.js +5 -2
  268. package/dist/core/tools/bash.js.map +1 -1
  269. package/dist/core/tools/edit.d.ts.map +1 -1
  270. package/dist/core/tools/edit.js +17 -2
  271. package/dist/core/tools/edit.js.map +1 -1
  272. package/dist/core/tools/find.d.ts +3 -0
  273. package/dist/core/tools/find.d.ts.map +1 -1
  274. package/dist/core/tools/find.js +11 -18
  275. package/dist/core/tools/find.js.map +1 -1
  276. package/dist/core/trust-manager.d.ts +6 -4
  277. package/dist/core/trust-manager.d.ts.map +1 -1
  278. package/dist/core/trust-manager.js +55 -21
  279. package/dist/core/trust-manager.js.map +1 -1
  280. package/dist/extensions/index.d.ts.map +1 -1
  281. package/dist/extensions/index.js +5 -1
  282. package/dist/extensions/index.js.map +1 -1
  283. package/dist/extensions/llama/provider.d.ts.map +1 -1
  284. package/dist/extensions/llama/provider.js +5 -1
  285. package/dist/extensions/llama/provider.js.map +1 -1
  286. package/dist/extensions/stub-provider/index.d.ts +9 -0
  287. package/dist/extensions/stub-provider/index.d.ts.map +1 -0
  288. package/dist/extensions/stub-provider/index.js +13 -0
  289. package/dist/extensions/stub-provider/index.js.map +1 -0
  290. package/dist/extensions/stub-provider/provider.d.ts +77 -0
  291. package/dist/extensions/stub-provider/provider.d.ts.map +1 -0
  292. package/dist/extensions/stub-provider/provider.js +193 -0
  293. package/dist/extensions/stub-provider/provider.js.map +1 -0
  294. package/dist/hooks/gsd/draht-quality-gate.js +3 -3
  295. package/dist/index.d.ts +1 -1
  296. package/dist/index.d.ts.map +1 -1
  297. package/dist/index.js.map +1 -1
  298. package/dist/main.d.ts.map +1 -1
  299. package/dist/main.js +242 -45
  300. package/dist/main.js.map +1 -1
  301. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  302. package/dist/modes/interactive/components/config-selector.js +3 -2
  303. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  304. package/dist/modes/interactive/components/extension-selector.d.ts +49 -0
  305. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  306. package/dist/modes/interactive/components/extension-selector.js +202 -5
  307. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  308. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  309. package/dist/modes/interactive/components/session-selector.js +10 -2
  310. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  311. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  312. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  313. package/dist/modes/interactive/components/settings-selector.js +10 -0
  314. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  315. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  316. package/dist/modes/interactive/components/tool-execution.js +10 -1
  317. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  318. package/dist/modes/interactive/components/tree-selector.d.ts +20 -2
  319. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  320. package/dist/modes/interactive/components/tree-selector.js +21 -5
  321. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  322. package/dist/modes/interactive/interactive-mode.d.ts +97 -3
  323. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  324. package/dist/modes/interactive/interactive-mode.js +394 -24
  325. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  326. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  327. package/dist/modes/rpc/rpc-mode.js +165 -7
  328. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  329. package/dist/modes/rpc/rpc-types.d.ts +68 -1
  330. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  331. package/dist/modes/rpc/rpc-types.js.map +1 -1
  332. package/dist/prompts/commands/atomic-commit.md +1 -12
  333. package/dist/prompts/commands/brainstorm.md +12 -15
  334. package/dist/prompts/commands/create-verification-skill.md +108 -0
  335. package/dist/prompts/commands/discuss-phase.md +3 -14
  336. package/dist/prompts/commands/execute-phase.md +3 -11
  337. package/dist/prompts/commands/fix.md +41 -18
  338. package/dist/prompts/commands/grill.md +66 -0
  339. package/dist/prompts/commands/init-project.md +5 -15
  340. package/dist/prompts/commands/map-codebase.md +1 -13
  341. package/dist/prompts/commands/new-project.md +5 -15
  342. package/dist/prompts/commands/next-milestone.md +1 -13
  343. package/dist/prompts/commands/orchestrate.md +1 -1
  344. package/dist/prompts/commands/pause-work.md +1 -13
  345. package/dist/prompts/commands/plan-phase.md +2 -11
  346. package/dist/prompts/commands/progress.md +0 -13
  347. package/dist/prompts/commands/quick.md +3 -11
  348. package/dist/prompts/commands/resolve-conflicts.md +71 -0
  349. package/dist/prompts/commands/resume-work.md +0 -13
  350. package/dist/prompts/commands/review.md +4 -13
  351. package/dist/prompts/commands/triage.md +159 -0
  352. package/dist/prompts/commands/verify-work.md +4 -14
  353. package/dist/prompts/commands/why.md +135 -0
  354. package/dist/skills/atomic-reasoning/SKILL.md +115 -0
  355. package/dist/skills/blast-radius/SKILL.md +55 -0
  356. package/dist/skills/epistemics/SKILL.md +99 -0
  357. package/dist/skills/hexagon-animation/SKILL.md +49 -0
  358. package/dist/skills/hexagon-animation/generate.mjs +81 -0
  359. package/dist/skills/hexagon-animation/template.html +361 -0
  360. package/dist/skills/typescript-discipline/SKILL.md +50 -0
  361. package/dist/skills/typescript-discipline/references/patterns.md +294 -0
  362. package/dist/skills/unslop/SKILL.md +101 -0
  363. package/dist/utils/canonical-path.d.ts +28 -0
  364. package/dist/utils/canonical-path.d.ts.map +1 -0
  365. package/dist/utils/canonical-path.js +90 -0
  366. package/dist/utils/canonical-path.js.map +1 -0
  367. package/dist/utils/child-process.d.ts +12 -1
  368. package/dist/utils/child-process.d.ts.map +1 -1
  369. package/dist/utils/child-process.js +25 -8
  370. package/dist/utils/child-process.js.map +1 -1
  371. package/dist/utils/clipboard.d.ts +1 -1
  372. package/dist/utils/clipboard.d.ts.map +1 -1
  373. package/dist/utils/clipboard.js +22 -2
  374. package/dist/utils/clipboard.js.map +1 -1
  375. package/dist/utils/exif-orientation.d.ts.map +1 -1
  376. package/dist/utils/exif-orientation.js +2 -3
  377. package/dist/utils/exif-orientation.js.map +1 -1
  378. package/dist/utils/paths.d.ts +2 -7
  379. package/dist/utils/paths.d.ts.map +1 -1
  380. package/dist/utils/paths.js +13 -15
  381. package/dist/utils/paths.js.map +1 -1
  382. package/dist/utils/shell.d.ts.map +1 -1
  383. package/dist/utils/shell.js +6 -4
  384. package/dist/utils/shell.js.map +1 -1
  385. package/dist/utils/tools-manager.d.ts.map +1 -1
  386. package/dist/utils/tools-manager.js +3 -5
  387. package/dist/utils/tools-manager.js.map +1 -1
  388. package/docs/attachable-sessions.md +79 -0
  389. package/docs/compaction.md +21 -21
  390. package/docs/containerization.md +23 -23
  391. package/docs/custom-provider.md +16 -16
  392. package/docs/development.md +9 -9
  393. package/docs/docs.json +6 -2
  394. package/docs/duet.md +42 -0
  395. package/docs/extensions.md +58 -58
  396. package/docs/index.md +10 -10
  397. package/docs/json.md +7 -7
  398. package/docs/keybindings.md +6 -5
  399. package/docs/llama-cpp.md +6 -6
  400. package/docs/models.md +6 -6
  401. package/docs/packages.md +43 -43
  402. package/docs/prompt-templates.md +4 -4
  403. package/docs/providers.md +12 -12
  404. package/docs/quickstart.md +32 -32
  405. package/docs/rpc.md +83 -12
  406. package/docs/sdk.md +15 -15
  407. package/docs/security.md +18 -18
  408. package/docs/session-format.md +35 -13
  409. package/docs/sessions.md +17 -14
  410. package/docs/settings.md +25 -18
  411. package/docs/shell-aliases.md +2 -2
  412. package/docs/skills.md +12 -11
  413. package/docs/terminal-setup.md +12 -12
  414. package/docs/termux.md +6 -6
  415. package/docs/themes.md +11 -11
  416. package/docs/tmux.md +4 -4
  417. package/docs/tui.md +5 -5
  418. package/docs/usage.md +50 -50
  419. package/docs/windows.md +2 -2
  420. package/examples/extensions/overlay-qa-tests.ts +3 -3
  421. package/hooks/gsd/draht-quality-gate.js +3 -3
  422. package/package.json +11 -10
  423. package/prompts/commands/atomic-commit.md +1 -12
  424. package/prompts/commands/brainstorm.md +12 -15
  425. package/prompts/commands/create-verification-skill.md +108 -0
  426. package/prompts/commands/discuss-phase.md +3 -14
  427. package/prompts/commands/execute-phase.md +3 -11
  428. package/prompts/commands/fix.md +41 -18
  429. package/prompts/commands/grill.md +66 -0
  430. package/prompts/commands/init-project.md +5 -15
  431. package/prompts/commands/map-codebase.md +1 -13
  432. package/prompts/commands/new-project.md +5 -15
  433. package/prompts/commands/next-milestone.md +1 -13
  434. package/prompts/commands/orchestrate.md +1 -1
  435. package/prompts/commands/pause-work.md +1 -13
  436. package/prompts/commands/plan-phase.md +2 -11
  437. package/prompts/commands/progress.md +0 -13
  438. package/prompts/commands/quick.md +3 -11
  439. package/prompts/commands/resolve-conflicts.md +71 -0
  440. package/prompts/commands/resume-work.md +0 -13
  441. package/prompts/commands/review.md +4 -13
  442. package/prompts/commands/triage.md +159 -0
  443. package/prompts/commands/verify-work.md +4 -14
  444. package/prompts/commands/why.md +135 -0
  445. package/skills/atomic-reasoning/SKILL.md +115 -0
  446. package/skills/blast-radius/SKILL.md +55 -0
  447. package/skills/epistemics/SKILL.md +99 -0
  448. package/skills/hexagon-animation/SKILL.md +49 -0
  449. package/skills/hexagon-animation/generate.mjs +81 -0
  450. package/skills/hexagon-animation/template.html +361 -0
  451. package/skills/typescript-discipline/SKILL.md +50 -0
  452. package/skills/typescript-discipline/references/patterns.md +294 -0
  453. package/skills/unslop/SKILL.md +101 -0
  454. package/dist/prompts/agents/build.md +0 -86
  455. package/dist/prompts/agents/plan.md +0 -79
  456. package/dist/prompts/agents/verify.md +0 -69
  457. package/prompts/agents/build.md +0 -86
  458. package/prompts/agents/plan.md +0 -79
  459. package/prompts/agents/verify.md +0 -69
@@ -8,6 +8,7 @@ import { FileModelsStore, InMemoryCodingAgentModelsStore } from "./models-store.
8
8
  import { composeModelProvider, configuredRequestAuthStatus, resolveCompatibilityRequestConfig, resolveConfiguredModelHeaders, validateExtensionProvider, } from "./provider-composer.js";
9
9
  import { withRemoteCatalog } from "./remote-catalog-provider.js";
10
10
  import { RuntimeCredentials } from "./runtime-credentials.js";
11
+ const DEFAULT_MODEL_REFRESH_TIMEOUT_MS = 15_000;
11
12
  function mergeHeaders(base, override) {
12
13
  if (!base && !override)
13
14
  return undefined;
@@ -36,6 +37,7 @@ export class ModelRuntime {
36
37
  storedProviders: new Set(),
37
38
  auth: new Map(),
38
39
  };
40
+ this.availabilityRefreshSeq = 0;
39
41
  this.credentials = credentials;
40
42
  this.config = config;
41
43
  this.modelsPath = modelsPath;
@@ -66,7 +68,7 @@ export class ModelRuntime {
66
68
  const refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;
67
69
  const controller = refreshFromNetwork ? new AbortController() : undefined;
68
70
  const timeout = controller
69
- ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15_000)
71
+ ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? DEFAULT_MODEL_REFRESH_TIMEOUT_MS)
70
72
  : undefined;
71
73
  try {
72
74
  await runtime.refresh({ allowNetwork: refreshFromNetwork, signal: controller?.signal });
@@ -141,7 +143,7 @@ export class ModelRuntime {
141
143
  available: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),
142
144
  };
143
145
  }
144
- async runAvailabilityRefresh() {
146
+ async runAvailabilityRefresh(seq) {
145
147
  const providers = this.models.getProviders();
146
148
  const [available, checks, credentials] = await Promise.all([
147
149
  this.models.getAvailable(),
@@ -151,6 +153,11 @@ export class ModelRuntime {
151
153
  ])),
152
154
  this.credentials.list(),
153
155
  ]);
156
+ // A newer rebuild was requested while this one was in flight; drop this
157
+ // result so a slow, superseded refresh cannot clobber the snapshot with
158
+ // stale data.
159
+ if (seq !== this.availabilityRefreshSeq)
160
+ return;
154
161
  const auth = new Map(checks);
155
162
  const configuredProviders = new Set(checks
156
163
  .filter((entry) => entry[1] !== undefined)
@@ -164,10 +171,14 @@ export class ModelRuntime {
164
171
  };
165
172
  this.availabilityError = undefined;
166
173
  }
167
- queueAvailabilityRefresh(after) {
168
- const refresh = (after ?? Promise.resolve()).catch(() => { }).then(() => this.runAvailabilityRefresh());
174
+ queueAvailabilityRefresh() {
175
+ const seq = ++this.availabilityRefreshSeq;
176
+ const refresh = this.runAvailabilityRefresh(seq);
169
177
  const recorded = refresh.catch((error) => {
170
- this.availabilityError = error instanceof Error ? error.message : String(error);
178
+ // Only the latest requested rebuild owns the error state.
179
+ if (seq === this.availabilityRefreshSeq) {
180
+ this.availabilityError = error instanceof Error ? error.message : String(error);
181
+ }
171
182
  throw error;
172
183
  });
173
184
  const tracked = recorded.finally(() => {
@@ -179,11 +190,16 @@ export class ModelRuntime {
179
190
  }
180
191
  /** Coalesce concurrent readers onto the pending refresh. */
181
192
  refreshAvailability() {
182
- return this.availabilityRefresh ?? this.queueAvailabilityRefresh(undefined);
183
- }
184
- /** Mutations must not observe an in-flight refresh started before them. */
193
+ return this.availabilityRefresh ?? this.queueAvailabilityRefresh();
194
+ }
195
+ /**
196
+ * Mutations must observe a rebuild that starts after their state change, and a
197
+ * stuck in-flight refresh must not block them. Start a fresh, independent
198
+ * rebuild instead of chaining onto the pending one. The sequence guard in
199
+ * runAvailabilityRefresh ensures a superseded rebuild cannot clobber its result.
200
+ */
185
201
  forceRefreshAvailability() {
186
- return this.queueAvailabilityRefresh(this.availabilityRefresh);
202
+ return this.queueAvailabilityRefresh();
187
203
  }
188
204
  getProviders() {
189
205
  return this.models.getProviders();
@@ -343,7 +359,11 @@ export class ModelRuntime {
343
359
  }
344
360
  async login(providerId, type, interaction) {
345
361
  const credential = await this.models.login(providerId, type, interaction);
346
- await this.refresh({ allowNetwork: this.modelNetworkEnabled });
362
+ const timeoutSignal = AbortSignal.timeout(DEFAULT_MODEL_REFRESH_TIMEOUT_MS);
363
+ await this.refresh({
364
+ allowNetwork: this.modelNetworkEnabled,
365
+ signal: interaction.signal ? AbortSignal.any([interaction.signal, timeoutSignal]) : timeoutSignal,
366
+ });
347
367
  return credential;
348
368
  }
349
369
  async logout(providerId) {
@@ -1 +1 @@
1
- {"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAaN,YAAY,EACZ,UAAU,EAIV,WAAW,GAWX,MAAM,WAAW,CAAC;AACnB,OAAO,KAAK,sBAAsB,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAGN,oBAAoB,EACpB,2BAA2B,EAE3B,iCAAiC,EACjC,6BAA6B,EAC7B,yBAAyB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AA+B9D,SAAS,YAAY,CACpB,IAAiC,EACjC,QAAqC;IAErC,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IACzC,MAAM,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC;IAC3B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,CAAC;QAC5D,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACrC,KAAK,MAAM,YAAY,IAAI,MAAM,CAAC,IAAI,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ACf,GAAG,IAAI,CAAC,QAAQ;gBAChB,IAAI;gBACJ,mBAAmB;gBACnB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;aACvF,CAAC;QACH,CAAC;QACD,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED,kBAAkB,CAAC,UAAkB;QACpC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5C,CAAC;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype ModelsStreamTransforms,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@draht/ai\";\nimport * as builtinProviderCatalog from \"@draht/ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n}\n\nexport interface ModelRuntimeAuthOverrides {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefresh: Promise<void> | undefined;\n\tprivate availabilityError: string | undefined;\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.DRAHT_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller = refreshFromNetwork ? new AbortController() : undefined;\n\t\tconst timeout = controller\n\t\t\t? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15_000)\n\t\t\t: undefined;\n\t\ttry {\n\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal: controller?.signal });\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list(),\n\t\t]);\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tthis.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(after: Promise<void> | undefined): Promise<void> {\n\t\tconst refresh = (after ?? Promise.resolve()).catch(() => {}).then(() => this.runAvailabilityRefresh());\n\t\tconst recorded = refresh.catch((error) => {\n\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\tthrow error;\n\t\t});\n\t\tconst tracked = recorded.finally(() => {\n\t\t\tif (this.availabilityRefresh === tracked) this.availabilityRefresh = undefined;\n\t\t});\n\t\tthis.availabilityRefresh = tracked;\n\t\treturn tracked;\n\t}\n\n\t/** Coalesce concurrent readers onto the pending refresh. */\n\tprivate refreshAvailability(): Promise<void> {\n\t\treturn this.availabilityRefresh ?? this.queueAvailabilityRefresh(undefined);\n\t}\n\n\t/** Mutations must not observe an in-flight refresh started before them. */\n\tprivate forceRefreshAvailability(): Promise<void> {\n\t\treturn this.queueAvailabilityRefresh(this.availabilityRefresh);\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId);\n\t}\n\n\tasync getAvailable(providerId?: string): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tif (this.availabilityRefresh) {\n\t\t\t\tawait this.availabilityRefresh;\n\t\t\t\treturn this.snapshot.available.filter((model) => model.provider === providerId);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await this.models.getAvailable(providerId);\n\t\t\t} catch (error) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.refreshAvailability();\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync setRuntimeApiKey(\n\t\tproviderId: string,\n\t\tapiKey: string,\n\t\trefreshOptions: ModelsRefreshOptions = {},\n\t): Promise<void> {\n\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\tconst auth = new Map(this.snapshot.auth).set(providerId, { type: \"api_key\", source: \"runtime API key\" });\n\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\tconst storedProviders = new Set(this.snapshot.storedProviders).add(providerId);\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tauth,\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\n\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t};\n\t\tawait this.refresh(refreshOptions);\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise<void> {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tlistCredentials(): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list();\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest(\n\t\tmodel: Model<Api>,\n\t\toptions: (StreamOptions & ModelsStreamTransforms) | undefined,\n\t): Promise<{ provider: Provider; model: Model<Api>; options: StreamOptions }> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...providerOptions } = options ?? {};\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t},\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsStreamTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tasync login(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst credential = await this.models.login(providerId, type, interaction);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\tawait this.models.logout(providerId);\n\t\t// Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.\n\t\tthis.recomposeProvider(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tthis.updateModelSnapshot();\n\t\ttry {\n\t\t\tawait this.forceRefreshAvailability();\n\t\t} catch {\n\t\t\t// Availability errors are recorded by forceRefreshAvailability; refreshed models remain usable.\n\t\t}\n\t\treturn result;\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
1
+ {"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OA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AM,EAAE,qBAAqB;iBAC7B,CAAC,CAAC;YACJ,CAAC;YACD,IAAI,CAAC,QAAQ,GAAG;gBACf,GAAG,IAAI,CAAC,QAAQ;gBAChB,IAAI;gBACJ,mBAAmB;gBACnB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;aACvF,CAAC;QACH,CAAC;QACD,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED,kBAAkB,CAAC,UAAkB;QACpC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAC5C,CAAC;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype ModelsStreamTransforms,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@draht/ai\";\nimport * as builtinProviderCatalog from \"@draht/ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model<Api>[];\n\tavailable: readonly Model<Api>[];\n\tconfiguredProviders: ReadonlySet<string>;\n\tstoredProviders: ReadonlySet<string>;\n\tauth: ReadonlyMap<string, AuthCheck | undefined>;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n}\n\nexport interface ModelRuntimeAuthOverrides {\n\tapiKey?: string;\n\tenv?: Record<string, string>;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nconst DEFAULT_MODEL_REFRESH_TIMEOUT_MS = 15_000;\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap<string, Provider>;\n\tprivate readonly builtins = new Map<string, Provider>();\n\tprivate readonly nativeExtensionProviders = new Map<string, Provider>();\n\tprivate readonly extensionProviders = new Map<string, ProviderConfigInput>();\n\tprivate readonly compositionErrors = new Map<string, string>();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefresh: Promise<void> | undefined;\n\tprivate availabilityRefreshSeq = 0;\n\tprivate availabilityError: string | undefined;\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise<ModelRuntime> {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.DRAHT_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller = refreshFromNetwork ? new AbortController() : undefined;\n\t\tconst timeout = controller\n\t\t\t? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? DEFAULT_MODEL_REFRESH_TIMEOUT_MS)\n\t\t\t: undefined;\n\t\ttry {\n\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal: controller?.signal });\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set<string> {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(seq: number): Promise<void> {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list(),\n\t\t]);\n\t\t// A newer rebuild was requested while this one was in flight; drop this\n\t\t// result so a slow, superseded refresh cannot clobber the snapshot with\n\t\t// stale data.\n\t\tif (seq !== this.availabilityRefreshSeq) return;\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tthis.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(): Promise<void> {\n\t\tconst seq = ++this.availabilityRefreshSeq;\n\t\tconst refresh = this.runAvailabilityRefresh(seq);\n\t\tconst recorded = refresh.catch((error) => {\n\t\t\t// Only the latest requested rebuild owns the error state.\n\t\t\tif (seq === this.availabilityRefreshSeq) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\t\tconst tracked = recorded.finally(() => {\n\t\t\tif (this.availabilityRefresh === tracked) this.availabilityRefresh = undefined;\n\t\t});\n\t\tthis.availabilityRefresh = tracked;\n\t\treturn tracked;\n\t}\n\n\t/** Coalesce concurrent readers onto the pending refresh. */\n\tprivate refreshAvailability(): Promise<void> {\n\t\treturn this.availabilityRefresh ?? this.queueAvailabilityRefresh();\n\t}\n\n\t/**\n\t * Mutations must observe a rebuild that starts after their state change, and a\n\t * stuck in-flight refresh must not block them. Start a fresh, independent\n\t * rebuild instead of chaining onto the pending one. The sequence guard in\n\t * runAvailabilityRefresh ensures a superseded rebuild cannot clobber its result.\n\t */\n\tprivate forceRefreshAvailability(): Promise<void> {\n\t\treturn this.queueAvailabilityRefresh();\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model<Api>[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string): Promise<AuthCheck | undefined> {\n\t\treturn this.models.checkAuth(providerId);\n\t}\n\n\tasync getAvailable(providerId?: string): Promise<readonly Model<Api>[]> {\n\t\tif (providerId) {\n\t\t\tif (this.availabilityRefresh) {\n\t\t\t\tawait this.availabilityRefresh;\n\t\t\t\treturn this.snapshot.available.filter((model) => model.provider === providerId);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await this.models.getAvailable(providerId);\n\t\t\t} catch (error) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.refreshAvailability();\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model<Api>[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tgetAuth(model: Model<Api>, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model<Api>,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise<AuthResult | undefined> {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync setRuntimeApiKey(\n\t\tproviderId: string,\n\t\tapiKey: string,\n\t\trefreshOptions: ModelsRefreshOptions = {},\n\t): Promise<void> {\n\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\tconst auth = new Map(this.snapshot.auth).set(providerId, { type: \"api_key\", source: \"runtime API key\" });\n\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\tconst storedProviders = new Set(this.snapshot.storedProviders).add(providerId);\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tauth,\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\n\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t};\n\t\tawait this.refresh(refreshOptions);\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise<void> {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tlistCredentials(): Promise<readonly CredentialInfo[]> {\n\t\treturn this.credentials.list();\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest(\n\t\tmodel: Model<Api>,\n\t\toptions: (StreamOptions & ModelsStreamTransforms) | undefined,\n\t): Promise<{ provider: Provider; model: Model<Api>; options: StreamOptions }> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...providerOptions } = options ?? {};\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t},\n\t\t};\n\t}\n\n\tstream<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsStreamTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model<TApi>,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions<TApi>,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete<TApi extends Api>(\n\t\tmodel: Model<TApi>,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions<TApi>,\n\t): Promise<AssistantMessage> {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage> {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tasync login(providerId: string, type: AuthType, interaction: AuthInteraction): Promise<Credential> {\n\t\tconst credential = await this.models.login(providerId, type, interaction);\n\t\tconst timeoutSignal = AbortSignal.timeout(DEFAULT_MODEL_REFRESH_TIMEOUT_MS);\n\t\tawait this.refresh({\n\t\t\tallowNetwork: this.modelNetworkEnabled,\n\t\t\tsignal: interaction.signal ? AbortSignal.any([interaction.signal, timeoutSignal]) : timeoutSignal,\n\t\t});\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise<void> {\n\t\tawait this.models.logout(providerId);\n\t\t// Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.\n\t\tthis.recomposeProvider(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise<ModelsRefreshResult> {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tthis.updateModelSnapshot();\n\t\ttry {\n\t\t\tawait this.forceRefreshAvailability();\n\t\t} catch {\n\t\t\t// Availability errors are recorded by forceRefreshAvailability; refreshed models remain usable.\n\t\t}\n\t\treturn result;\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record<string, unknown>)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"permission-gate.d.ts","sourceRoot":"","sources":["../../../src/core/multi-agent/permission-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAQH,qEAAqE;AACrE,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC;AAE5D;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAEzD,eAAO,MAAM,gBAAgB,EAAE,SAAS,cAAc,EAAgC,CAAC;AAEvF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAExE;AAED,iEAAiE;AACjE,MAAM,WAAW,cAAc;IAC9B,wGAAwG;IACxG,IAAI,EAAE,MAAM,CAAC;IACb,6GAA6G;IAC7G,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6GAA6G;IAC7G,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,iDAAiD;IACjD,MAAM,EAAE,gBAAgB,CAAC;CACzB;AAED,yEAAyE;AACzE,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C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiB;IAEtC,YAAY,KAAK,GAAE,cAAc,EAAO,EAAE,OAAO,GAAE,qBAA0B,EAI5E;IAED,+GAA+G;IAC/G,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GAAG,kBAAkB,CAUjF;IAED;;;OAGG;IACH,OAAO,CAAC,SAAS;IAOjB,OAAO,CAAC,eAAe;CAiDvB"}
@@ -61,9 +61,10 @@ const PATH_SCOPED_TOOLS = new Set(["read", "write", "edit"]);
61
61
  const READ_ONLY_PATH_TOOLS = new Set(["grep", "find", "ls"]);
62
62
  /**
63
63
  * Tools that are safe to run without confirmation because the call itself
64
- * touches nothing: `subagent` only delegates — the spawned child process runs
65
- * this same gate over every tool call it actually makes. Explicit rules can
66
- * still `deny`/`approve` these.
64
+ * only delegates: spawned child processes run this same gate over every tool
65
+ * call they actually make. Explicit rules can still `deny`/`approve` these.
66
+ * Duet delegation is deliberately not included because it fans out paid model
67
+ * requests; unmatched duet batches require explicit approval.
67
68
  */
68
69
  const DEFAULT_ALLOWED_TOOLS = new Set(["subagent"]);
69
70
  function isPermissionAction(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"permission-gate.js","sourceRoot":"","sources":["../../../src/core/multi-agent/permission-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAC7B,OAAO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M,EAAE,6BAA6B,QAAQ,wBAAwB,EAAE,CAAC;IACrG,CAAC;CACD","sourcesContent":["/**\n * Permission gate: a three-tier permission system that decides whether a\n * tool call may proceed automatically, must be blocked, or must be confirmed\n * by the user before it runs.\n *\n * SECURITY-CRITICAL: this module gates real bash/write tool calls. Prefer\n * fail-safe (approve/deny) over fail-open (allow) whenever a decision is\n * ambiguous.\n *\n * Configuration is read from `.draht/permissions.yml` (project) and\n * `~/.draht/agent/permissions.yml` (global), e.g.:\n *\n * ```yaml\n * rules:\n * - tool: bash\n * pattern: \"rm -rf *\"\n * action: deny\n * - tool: bash\n * pattern: \"git push *\"\n * action: approve\n * - tool: read\n * action: allow\n * - tool: write\n * paths: [\"src/**\"]\n * action: allow\n * - tool: write\n * action: approve\n * ```\n *\n * Rules are evaluated top-to-bottom; the first matching rule wins.\n *\n * On top of the rules sits a session-level `PermissionMode` (`default` /\n * `auto` / `yolo`, see the type doc) that relaxes how unmatched calls and\n * `approve` outcomes are handled — `deny` rules are never relaxed.\n *\n * `pattern` matching against bash commands is textual (no real shell\n * parser), so `deny` and `allow`/`approve` patterns are matched with\n * deliberately asymmetric strategies to stay fail-safe: `deny` scans every\n * chained/wrapped/unwrapped piece of the command it can find (paranoid,\n * over-matching is safe), while `allow`/`approve` require an exact\n * chain-shape match and reject anything containing `$(...)`, backticks, or\n * redirection (strict, under-matching just falls through to the default\n * decision instead of silently authorizing more than intended). See the\n * doc comment on `matchCommandPattern` below for details and known limits —\n * in particular, `pattern` can never guarantee real path containment; use\n * `paths` for that.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { minimatch } from \"minimatch\";\nimport { parse } from \"yaml\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../config.ts\";\n\n/** The three permission tiers a rule (or default) can resolve to. */\nexport type PermissionAction = \"deny\" | \"allow\" | \"approve\";\n\n/**\n * Session-level permission mode. Modes only relax the gate's *default*\n * decisions — explicit rules from `permissions.yml` always win first:\n *\n * - `default`: rules as authored; unmatched bash requires approval.\n * - `auto`: unmatched bash is auto-allowed unless it trips the built-in\n * danger filter (`DANGEROUS_COMMAND_PATTERNS`), in which case it still\n * requires approval. Explicit `deny`/`approve` rules behave as authored.\n * - `yolo`: every `approve` (rule-based or default) is downgraded to\n * `allow`. Explicit `deny` rules still block — yolo is \"stop asking\",\n * not \"disable the gate\".\n */\nexport type PermissionMode = \"default\" | \"auto\" | \"yolo\";\n\nexport const PERMISSION_MODES: readonly PermissionMode[] = [\"default\", \"auto\", \"yolo\"];\n\nexport function isPermissionMode(value: unknown): value is PermissionMode {\n\treturn typeof value === \"string\" && (PERMISSION_MODES as readonly string[]).includes(value);\n}\n\n/** A single permission rule as authored in `permissions.yml`. */\nexport interface PermissionRule {\n\t/** Tool identifier this rule applies to (e.g. \"bash\", \"read\", \"write\", \"edit\"), or \"*\" for any tool. */\n\ttool: string;\n\t/** Glob pattern matched against the bash command string (only meaningful for tools with a `command` arg). */\n\tpattern?: string;\n\t/** Glob patterns matched against the file path (only meaningful for tools with a `path`/`file_path` arg). */\n\tpaths?: string[];\n\t/** The action to take when this rule matches. */\n\taction: PermissionAction;\n}\n\n/** The result of evaluating a tool call against the permission rules. */\nexport interface PermissionDecision {\n\taction: PermissionAction;\n\treason: string;\n}\n\nconst VALID_ACTIONS: readonly PermissionAction[] = [\"deny\", \"allow\", \"approve\"];\nconst RULES_FILE_NAME = \"permissions.yml\";\nconst PATH_SCOPED_TOOLS = new Set([\"read\", \"write\", \"edit\"]);\n/** Read-only tools whose optional `path` arg defaults to the cwd when omitted. */\nconst READ_ONLY_PATH_TOOLS = new Set([\"grep\", \"find\", \"ls\"]);\n/**\n * Tools that are safe to run without confirmation because the call itself\n * touches nothing: `subagent` only delegates — the spawned child process runs\n * this same gate over every tool call it actually makes. Explicit rules can\n * still `deny`/`approve` these.\n */\nconst DEFAULT_ALLOWED_TOOLS = new Set([\"subagent\"]);\n\nfunction isPermissionAction(value: unknown): value is PermissionAction {\n\treturn typeof value === \"string\" && (VALID_ACTIONS as readonly string[]).includes(value);\n}\n\nfunction validateRule(raw: unknown, index: number): PermissionRule {\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} must be an object`);\n\t}\n\tconst record = raw as Record<string, unknown>;\n\n\tif (typeof record.tool !== \"string\" || record.tool.length === 0) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} is missing a valid \"tool\" field`);\n\t}\n\tif (!isPermissionAction(record.action)) {\n\t\tthrow new Error(\n\t\t\t`permissions.yml: rule at index ${index} has an invalid \"action\" (must be one of ${VALID_ACTIONS.join(\", \")})`,\n\t\t);\n\t}\n\n\tconst rule: PermissionRule = { tool: record.tool, action: record.action };\n\n\tif (record.pattern !== undefined) {\n\t\tif (typeof record.pattern !== \"string\") {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has a non-string \"pattern\"`);\n\t\t}\n\t\trule.pattern = record.pattern;\n\t}\n\n\tif (record.paths !== undefined) {\n\t\tif (!Array.isArray(record.paths) || !record.paths.every((entry) => typeof entry === \"string\")) {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has an invalid \"paths\" (must be a string array)`);\n\t\t}\n\t\trule.paths = record.paths as string[];\n\t}\n\n\treturn rule;\n}\n\n/**\n * Parse a `permissions.yml` document (as a string) into an ordered list of\n * rules. Returns an empty array for empty documents or documents without a\n * `rules` key. Throws on malformed rule entries so misconfiguration fails\n * loudly rather than silently degrading the gate.\n */\nexport function parseRules(yamlText: string): PermissionRule[] {\n\tconst parsed = parse(yamlText) as { rules?: unknown } | null | undefined;\n\tif (parsed === null || parsed === undefined) return [];\n\tif (parsed.rules === undefined) return [];\n\tif (!Array.isArray(parsed.rules)) {\n\t\tthrow new Error('permissions.yml: \"rules\" must be an array');\n\t}\n\treturn parsed.rules.map((raw, index) => validateRule(raw, index));\n}\n\nfunction readRulesFile(filePath: string): PermissionRule[] {\n\tif (!existsSync(filePath)) return [];\n\treturn parseRules(readFileSync(filePath, \"utf-8\"));\n}\n\n/**\n * Load and merge permission rules from the global (`~/.draht/agent/permissions.yml`)\n * and project (`<projectDir>/.draht/permissions.yml`) config files.\n *\n * Loading order: global is read first, project is read after (so a project\n * can be authored as a delta on top of the global defaults). Merge order is\n * reversed relative to load order: project rules are placed *before* global\n * rules in the returned array, so that under first-match-wins evaluation the\n * project's rules take precedence over — i.e. \"override\" — the global ones.\n */\nexport function loadRules(projectDir?: string, globalDir?: string): PermissionRule[] {\n\tconst globalRulesPath = join(globalDir ?? getAgentDir(), RULES_FILE_NAME);\n\tconst projectRulesPath = join(projectDir ?? process.cwd(), CONFIG_DIR_NAME, RULES_FILE_NAME);\n\n\tconst globalRules = readRulesFile(globalRulesPath);\n\tconst projectRules = readRulesFile(projectRulesPath);\n\n\treturn [...projectRules, ...globalRules];\n}\n\n/**\n * Bash `pattern` matching against the raw command string can never be more\n * than textual — it has no real shell parser behind it. A previous\n * implementation matched the whole command string against the pattern with\n * minimatch after stripping every \"/\" (to stop \"*\" from being blocked by\n * minimatch's path-segment semantics). That was trivially bypassed: any\n * prefix at all (a leading space, `sudo`, `/bin/`, `env`, chaining with `;`\n * or `&&`, wrapping in `bash -c \"...\"`, double spaces, reordered combined\n * flags like `-fr` vs `-rf`, or different case) defeated the anchored match,\n * and — separately — a trailing-wildcard *allow* rule like\n * `{ pattern: \"npm test*\", action: \"allow\" }` matched anything appended\n * after it via `;`, `&&`, `|`, backticks, or `$(...)`, silently\n * auto-approving injected commands.\n *\n * To stay fail-safe rather than fail-open, `deny` and `allow`/`approve` are\n * matched with deliberately different, asymmetric strategies:\n *\n * - `deny` is matched *paranoidly*. The command is decomposed into every\n * independently-executed piece we can find — split on chaining operators\n * (`;`, `&&`, `||`, `|`, `&`, newlines); unwrapped from passthrough\n * prefixes (`sudo`, `env`, `nice`, ...) and leading `VAR=val`\n * assignments; unwrapped from `bash -c \"...\"` / `sh -c '...'` / `eval\n * \"...\"`; unwrapped from `$(...)`/backtick substitutions; resolved from\n * an absolute/relative path to a bare command name — recursively, up to\n * a bounded depth/count. The pattern matches if *any* resulting\n * candidate matches, after collapsing whitespace and canonicalizing\n * combined short flags (so `-rf`/`-fr` compare equal), case-insensitively.\n * Over-matching here is the safe failure mode.\n * - `allow`/`approve` are matched *strictly*: the command is rejected\n * outright if it contains any dynamic/opaque construct (`$(...)`,\n * backticks, redirection `<`/`>`), and otherwise must have the exact same\n * chain shape (same number of segments joined by the same operators) as\n * the pattern, with each segment matched independently. A rule authored\n * for `npm test*` therefore can never also authorize\n * `npm test; rm -rf /` — the extra chained segment has no counterpart in\n * the pattern, so the rule simply doesn't match (falling through to the\n * default decision) instead of silently allowing it.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): interpreter\n * escape hatches. Once a command hands control to a language runtime, the\n * payload is no longer shell and no shell-shaped pattern — `deny` rules\n * included — can see into it: `python -c \"os.system('rm -rf /')\"` never\n * surfaces `rm -rf /` as a match candidate, `python script.py` hides the\n * danger in file contents the gate never reads, and\n * `python -c \"shutil.rmtree('/')\"` involves no shell command at all. The\n * built-in danger filter flags *inline eval* invocations (`python -c`,\n * `node -e`, ...) so auto mode prompts on them, but script files and\n * in-language equivalents are out of reach by construction. The gate is a\n * guard against a confused agent, not a confinement boundary for a\n * malicious one — a hard boundary needs OS-level sandboxing of the bash\n * tool itself (Seatbelt/Landlock-style), not better string matching.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): `pattern` cannot\n * enforce real directory containment. A rule like\n * `{ pattern: \"cat /safe/dir/*\", action: \"allow\" }` will still match\n * `cat /safe/dir/../../../etc/passwd`, because from a glob's point of view\n * `..` is just more characters absorbed by the trailing `*` — there is no\n * shell/path awareness in a plain string pattern. Use the `paths` mechanism\n * (which resolves real paths via `resolve`/`relative`, see `toMatchablePath`\n * below) instead of `pattern` whenever a rule needs to be scoped to a\n * directory; don't rely on `pattern` for path containment.\n */\n\n/** Command names that merely forward to another command without changing what ultimately runs. */\nconst PASSTHROUGH_PREFIXES = new Set([\n\t\"sudo\",\n\t\"doas\",\n\t\"command\",\n\t\"exec\",\n\t\"nice\",\n\t\"nohup\",\n\t\"env\",\n\t\"time\",\n\t\"stdbuf\",\n\t\"ionice\",\n\t\"chrt\",\n\t\"setsid\",\n\t\"xargs\",\n]);\n\n/** Shells whose `-c <command>` argument is itself a full command line to unwrap and re-check. */\nconst SHELL_C_WRAPPERS = new Set([\"bash\", \"sh\", \"zsh\", \"ksh\", \"dash\"]);\n\n/** Constructs that make a command dynamic/opaque enough that allow/approve patterns must never match it. */\nconst DANGEROUS_CONSTRUCT_RE = /\\$\\(|`|<|>/;\n\ninterface ChainSegment {\n\ttext: string;\n\t/** The operator immediately preceding this segment; `undefined` for the first segment. */\n\toperator?: string;\n}\n\n/** Quote-aware split of a command string on top-level chain operators (`;`, `&&`, `||`, `|`, `&`, newlines). */\nfunction splitChain(command: string): ChainSegment[] {\n\tconst segments: ChainSegment[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet operator: string | undefined;\n\tlet i = 0;\n\twhile (i < command.length) {\n\t\tconst ch = command[i];\n\t\tif (quote) {\n\t\t\tcurrent += ch;\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"' || ch === \"'\") {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && i + 1 < command.length) {\n\t\t\tcurrent += ch + command[i + 1];\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tconst two = command.slice(i, i + 2);\n\t\tif (two === \"&&\" || two === \"||\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = two;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = ch === \"\\n\" ? \";\" : ch;\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\tsegments.push({ text: current, operator });\n\treturn segments;\n}\n\nfunction collapseWhitespace(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/** Canonicalizes combined single-dash short-flag clusters (`-rf` / `-fr`) by sorting their letters. */\nfunction normalizeFlagClusters(text: string): string {\n\treturn text.replace(/(^|\\s)-([A-Za-z]{2,})(?=\\s|$)/g, (_match, pre: string, letters: string) => {\n\t\treturn `${pre}-${letters.split(\"\").sort().join(\"\")}`;\n\t});\n}\n\nfunction normalizeForMatch(text: string): string {\n\treturn normalizeFlagClusters(collapseWhitespace(text));\n}\n\n/** Resolves a leading `/some/path/cmd` (or `./cmd`, `../cmd`) first token down to its bare basename. */\nfunction resolveBasenameOfFirstToken(text: string): string {\n\tconst leadingWs = text.slice(0, text.length - text.trimStart().length);\n\tconst trimmed = text.trimStart();\n\tconst match = trimmed.match(/^(\\S+)([\\s\\S]*)$/);\n\tif (!match) return text;\n\tconst [, firstToken, rest] = match;\n\tif (!firstToken.includes(\"/\")) return text;\n\tconst basename = firstToken.slice(firstToken.lastIndexOf(\"/\") + 1);\n\treturn leadingWs + basename + rest;\n}\n\nfunction stripLeadingBackslashEscape(text: string): string {\n\treturn text.replace(/^(\\s*)\\\\(?=[A-Za-z])/, \"$1\");\n}\n\nfunction stripEnvAssignments(text: string): string {\n\treturn text.replace(/^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)+/, \"\");\n}\n\n/** Strips one leading passthrough-wrapper command (e.g. `sudo`, `env FOO=1`) and its own flags, if present. */\nfunction stripPassthroughPrefix(text: string): { stripped: string; changed: boolean } {\n\tconst trimmed = text.replace(/^\\s+/, \"\");\n\tconst match = trimmed.match(/^(\\S+)((?:\\s+-\\S+)*)\\s+/);\n\tif (!match) return { stripped: text, changed: false };\n\tconst token = match[1];\n\tconst basename = token.includes(\"/\") ? token.slice(token.lastIndexOf(\"/\") + 1) : token;\n\tif (!PASSTHROUGH_PREFIXES.has(basename.toLowerCase())) return { stripped: text, changed: false };\n\treturn { stripped: trimmed.slice(match[0].length), changed: true };\n}\n\n/** Extracts the inner command line from a `bash -c \"...\"` / `sh -c '...'` style wrapper, if present. */\nfunction extractShellDashC(text: string): string | undefined {\n\tconst trimmed = text.trim();\n\tconst match = trimmed.match(/^(\\S+)(?:\\s+-\\S+)*\\s+-c\\s+(['\"])([\\s\\S]*)\\2\\s*$/);\n\tif (!match) return undefined;\n\tconst token = match[1];\n\tconst basename = token.includes(\"/\") ? token.slice(token.lastIndexOf(\"/\") + 1) : token;\n\tif (!SHELL_C_WRAPPERS.has(basename.toLowerCase())) return undefined;\n\treturn match[3];\n}\n\n/** Extracts the inner command line from an `eval \"...\"` / `eval '...'` wrapper, if present. */\nfunction extractEvalArg(text: string): string | undefined {\n\tconst match = text.trim().match(/^eval\\s+(['\"])([\\s\\S]*)\\1\\s*$/i);\n\treturn match ? match[2] : undefined;\n}\n\n/** Extracts the contents of every `$(...)` and `` `...` `` command substitution found anywhere in `text`. */\nfunction extractSubstitutions(text: string): string[] {\n\tconst results: string[] = [];\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tif (text[i] === \"$\" && text[i + 1] === \"(\") {\n\t\t\tlet depth = 1;\n\t\t\tlet j = i + 2;\n\t\t\twhile (j < text.length && depth > 0) {\n\t\t\t\tif (text[j] === \"(\") depth++;\n\t\t\t\telse if (text[j] === \")\") depth--;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tresults.push(text.slice(i + 2, depth === 0 ? j - 1 : j));\n\t\t\ti = j;\n\t\t\tcontinue;\n\t\t}\n\t\ti++;\n\t}\n\tconst backtickMatches = text.match(/`([^`]*)`/g);\n\tif (backtickMatches) {\n\t\tfor (const m of backtickMatches) results.push(m.slice(1, -1));\n\t}\n\treturn results;\n}\n\n/**\n * Returns the literal output of a simple `echo ...` command. This covers a\n * substitution used as a command position, such as `$(echo rm -rf /)`, where\n * the output is subsequently executed by the outer shell.\n */\nfunction extractSimpleEchoOutput(text: string): string | undefined {\n\tconst match = text.match(/^\\s*echo\\s+([^$`]+?)\\s*$/i);\n\treturn match?.[1];\n}\n\nconst MAX_DENY_CANDIDATES = 50;\nconst MAX_DENY_DEPTH = 4;\n\n/**\n * Paranoidly enumerates every independently-executed \"piece\" of `command` a\n * `deny` rule should be checked against: the raw command, each chained\n * segment, prefix/wrapper-stripped variants of each segment, and the bodies\n * of any `bash -c` / `eval` / `$(...)` / backtick constructs — recursively,\n * bounded so adversarial input can't cause unbounded work.\n */\nfunction collectDenyCandidates(command: string): string[] {\n\tconst seen = new Set<string>();\n\tconst queue: Array<{ text: string; depth: number }> = [{ text: command, depth: 0 }];\n\n\twhile (queue.length > 0 && seen.size < MAX_DENY_CANDIDATES) {\n\t\tconst next = queue.shift();\n\t\tif (!next) break;\n\t\tconst { text, depth } = next;\n\t\tif (seen.has(text)) continue;\n\t\tseen.add(text);\n\t\tif (depth >= MAX_DENY_DEPTH) continue;\n\n\t\tconst enqueue = (candidate: string) => {\n\t\t\tif (!seen.has(candidate) && seen.size + queue.length < MAX_DENY_CANDIDATES) {\n\t\t\t\tqueue.push({ text: candidate, depth: depth + 1 });\n\t\t\t}\n\t\t};\n\n\t\tconst segments = splitChain(text).map((s) => s.text);\n\t\tconst pieces = segments.length > 1 ? segments : [text];\n\t\tfor (const seg of segments) enqueue(seg);\n\n\t\tfor (const piece of pieces) {\n\t\t\tlet working = stripLeadingBackslashEscape(piece);\n\t\t\tworking = stripEnvAssignments(working);\n\t\t\tfor (let guard = 0; guard < 5; guard++) {\n\t\t\t\tconst { stripped, changed } = stripPassthroughPrefix(working);\n\t\t\t\tif (!changed) break;\n\t\t\t\tworking = stripped;\n\t\t\t}\n\t\t\tenqueue(working);\n\n\t\t\tconst basenameResolved = resolveBasenameOfFirstToken(working);\n\t\t\tenqueue(basenameResolved);\n\n\t\t\tconst shellC = extractShellDashC(working) ?? extractShellDashC(basenameResolved);\n\t\t\tif (shellC !== undefined) enqueue(shellC);\n\n\t\t\tconst evalArg = extractEvalArg(working) ?? extractEvalArg(basenameResolved);\n\t\t\tif (evalArg !== undefined) enqueue(evalArg);\n\n\t\t\tfor (const sub of extractSubstitutions(piece)) {\n\t\t\t\tenqueue(sub);\n\t\t\t\tconst echoOutput = extractSimpleEchoOutput(sub);\n\t\t\t\tif (echoOutput !== undefined) enqueue(echoOutput);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [...seen];\n}\n\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = \"\";\n\tfor (const ch of pattern) {\n\t\tif (ch === \"*\") source += \".*\";\n\t\telse if (ch === \"?\") source += \".\";\n\t\telse source += ch.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\t}\n\treturn new RegExp(`^${source}$`, \"is\");\n}\n\nfunction matchDenyPattern(command: string, pattern: string): boolean {\n\tconst regex = globToRegExp(normalizeForMatch(pattern));\n\treturn collectDenyCandidates(command).some((candidate) => regex.test(normalizeForMatch(candidate)));\n}\n\n/**\n * Strictly matches `command` against an `allow`/`approve` `pattern`: any\n * dynamic/opaque construct disqualifies the match outright, and the command\n * must have the same chain shape (segment count and operators) as the\n * pattern, with every segment matching independently. This is what stops a\n * rule like `{ pattern: \"npm test*\", action: \"allow\" }` from also\n * authorizing `npm test; rm -rf /` or `` npm test `rm -rf /` ``.\n */\nfunction matchAllowPattern(command: string, pattern: string): boolean {\n\tif (DANGEROUS_CONSTRUCT_RE.test(command)) return false;\n\n\tconst commandSegments = splitChain(command);\n\tconst patternSegments = splitChain(pattern);\n\tif (commandSegments.length !== patternSegments.length) return false;\n\n\tfor (let i = 0; i < commandSegments.length; i++) {\n\t\tif (commandSegments[i].operator !== patternSegments[i].operator) return false;\n\t\tconst cmdText = normalizeForMatch(commandSegments[i].text);\n\t\tconst cmdResolved = normalizeForMatch(resolveBasenameOfFirstToken(commandSegments[i].text));\n\t\tconst regex = globToRegExp(normalizeForMatch(patternSegments[i].text));\n\t\tif (!regex.test(cmdText) && !regex.test(cmdResolved)) return false;\n\t}\n\treturn true;\n}\n\nfunction matchCommandPattern(command: string, pattern: string, action: PermissionAction): boolean {\n\treturn action === \"deny\" ? matchDenyPattern(command, pattern) : matchAllowPattern(command, pattern);\n}\n\n/**\n * Built-in danger filter backing `auto` mode. These are matched with the\n * same paranoid strategy as `deny` rules (chain splitting, wrapper\n * unwrapping, substitution extraction), so `echo hi && rm -rf /` or\n * `bash -c \"sudo dd ...\"` still trip the filter.\n *\n * This is a *prompt* heuristic, not a security boundary: it decides which\n * unmatched commands fall back to approval instead of auto-allow. It can\n * never enumerate every destructive command — anything that must be hard\n * blocked belongs in a `deny` rule in `permissions.yml`.\n */\nexport const DANGEROUS_COMMAND_PATTERNS: readonly string[] = [\n\t// recursive/forced deletion (flag clusters normalize to sorted letters,\n\t// so `-rf`/`-fr` become `-fr` and are caught by the `-f*` prefix; bare\n\t// `-r`/`-R` by the `-r*` prefix via case-insensitive matching)\n\t\"rm -r*\",\n\t\"rm -f*\",\n\t// privilege escalation\n\t\"sudo *\",\n\t\"doas *\",\n\t\"su *\",\n\t// raw disk / filesystem surgery\n\t\"dd *\",\n\t\"mkfs*\",\n\t// system state\n\t\"shutdown*\",\n\t\"reboot*\",\n\t\"halt*\",\n\t\"poweroff*\",\n\t// blanket permission changes\n\t\"chmod 777 *\",\n\t\"chmod -R *\",\n\t\"chown -R *\",\n\t// outward-facing / history-rewriting git and publishing\n\t\"git push*\",\n\t\"git reset --hard*\",\n\t\"git clean*\",\n\t\"npm publish*\",\n\t\"yarn publish*\",\n\t\"pnpm publish*\",\n\t// pipe-to-shell installers\n\t\"curl * | *\",\n\t\"wget * | *\",\n\t// inline interpreter eval — the code payload is another language the gate\n\t// cannot parse, so `python -c \"os.system('rm -rf /')\"` would otherwise\n\t// sail through as \"not shell-dangerous\". Running a script *file*\n\t// (`python script.py`) is deliberately NOT flagged: it is everyday dev\n\t// work, and the gate cannot see file contents anyway (see the module doc\n\t// on interpreter escape hatches).\n\t\"python* -c*\",\n\t\"node -e*\",\n\t\"node --eval*\",\n\t\"node -p*\",\n\t\"bun -e*\",\n\t\"bun --eval*\",\n\t\"deno eval*\",\n\t\"ruby -e*\",\n\t\"perl -e*\",\n\t\"php -r*\",\n];\n\n/**\n * Returns the first built-in dangerous pattern the command matches, or\n * `undefined` if the command passes the filter.\n */\nexport function findDangerousPattern(command: string): string | undefined {\n\treturn DANGEROUS_COMMAND_PATTERNS.find((pattern) => matchDenyPattern(command, pattern));\n}\n\n/** Normalize a (possibly relative or absolute) path into a forward-slash path relative to `cwd`, for glob matching. */\nfunction toMatchablePath(filePath: string, cwd: string): string {\n\tconst resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);\n\tconst rel = relative(cwd, resolved);\n\treturn rel.split(sep).join(\"/\");\n}\n\n/** Whether `filePath` (relative or absolute) resolves to a location inside `cwd`. */\nfunction isWithinProject(filePath: string, cwd: string): boolean {\n\tconst resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);\n\tconst rel = relative(cwd, resolved);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\n/**\n * NOTE: this assumes the tool-call args carry a `command` string under the\n * exact key `command`. If/when this gate is wired into actual tool\n * dispatch, verify every gated tool's argument shape matches these\n * hardcoded key names — a mismatch doesn't error, it just silently fails to\n * match any `pattern`/`paths` rule and falls through to the (fail-safe)\n * default decision. Not currently exploitable: nothing outside this module\n * and its test calls `PermissionGate`/`loadRules` yet.\n */\nfunction getCommandArg(args: Record<string, unknown>): string | undefined {\n\treturn typeof args.command === \"string\" ? args.command : undefined;\n}\n\n/** Prefers `file_path` over `path` when both are present; see the note on `getCommandArg` above. */\nfunction getPathArg(args: Record<string, unknown>): string | undefined {\n\tif (typeof args.file_path === \"string\") return args.file_path;\n\tif (typeof args.path === \"string\") return args.path;\n\treturn undefined;\n}\n\nfunction describeMatch(rule: PermissionRule): string {\n\tconst parts = [`tool=${rule.tool}`];\n\tif (rule.pattern !== undefined) parts.push(`pattern=${JSON.stringify(rule.pattern)}`);\n\tif (rule.paths !== undefined) parts.push(`paths=${JSON.stringify(rule.paths)}`);\n\treturn `matched rule (${parts.join(\", \")}) -> ${rule.action}`;\n}\n\nfunction ruleMatches(rule: PermissionRule, toolName: string, args: Record<string, unknown>, cwd: string): boolean {\n\tif (rule.tool !== \"*\" && rule.tool.toLowerCase() !== toolName) return false;\n\n\tif (rule.pattern !== undefined) {\n\t\tconst command = getCommandArg(args);\n\t\tif (command === undefined || !matchCommandPattern(command, rule.pattern, rule.action)) return false;\n\t}\n\n\tif (rule.paths !== undefined) {\n\t\tconst filePath = getPathArg(args);\n\t\tif (filePath === undefined) return false;\n\t\tconst matchable = toMatchablePath(filePath, cwd);\n\t\tif (!rule.paths.some((pattern) => minimatch(matchable, pattern, { dot: true }))) return false;\n\t}\n\n\treturn true;\n}\n\nexport interface PermissionGateOptions {\n\t/** Project root used to determine whether a path is \"within the project\" for default decisions. Defaults to `process.cwd()`. */\n\tcwd?: string;\n\t/** Session permission mode; see `PermissionMode`. Defaults to `\"default\"`. */\n\tmode?: PermissionMode;\n}\n\n/**\n * Evaluates tool calls against an ordered list of permission rules,\n * returning a `deny` / `allow` / `approve` decision.\n */\nexport class PermissionGate {\n\tprivate readonly rules: PermissionRule[];\n\tprivate readonly cwd: string;\n\tprivate readonly mode: PermissionMode;\n\n\tconstructor(rules: PermissionRule[] = [], options: PermissionGateOptions = {}) {\n\t\tthis.rules = rules;\n\t\tthis.cwd = options.cwd ?? process.cwd();\n\t\tthis.mode = options.mode ?? \"default\";\n\t}\n\n\t/** Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit. */\n\tevaluate(toolName: string, args: Record<string, unknown> = {}): PermissionDecision {\n\t\tconst normalizedTool = toolName.toLowerCase();\n\n\t\tfor (const rule of this.rules) {\n\t\t\tif (ruleMatches(rule, normalizedTool, args, this.cwd)) {\n\t\t\t\treturn this.applyMode({ action: rule.action, reason: describeMatch(rule) });\n\t\t\t}\n\t\t}\n\n\t\treturn this.applyMode(this.defaultDecision(normalizedTool, args));\n\t}\n\n\t/**\n\t * Applies the session mode to a decision. `deny` is never relaxed by any\n\t * mode; `yolo` downgrades every `approve` to `allow`.\n\t */\n\tprivate applyMode(decision: PermissionDecision): PermissionDecision {\n\t\tif (this.mode === \"yolo\" && decision.action === \"approve\") {\n\t\t\treturn { action: \"allow\", reason: `yolo mode: auto-allowed (${decision.reason})` };\n\t\t}\n\t\treturn decision;\n\t}\n\n\tprivate defaultDecision(toolName: string, args: Record<string, unknown>): PermissionDecision {\n\t\tif (DEFAULT_ALLOWED_TOOLS.has(toolName)) {\n\t\t\treturn { action: \"allow\", reason: `no rule matched; \"${toolName}\" is allowed by default` };\n\t\t}\n\n\t\tif (toolName === \"bash\") {\n\t\t\tif (this.mode === \"auto\") {\n\t\t\t\tconst command = getCommandArg(args);\n\t\t\t\tif (command === undefined) {\n\t\t\t\t\treturn { action: \"approve\", reason: \"auto mode: bash call without a command string requires approval\" };\n\t\t\t\t}\n\t\t\t\tconst dangerous = findDangerousPattern(command);\n\t\t\t\tif (dangerous !== undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason: `auto mode: command matched dangerous pattern ${JSON.stringify(dangerous)}, requires approval`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { action: \"allow\", reason: \"auto mode: no rule matched and command passed the danger filter\" };\n\t\t\t}\n\t\t\treturn { action: \"approve\", reason: \"no rule matched; bash commands require approval by default\" };\n\t\t}\n\n\t\tif (PATH_SCOPED_TOOLS.has(toolName)) {\n\t\t\tconst filePath = getPathArg(args);\n\t\t\tif (filePath !== undefined && isWithinProject(filePath, this.cwd)) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project (or missing), requires approval\",\n\t\t\t};\n\t\t}\n\n\t\tif (READ_ONLY_PATH_TOOLS.has(toolName)) {\n\t\t\t// Unlike read/write/edit, these tools treat a missing `path` as the\n\t\t\t// cwd, so an absent path arg is within the project by definition.\n\t\t\tconst filePath = getPathArg(args) ?? \".\";\n\t\t\tif (isWithinProject(filePath, this.cwd)) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; read-only tool allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project, requires approval\",\n\t\t\t};\n\t\t}\n\n\t\treturn { action: \"approve\", reason: `no rule matched for tool \"${toolName}\"; defaults to approve` };\n\t}\n}\n"]}
1
+ {"version":3,"file":"permission-gate.js","sourceRoot":"","sources":["../../../src/core/multi-agent/permission-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAmB/D,MAAM,CAAC,MAAM,gBAAgB,GAA8B,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAEvF,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC9C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAK,gBAAsC,CAAC,QAAQ,CAAC,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,EAAE,MAAM,EAAE,iEAAiE,EAAE,CAAC;YACvG,CAAC;YACD,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,4DAA4D,EAAE,CAAC;QACpG,CAAC;QAED,IAAI,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACrC,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;YAClC,IAAI,QAAQ,KAAK,SAAS,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gBACnE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,wDAAwD,EAAE,CAAC;YAC9F,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,SAAS;gBACjB,MAAM,EAAE,8EAA8E;aACtF,CAAC;QACH,CAAC;QAED,IAAI,oBAAoB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxC,oEAAoE;YACpE,kEAAkE;YAClE,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC;YACzC,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gBACzC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,uEAAuE,EAAE,CAAC;YAC7G,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,SAAS;gBACjB,MAAM,EAAE,iEAAiE;aACzE,CAAC;QACH,CAAC;QAED,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,6BAA6B,QAAQ,wBAAwB,EAAE,CAAC;IACrG,CAAC;CACD","sourcesContent":["/**\n * Permission gate: a three-tier permission system that decides whether a\n * tool call may proceed automatically, must be blocked, or must be confirmed\n * by the user before it runs.\n *\n * SECURITY-CRITICAL: this module gates real bash/write tool calls. Prefer\n * fail-safe (approve/deny) over fail-open (allow) whenever a decision is\n * ambiguous.\n *\n * Configuration is read from `.draht/permissions.yml` (project) and\n * `~/.draht/agent/permissions.yml` (global), e.g.:\n *\n * ```yaml\n * rules:\n * - tool: bash\n * pattern: \"rm -rf *\"\n * action: deny\n * - tool: bash\n * pattern: \"git push *\"\n * action: approve\n * - tool: read\n * action: allow\n * - tool: write\n * paths: [\"src/**\"]\n * action: allow\n * - tool: write\n * action: approve\n * ```\n *\n * Rules are evaluated top-to-bottom; the first matching rule wins.\n *\n * On top of the rules sits a session-level `PermissionMode` (`default` /\n * `auto` / `yolo`, see the type doc) that relaxes how unmatched calls and\n * `approve` outcomes are handled — `deny` rules are never relaxed.\n *\n * `pattern` matching against bash commands is textual (no real shell\n * parser), so `deny` and `allow`/`approve` patterns are matched with\n * deliberately asymmetric strategies to stay fail-safe: `deny` scans every\n * chained/wrapped/unwrapped piece of the command it can find (paranoid,\n * over-matching is safe), while `allow`/`approve` require an exact\n * chain-shape match and reject anything containing `$(...)`, backticks, or\n * redirection (strict, under-matching just falls through to the default\n * decision instead of silently authorizing more than intended). See the\n * doc comment on `matchCommandPattern` below for details and known limits —\n * in particular, `pattern` can never guarantee real path containment; use\n * `paths` for that.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { minimatch } from \"minimatch\";\nimport { parse } from \"yaml\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../../config.ts\";\n\n/** The three permission tiers a rule (or default) can resolve to. */\nexport type PermissionAction = \"deny\" | \"allow\" | \"approve\";\n\n/**\n * Session-level permission mode. Modes only relax the gate's *default*\n * decisions — explicit rules from `permissions.yml` always win first:\n *\n * - `default`: rules as authored; unmatched bash requires approval.\n * - `auto`: unmatched bash is auto-allowed unless it trips the built-in\n * danger filter (`DANGEROUS_COMMAND_PATTERNS`), in which case it still\n * requires approval. Explicit `deny`/`approve` rules behave as authored.\n * - `yolo`: every `approve` (rule-based or default) is downgraded to\n * `allow`. Explicit `deny` rules still block — yolo is \"stop asking\",\n * not \"disable the gate\".\n */\nexport type PermissionMode = \"default\" | \"auto\" | \"yolo\";\n\nexport const PERMISSION_MODES: readonly PermissionMode[] = [\"default\", \"auto\", \"yolo\"];\n\nexport function isPermissionMode(value: unknown): value is PermissionMode {\n\treturn typeof value === \"string\" && (PERMISSION_MODES as readonly string[]).includes(value);\n}\n\n/** A single permission rule as authored in `permissions.yml`. */\nexport interface PermissionRule {\n\t/** Tool identifier this rule applies to (e.g. \"bash\", \"read\", \"write\", \"edit\"), or \"*\" for any tool. */\n\ttool: string;\n\t/** Glob pattern matched against the bash command string (only meaningful for tools with a `command` arg). */\n\tpattern?: string;\n\t/** Glob patterns matched against the file path (only meaningful for tools with a `path`/`file_path` arg). */\n\tpaths?: string[];\n\t/** The action to take when this rule matches. */\n\taction: PermissionAction;\n}\n\n/** The result of evaluating a tool call against the permission rules. */\nexport interface PermissionDecision {\n\taction: PermissionAction;\n\treason: string;\n}\n\nconst VALID_ACTIONS: readonly PermissionAction[] = [\"deny\", \"allow\", \"approve\"];\nconst RULES_FILE_NAME = \"permissions.yml\";\nconst PATH_SCOPED_TOOLS = new Set([\"read\", \"write\", \"edit\"]);\n/** Read-only tools whose optional `path` arg defaults to the cwd when omitted. */\nconst READ_ONLY_PATH_TOOLS = new Set([\"grep\", \"find\", \"ls\"]);\n/**\n * Tools that are safe to run without confirmation because the call itself\n * only delegates: spawned child processes run this same gate over every tool\n * call they actually make. Explicit rules can still `deny`/`approve` these.\n * Duet delegation is deliberately not included because it fans out paid model\n * requests; unmatched duet batches require explicit approval.\n */\nconst DEFAULT_ALLOWED_TOOLS = new Set([\"subagent\"]);\n\nfunction isPermissionAction(value: unknown): value is PermissionAction {\n\treturn typeof value === \"string\" && (VALID_ACTIONS as readonly string[]).includes(value);\n}\n\nfunction validateRule(raw: unknown, index: number): PermissionRule {\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} must be an object`);\n\t}\n\tconst record = raw as Record<string, unknown>;\n\n\tif (typeof record.tool !== \"string\" || record.tool.length === 0) {\n\t\tthrow new Error(`permissions.yml: rule at index ${index} is missing a valid \"tool\" field`);\n\t}\n\tif (!isPermissionAction(record.action)) {\n\t\tthrow new Error(\n\t\t\t`permissions.yml: rule at index ${index} has an invalid \"action\" (must be one of ${VALID_ACTIONS.join(\", \")})`,\n\t\t);\n\t}\n\n\tconst rule: PermissionRule = { tool: record.tool, action: record.action };\n\n\tif (record.pattern !== undefined) {\n\t\tif (typeof record.pattern !== \"string\") {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has a non-string \"pattern\"`);\n\t\t}\n\t\trule.pattern = record.pattern;\n\t}\n\n\tif (record.paths !== undefined) {\n\t\tif (!Array.isArray(record.paths) || !record.paths.every((entry) => typeof entry === \"string\")) {\n\t\t\tthrow new Error(`permissions.yml: rule at index ${index} has an invalid \"paths\" (must be a string array)`);\n\t\t}\n\t\trule.paths = record.paths as string[];\n\t}\n\n\treturn rule;\n}\n\n/**\n * Parse a `permissions.yml` document (as a string) into an ordered list of\n * rules. Returns an empty array for empty documents or documents without a\n * `rules` key. Throws on malformed rule entries so misconfiguration fails\n * loudly rather than silently degrading the gate.\n */\nexport function parseRules(yamlText: string): PermissionRule[] {\n\tconst parsed = parse(yamlText) as { rules?: unknown } | null | undefined;\n\tif (parsed === null || parsed === undefined) return [];\n\tif (parsed.rules === undefined) return [];\n\tif (!Array.isArray(parsed.rules)) {\n\t\tthrow new Error('permissions.yml: \"rules\" must be an array');\n\t}\n\treturn parsed.rules.map((raw, index) => validateRule(raw, index));\n}\n\nfunction readRulesFile(filePath: string): PermissionRule[] {\n\tif (!existsSync(filePath)) return [];\n\treturn parseRules(readFileSync(filePath, \"utf-8\"));\n}\n\n/**\n * Load and merge permission rules from the global (`~/.draht/agent/permissions.yml`)\n * and project (`<projectDir>/.draht/permissions.yml`) config files.\n *\n * Loading order: global is read first, project is read after (so a project\n * can be authored as a delta on top of the global defaults). Merge order is\n * reversed relative to load order: project rules are placed *before* global\n * rules in the returned array, so that under first-match-wins evaluation the\n * project's rules take precedence over — i.e. \"override\" — the global ones.\n */\nexport function loadRules(projectDir?: string, globalDir?: string): PermissionRule[] {\n\tconst globalRulesPath = join(globalDir ?? getAgentDir(), RULES_FILE_NAME);\n\tconst projectRulesPath = join(projectDir ?? process.cwd(), CONFIG_DIR_NAME, RULES_FILE_NAME);\n\n\tconst globalRules = readRulesFile(globalRulesPath);\n\tconst projectRules = readRulesFile(projectRulesPath);\n\n\treturn [...projectRules, ...globalRules];\n}\n\n/**\n * Bash `pattern` matching against the raw command string can never be more\n * than textual — it has no real shell parser behind it. A previous\n * implementation matched the whole command string against the pattern with\n * minimatch after stripping every \"/\" (to stop \"*\" from being blocked by\n * minimatch's path-segment semantics). That was trivially bypassed: any\n * prefix at all (a leading space, `sudo`, `/bin/`, `env`, chaining with `;`\n * or `&&`, wrapping in `bash -c \"...\"`, double spaces, reordered combined\n * flags like `-fr` vs `-rf`, or different case) defeated the anchored match,\n * and — separately — a trailing-wildcard *allow* rule like\n * `{ pattern: \"npm test*\", action: \"allow\" }` matched anything appended\n * after it via `;`, `&&`, `|`, backticks, or `$(...)`, silently\n * auto-approving injected commands.\n *\n * To stay fail-safe rather than fail-open, `deny` and `allow`/`approve` are\n * matched with deliberately different, asymmetric strategies:\n *\n * - `deny` is matched *paranoidly*. The command is decomposed into every\n * independently-executed piece we can find — split on chaining operators\n * (`;`, `&&`, `||`, `|`, `&`, newlines); unwrapped from passthrough\n * prefixes (`sudo`, `env`, `nice`, ...) and leading `VAR=val`\n * assignments; unwrapped from `bash -c \"...\"` / `sh -c '...'` / `eval\n * \"...\"`; unwrapped from `$(...)`/backtick substitutions; resolved from\n * an absolute/relative path to a bare command name — recursively, up to\n * a bounded depth/count. The pattern matches if *any* resulting\n * candidate matches, after collapsing whitespace and canonicalizing\n * combined short flags (so `-rf`/`-fr` compare equal), case-insensitively.\n * Over-matching here is the safe failure mode.\n * - `allow`/`approve` are matched *strictly*: the command is rejected\n * outright if it contains any dynamic/opaque construct (`$(...)`,\n * backticks, redirection `<`/`>`), and otherwise must have the exact same\n * chain shape (same number of segments joined by the same operators) as\n * the pattern, with each segment matched independently. A rule authored\n * for `npm test*` therefore can never also authorize\n * `npm test; rm -rf /` — the extra chained segment has no counterpart in\n * the pattern, so the rule simply doesn't match (falling through to the\n * default decision) instead of silently allowing it.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): interpreter\n * escape hatches. Once a command hands control to a language runtime, the\n * payload is no longer shell and no shell-shaped pattern — `deny` rules\n * included — can see into it: `python -c \"os.system('rm -rf /')\"` never\n * surfaces `rm -rf /` as a match candidate, `python script.py` hides the\n * danger in file contents the gate never reads, and\n * `python -c \"shutil.rmtree('/')\"` involves no shell command at all. The\n * built-in danger filter flags *inline eval* invocations (`python -c`,\n * `node -e`, ...) so auto mode prompts on them, but script files and\n * in-language equivalents are out of reach by construction. The gate is a\n * guard against a confused agent, not a confinement boundary for a\n * malicious one — a hard boundary needs OS-level sandboxing of the bash\n * tool itself (Seatbelt/Landlock-style), not better string matching.\n *\n * KNOWN LIMITATION (not fixable with text matching alone): `pattern` cannot\n * enforce real directory containment. A rule like\n * `{ pattern: \"cat /safe/dir/*\", action: \"allow\" }` will still match\n * `cat /safe/dir/../../../etc/passwd`, because from a glob's point of view\n * `..` is just more characters absorbed by the trailing `*` — there is no\n * shell/path awareness in a plain string pattern. Use the `paths` mechanism\n * (which resolves real paths via `resolve`/`relative`, see `toMatchablePath`\n * below) instead of `pattern` whenever a rule needs to be scoped to a\n * directory; don't rely on `pattern` for path containment.\n */\n\n/** Command names that merely forward to another command without changing what ultimately runs. */\nconst PASSTHROUGH_PREFIXES = new Set([\n\t\"sudo\",\n\t\"doas\",\n\t\"command\",\n\t\"exec\",\n\t\"nice\",\n\t\"nohup\",\n\t\"env\",\n\t\"time\",\n\t\"stdbuf\",\n\t\"ionice\",\n\t\"chrt\",\n\t\"setsid\",\n\t\"xargs\",\n]);\n\n/** Shells whose `-c <command>` argument is itself a full command line to unwrap and re-check. */\nconst SHELL_C_WRAPPERS = new Set([\"bash\", \"sh\", \"zsh\", \"ksh\", \"dash\"]);\n\n/** Constructs that make a command dynamic/opaque enough that allow/approve patterns must never match it. */\nconst DANGEROUS_CONSTRUCT_RE = /\\$\\(|`|<|>/;\n\ninterface ChainSegment {\n\ttext: string;\n\t/** The operator immediately preceding this segment; `undefined` for the first segment. */\n\toperator?: string;\n}\n\n/** Quote-aware split of a command string on top-level chain operators (`;`, `&&`, `||`, `|`, `&`, newlines). */\nfunction splitChain(command: string): ChainSegment[] {\n\tconst segments: ChainSegment[] = [];\n\tlet current = \"\";\n\tlet quote: '\"' | \"'\" | undefined;\n\tlet operator: string | undefined;\n\tlet i = 0;\n\twhile (i < command.length) {\n\t\tconst ch = command[i];\n\t\tif (quote) {\n\t\t\tcurrent += ch;\n\t\t\tif (ch === quote) quote = undefined;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === '\"' || ch === \"'\") {\n\t\t\tquote = ch;\n\t\t\tcurrent += ch;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"\\\\\" && i + 1 < command.length) {\n\t\t\tcurrent += ch + command[i + 1];\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tconst two = command.slice(i, i + 2);\n\t\tif (two === \"&&\" || two === \"||\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = two;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \";\" || ch === \"|\" || ch === \"&\" || ch === \"\\n\") {\n\t\t\tsegments.push({ text: current, operator });\n\t\t\tcurrent = \"\";\n\t\t\toperator = ch === \"\\n\" ? \";\" : ch;\n\t\t\ti += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += ch;\n\t\ti++;\n\t}\n\tsegments.push({ text: current, operator });\n\treturn segments;\n}\n\nfunction collapseWhitespace(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/** Canonicalizes combined single-dash short-flag clusters (`-rf` / `-fr`) by sorting their letters. */\nfunction normalizeFlagClusters(text: string): string {\n\treturn text.replace(/(^|\\s)-([A-Za-z]{2,})(?=\\s|$)/g, (_match, pre: string, letters: string) => {\n\t\treturn `${pre}-${letters.split(\"\").sort().join(\"\")}`;\n\t});\n}\n\nfunction normalizeForMatch(text: string): string {\n\treturn normalizeFlagClusters(collapseWhitespace(text));\n}\n\n/** Resolves a leading `/some/path/cmd` (or `./cmd`, `../cmd`) first token down to its bare basename. */\nfunction resolveBasenameOfFirstToken(text: string): string {\n\tconst leadingWs = text.slice(0, text.length - text.trimStart().length);\n\tconst trimmed = text.trimStart();\n\tconst match = trimmed.match(/^(\\S+)([\\s\\S]*)$/);\n\tif (!match) return text;\n\tconst [, firstToken, rest] = match;\n\tif (!firstToken.includes(\"/\")) return text;\n\tconst basename = firstToken.slice(firstToken.lastIndexOf(\"/\") + 1);\n\treturn leadingWs + basename + rest;\n}\n\nfunction stripLeadingBackslashEscape(text: string): string {\n\treturn text.replace(/^(\\s*)\\\\(?=[A-Za-z])/, \"$1\");\n}\n\nfunction stripEnvAssignments(text: string): string {\n\treturn text.replace(/^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)+/, \"\");\n}\n\n/** Strips one leading passthrough-wrapper command (e.g. `sudo`, `env FOO=1`) and its own flags, if present. */\nfunction stripPassthroughPrefix(text: string): { stripped: string; changed: boolean } {\n\tconst trimmed = text.replace(/^\\s+/, \"\");\n\tconst match = trimmed.match(/^(\\S+)((?:\\s+-\\S+)*)\\s+/);\n\tif (!match) return { stripped: text, changed: false };\n\tconst token = match[1];\n\tconst basename = token.includes(\"/\") ? token.slice(token.lastIndexOf(\"/\") + 1) : token;\n\tif (!PASSTHROUGH_PREFIXES.has(basename.toLowerCase())) return { stripped: text, changed: false };\n\treturn { stripped: trimmed.slice(match[0].length), changed: true };\n}\n\n/** Extracts the inner command line from a `bash -c \"...\"` / `sh -c '...'` style wrapper, if present. */\nfunction extractShellDashC(text: string): string | undefined {\n\tconst trimmed = text.trim();\n\tconst match = trimmed.match(/^(\\S+)(?:\\s+-\\S+)*\\s+-c\\s+(['\"])([\\s\\S]*)\\2\\s*$/);\n\tif (!match) return undefined;\n\tconst token = match[1];\n\tconst basename = token.includes(\"/\") ? token.slice(token.lastIndexOf(\"/\") + 1) : token;\n\tif (!SHELL_C_WRAPPERS.has(basename.toLowerCase())) return undefined;\n\treturn match[3];\n}\n\n/** Extracts the inner command line from an `eval \"...\"` / `eval '...'` wrapper, if present. */\nfunction extractEvalArg(text: string): string | undefined {\n\tconst match = text.trim().match(/^eval\\s+(['\"])([\\s\\S]*)\\1\\s*$/i);\n\treturn match ? match[2] : undefined;\n}\n\n/** Extracts the contents of every `$(...)` and `` `...` `` command substitution found anywhere in `text`. */\nfunction extractSubstitutions(text: string): string[] {\n\tconst results: string[] = [];\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tif (text[i] === \"$\" && text[i + 1] === \"(\") {\n\t\t\tlet depth = 1;\n\t\t\tlet j = i + 2;\n\t\t\twhile (j < text.length && depth > 0) {\n\t\t\t\tif (text[j] === \"(\") depth++;\n\t\t\t\telse if (text[j] === \")\") depth--;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tresults.push(text.slice(i + 2, depth === 0 ? j - 1 : j));\n\t\t\ti = j;\n\t\t\tcontinue;\n\t\t}\n\t\ti++;\n\t}\n\tconst backtickMatches = text.match(/`([^`]*)`/g);\n\tif (backtickMatches) {\n\t\tfor (const m of backtickMatches) results.push(m.slice(1, -1));\n\t}\n\treturn results;\n}\n\n/**\n * Returns the literal output of a simple `echo ...` command. This covers a\n * substitution used as a command position, such as `$(echo rm -rf /)`, where\n * the output is subsequently executed by the outer shell.\n */\nfunction extractSimpleEchoOutput(text: string): string | undefined {\n\tconst match = text.match(/^\\s*echo\\s+([^$`]+?)\\s*$/i);\n\treturn match?.[1];\n}\n\nconst MAX_DENY_CANDIDATES = 50;\nconst MAX_DENY_DEPTH = 4;\n\n/**\n * Paranoidly enumerates every independently-executed \"piece\" of `command` a\n * `deny` rule should be checked against: the raw command, each chained\n * segment, prefix/wrapper-stripped variants of each segment, and the bodies\n * of any `bash -c` / `eval` / `$(...)` / backtick constructs — recursively,\n * bounded so adversarial input can't cause unbounded work.\n */\nfunction collectDenyCandidates(command: string): string[] {\n\tconst seen = new Set<string>();\n\tconst queue: Array<{ text: string; depth: number }> = [{ text: command, depth: 0 }];\n\n\twhile (queue.length > 0 && seen.size < MAX_DENY_CANDIDATES) {\n\t\tconst next = queue.shift();\n\t\tif (!next) break;\n\t\tconst { text, depth } = next;\n\t\tif (seen.has(text)) continue;\n\t\tseen.add(text);\n\t\tif (depth >= MAX_DENY_DEPTH) continue;\n\n\t\tconst enqueue = (candidate: string) => {\n\t\t\tif (!seen.has(candidate) && seen.size + queue.length < MAX_DENY_CANDIDATES) {\n\t\t\t\tqueue.push({ text: candidate, depth: depth + 1 });\n\t\t\t}\n\t\t};\n\n\t\tconst segments = splitChain(text).map((s) => s.text);\n\t\tconst pieces = segments.length > 1 ? segments : [text];\n\t\tfor (const seg of segments) enqueue(seg);\n\n\t\tfor (const piece of pieces) {\n\t\t\tlet working = stripLeadingBackslashEscape(piece);\n\t\t\tworking = stripEnvAssignments(working);\n\t\t\tfor (let guard = 0; guard < 5; guard++) {\n\t\t\t\tconst { stripped, changed } = stripPassthroughPrefix(working);\n\t\t\t\tif (!changed) break;\n\t\t\t\tworking = stripped;\n\t\t\t}\n\t\t\tenqueue(working);\n\n\t\t\tconst basenameResolved = resolveBasenameOfFirstToken(working);\n\t\t\tenqueue(basenameResolved);\n\n\t\t\tconst shellC = extractShellDashC(working) ?? extractShellDashC(basenameResolved);\n\t\t\tif (shellC !== undefined) enqueue(shellC);\n\n\t\t\tconst evalArg = extractEvalArg(working) ?? extractEvalArg(basenameResolved);\n\t\t\tif (evalArg !== undefined) enqueue(evalArg);\n\n\t\t\tfor (const sub of extractSubstitutions(piece)) {\n\t\t\t\tenqueue(sub);\n\t\t\t\tconst echoOutput = extractSimpleEchoOutput(sub);\n\t\t\t\tif (echoOutput !== undefined) enqueue(echoOutput);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [...seen];\n}\n\nfunction globToRegExp(pattern: string): RegExp {\n\tlet source = \"\";\n\tfor (const ch of pattern) {\n\t\tif (ch === \"*\") source += \".*\";\n\t\telse if (ch === \"?\") source += \".\";\n\t\telse source += ch.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\t}\n\treturn new RegExp(`^${source}$`, \"is\");\n}\n\nfunction matchDenyPattern(command: string, pattern: string): boolean {\n\tconst regex = globToRegExp(normalizeForMatch(pattern));\n\treturn collectDenyCandidates(command).some((candidate) => regex.test(normalizeForMatch(candidate)));\n}\n\n/**\n * Strictly matches `command` against an `allow`/`approve` `pattern`: any\n * dynamic/opaque construct disqualifies the match outright, and the command\n * must have the same chain shape (segment count and operators) as the\n * pattern, with every segment matching independently. This is what stops a\n * rule like `{ pattern: \"npm test*\", action: \"allow\" }` from also\n * authorizing `npm test; rm -rf /` or `` npm test `rm -rf /` ``.\n */\nfunction matchAllowPattern(command: string, pattern: string): boolean {\n\tif (DANGEROUS_CONSTRUCT_RE.test(command)) return false;\n\n\tconst commandSegments = splitChain(command);\n\tconst patternSegments = splitChain(pattern);\n\tif (commandSegments.length !== patternSegments.length) return false;\n\n\tfor (let i = 0; i < commandSegments.length; i++) {\n\t\tif (commandSegments[i].operator !== patternSegments[i].operator) return false;\n\t\tconst cmdText = normalizeForMatch(commandSegments[i].text);\n\t\tconst cmdResolved = normalizeForMatch(resolveBasenameOfFirstToken(commandSegments[i].text));\n\t\tconst regex = globToRegExp(normalizeForMatch(patternSegments[i].text));\n\t\tif (!regex.test(cmdText) && !regex.test(cmdResolved)) return false;\n\t}\n\treturn true;\n}\n\nfunction matchCommandPattern(command: string, pattern: string, action: PermissionAction): boolean {\n\treturn action === \"deny\" ? matchDenyPattern(command, pattern) : matchAllowPattern(command, pattern);\n}\n\n/**\n * Built-in danger filter backing `auto` mode. These are matched with the\n * same paranoid strategy as `deny` rules (chain splitting, wrapper\n * unwrapping, substitution extraction), so `echo hi && rm -rf /` or\n * `bash -c \"sudo dd ...\"` still trip the filter.\n *\n * This is a *prompt* heuristic, not a security boundary: it decides which\n * unmatched commands fall back to approval instead of auto-allow. It can\n * never enumerate every destructive command — anything that must be hard\n * blocked belongs in a `deny` rule in `permissions.yml`.\n */\nexport const DANGEROUS_COMMAND_PATTERNS: readonly string[] = [\n\t// recursive/forced deletion (flag clusters normalize to sorted letters,\n\t// so `-rf`/`-fr` become `-fr` and are caught by the `-f*` prefix; bare\n\t// `-r`/`-R` by the `-r*` prefix via case-insensitive matching)\n\t\"rm -r*\",\n\t\"rm -f*\",\n\t// privilege escalation\n\t\"sudo *\",\n\t\"doas *\",\n\t\"su *\",\n\t// raw disk / filesystem surgery\n\t\"dd *\",\n\t\"mkfs*\",\n\t// system state\n\t\"shutdown*\",\n\t\"reboot*\",\n\t\"halt*\",\n\t\"poweroff*\",\n\t// blanket permission changes\n\t\"chmod 777 *\",\n\t\"chmod -R *\",\n\t\"chown -R *\",\n\t// outward-facing / history-rewriting git and publishing\n\t\"git push*\",\n\t\"git reset --hard*\",\n\t\"git clean*\",\n\t\"npm publish*\",\n\t\"yarn publish*\",\n\t\"pnpm publish*\",\n\t// pipe-to-shell installers\n\t\"curl * | *\",\n\t\"wget * | *\",\n\t// inline interpreter eval — the code payload is another language the gate\n\t// cannot parse, so `python -c \"os.system('rm -rf /')\"` would otherwise\n\t// sail through as \"not shell-dangerous\". Running a script *file*\n\t// (`python script.py`) is deliberately NOT flagged: it is everyday dev\n\t// work, and the gate cannot see file contents anyway (see the module doc\n\t// on interpreter escape hatches).\n\t\"python* -c*\",\n\t\"node -e*\",\n\t\"node --eval*\",\n\t\"node -p*\",\n\t\"bun -e*\",\n\t\"bun --eval*\",\n\t\"deno eval*\",\n\t\"ruby -e*\",\n\t\"perl -e*\",\n\t\"php -r*\",\n];\n\n/**\n * Returns the first built-in dangerous pattern the command matches, or\n * `undefined` if the command passes the filter.\n */\nexport function findDangerousPattern(command: string): string | undefined {\n\treturn DANGEROUS_COMMAND_PATTERNS.find((pattern) => matchDenyPattern(command, pattern));\n}\n\n/** Normalize a (possibly relative or absolute) path into a forward-slash path relative to `cwd`, for glob matching. */\nfunction toMatchablePath(filePath: string, cwd: string): string {\n\tconst resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);\n\tconst rel = relative(cwd, resolved);\n\treturn rel.split(sep).join(\"/\");\n}\n\n/** Whether `filePath` (relative or absolute) resolves to a location inside `cwd`. */\nfunction isWithinProject(filePath: string, cwd: string): boolean {\n\tconst resolved = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);\n\tconst rel = relative(cwd, resolved);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\n/**\n * NOTE: this assumes the tool-call args carry a `command` string under the\n * exact key `command`. If/when this gate is wired into actual tool\n * dispatch, verify every gated tool's argument shape matches these\n * hardcoded key names — a mismatch doesn't error, it just silently fails to\n * match any `pattern`/`paths` rule and falls through to the (fail-safe)\n * default decision. Not currently exploitable: nothing outside this module\n * and its test calls `PermissionGate`/`loadRules` yet.\n */\nfunction getCommandArg(args: Record<string, unknown>): string | undefined {\n\treturn typeof args.command === \"string\" ? args.command : undefined;\n}\n\n/** Prefers `file_path` over `path` when both are present; see the note on `getCommandArg` above. */\nfunction getPathArg(args: Record<string, unknown>): string | undefined {\n\tif (typeof args.file_path === \"string\") return args.file_path;\n\tif (typeof args.path === \"string\") return args.path;\n\treturn undefined;\n}\n\nfunction describeMatch(rule: PermissionRule): string {\n\tconst parts = [`tool=${rule.tool}`];\n\tif (rule.pattern !== undefined) parts.push(`pattern=${JSON.stringify(rule.pattern)}`);\n\tif (rule.paths !== undefined) parts.push(`paths=${JSON.stringify(rule.paths)}`);\n\treturn `matched rule (${parts.join(\", \")}) -> ${rule.action}`;\n}\n\nfunction ruleMatches(rule: PermissionRule, toolName: string, args: Record<string, unknown>, cwd: string): boolean {\n\tif (rule.tool !== \"*\" && rule.tool.toLowerCase() !== toolName) return false;\n\n\tif (rule.pattern !== undefined) {\n\t\tconst command = getCommandArg(args);\n\t\tif (command === undefined || !matchCommandPattern(command, rule.pattern, rule.action)) return false;\n\t}\n\n\tif (rule.paths !== undefined) {\n\t\tconst filePath = getPathArg(args);\n\t\tif (filePath === undefined) return false;\n\t\tconst matchable = toMatchablePath(filePath, cwd);\n\t\tif (!rule.paths.some((pattern) => minimatch(matchable, pattern, { dot: true }))) return false;\n\t}\n\n\treturn true;\n}\n\nexport interface PermissionGateOptions {\n\t/** Project root used to determine whether a path is \"within the project\" for default decisions. Defaults to `process.cwd()`. */\n\tcwd?: string;\n\t/** Session permission mode; see `PermissionMode`. Defaults to `\"default\"`. */\n\tmode?: PermissionMode;\n}\n\n/**\n * Evaluates tool calls against an ordered list of permission rules,\n * returning a `deny` / `allow` / `approve` decision.\n */\nexport class PermissionGate {\n\tprivate readonly rules: PermissionRule[];\n\tprivate readonly cwd: string;\n\tprivate readonly mode: PermissionMode;\n\n\tconstructor(rules: PermissionRule[] = [], options: PermissionGateOptions = {}) {\n\t\tthis.rules = rules;\n\t\tthis.cwd = options.cwd ?? process.cwd();\n\t\tthis.mode = options.mode ?? \"default\";\n\t}\n\n\t/** Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit. */\n\tevaluate(toolName: string, args: Record<string, unknown> = {}): PermissionDecision {\n\t\tconst normalizedTool = toolName.toLowerCase();\n\n\t\tfor (const rule of this.rules) {\n\t\t\tif (ruleMatches(rule, normalizedTool, args, this.cwd)) {\n\t\t\t\treturn this.applyMode({ action: rule.action, reason: describeMatch(rule) });\n\t\t\t}\n\t\t}\n\n\t\treturn this.applyMode(this.defaultDecision(normalizedTool, args));\n\t}\n\n\t/**\n\t * Applies the session mode to a decision. `deny` is never relaxed by any\n\t * mode; `yolo` downgrades every `approve` to `allow`.\n\t */\n\tprivate applyMode(decision: PermissionDecision): PermissionDecision {\n\t\tif (this.mode === \"yolo\" && decision.action === \"approve\") {\n\t\t\treturn { action: \"allow\", reason: `yolo mode: auto-allowed (${decision.reason})` };\n\t\t}\n\t\treturn decision;\n\t}\n\n\tprivate defaultDecision(toolName: string, args: Record<string, unknown>): PermissionDecision {\n\t\tif (DEFAULT_ALLOWED_TOOLS.has(toolName)) {\n\t\t\treturn { action: \"allow\", reason: `no rule matched; \"${toolName}\" is allowed by default` };\n\t\t}\n\n\t\tif (toolName === \"bash\") {\n\t\t\tif (this.mode === \"auto\") {\n\t\t\t\tconst command = getCommandArg(args);\n\t\t\t\tif (command === undefined) {\n\t\t\t\t\treturn { action: \"approve\", reason: \"auto mode: bash call without a command string requires approval\" };\n\t\t\t\t}\n\t\t\t\tconst dangerous = findDangerousPattern(command);\n\t\t\t\tif (dangerous !== undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\taction: \"approve\",\n\t\t\t\t\t\treason: `auto mode: command matched dangerous pattern ${JSON.stringify(dangerous)}, requires approval`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { action: \"allow\", reason: \"auto mode: no rule matched and command passed the danger filter\" };\n\t\t\t}\n\t\t\treturn { action: \"approve\", reason: \"no rule matched; bash commands require approval by default\" };\n\t\t}\n\n\t\tif (PATH_SCOPED_TOOLS.has(toolName)) {\n\t\t\tconst filePath = getPathArg(args);\n\t\t\tif (filePath !== undefined && isWithinProject(filePath, this.cwd)) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project (or missing), requires approval\",\n\t\t\t};\n\t\t}\n\n\t\tif (READ_ONLY_PATH_TOOLS.has(toolName)) {\n\t\t\t// Unlike read/write/edit, these tools treat a missing `path` as the\n\t\t\t// cwd, so an absent path arg is within the project by definition.\n\t\t\tconst filePath = getPathArg(args) ?? \".\";\n\t\t\tif (isWithinProject(filePath, this.cwd)) {\n\t\t\t\treturn { action: \"allow\", reason: \"no rule matched; read-only tool allowed by default within the project\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\taction: \"approve\",\n\t\t\t\treason: \"no rule matched; path is outside the project, requires approval\",\n\t\t\t};\n\t\t}\n\n\t\treturn { action: \"approve\", reason: `no rule matched for tool \"${toolName}\"; defaults to approve` };\n\t}\n}\n"]}
@@ -16,6 +16,8 @@ export declare const WORKTREE_DIR_NAME = ".draht-worktrees";
16
16
  /** Result of attempting to merge a task's worktree branch back into its base branch. */
17
17
  export interface MergeResult {
18
18
  success: boolean;
19
+ /** The `agent/<taskId>` branch the task's work is committed on. Absent for an unknown `taskId`. */
20
+ branch?: string;
19
21
  /** Paths with unresolved conflicts. Present (possibly empty) only when `success` is false. */
20
22
  conflicts?: string[];
21
23
  }
@@ -1 +1 @@
1
- {"version":3,"file":"worktree.d.ts","sourceRoot":"","sources":["../../../src/core/multi-agent/worktree.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAMH,kGAAkG;AAClG,eAAO,MAAM,iBAAiB,qBAAqB,CAAC;AAEpD,wFAAwF;AACxF,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAaD;;;GAGG;AACH,qBAAa,gBAAgB;IAC5B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAqC;IAE/D,+DAA+D;IAC/D,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAO9B;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAsB/D;IAED;;;;;;OAMG;IACH,KAAK,CA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