@dirgha/code 1.2.0

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 (360) hide show
  1. package/LICENSE +101 -0
  2. package/README.md +674 -0
  3. package/dist/dirgha.mjs +2185 -0
  4. package/dist_v2/acp/index.d.ts +1 -0
  5. package/dist_v2/acp/index.js +2 -0
  6. package/dist_v2/acp/server.d.ts +31 -0
  7. package/dist_v2/acp/server.js +137 -0
  8. package/dist_v2/cli/auth-cmd.d.ts +10 -0
  9. package/dist_v2/cli/auth-cmd.js +69 -0
  10. package/dist_v2/cli/config.d.ts +46 -0
  11. package/dist_v2/cli/config.js +70 -0
  12. package/dist_v2/cli/flags.d.ts +10 -0
  13. package/dist_v2/cli/flags.js +49 -0
  14. package/dist_v2/cli/flows/full-cycle.d.ts +30 -0
  15. package/dist_v2/cli/flows/full-cycle.js +39 -0
  16. package/dist_v2/cli/flows/index.d.ts +2 -0
  17. package/dist_v2/cli/flows/index.js +3 -0
  18. package/dist_v2/cli/flows/tarball.d.ts +10 -0
  19. package/dist_v2/cli/flows/tarball.js +47 -0
  20. package/dist_v2/cli/index.d.ts +4 -0
  21. package/dist_v2/cli/index.js +5 -0
  22. package/dist_v2/cli/interactive.d.ts +21 -0
  23. package/dist_v2/cli/interactive.js +207 -0
  24. package/dist_v2/cli/main.d.ts +10 -0
  25. package/dist_v2/cli/main.js +173 -0
  26. package/dist_v2/cli/models-cmd.d.ts +6 -0
  27. package/dist_v2/cli/models-cmd.js +50 -0
  28. package/dist_v2/cli/setup.d.ts +13 -0
  29. package/dist_v2/cli/setup.js +128 -0
  30. package/dist_v2/cli/slash/account.d.ts +10 -0
  31. package/dist_v2/cli/slash/account.js +59 -0
  32. package/dist_v2/cli/slash/clear.d.ts +8 -0
  33. package/dist_v2/cli/slash/clear.js +15 -0
  34. package/dist_v2/cli/slash/compact.d.ts +7 -0
  35. package/dist_v2/cli/slash/compact.js +13 -0
  36. package/dist_v2/cli/slash/config.d.ts +8 -0
  37. package/dist_v2/cli/slash/config.js +49 -0
  38. package/dist_v2/cli/slash/exit.d.ts +7 -0
  39. package/dist_v2/cli/slash/exit.js +16 -0
  40. package/dist_v2/cli/slash/fleet.d.ts +7 -0
  41. package/dist_v2/cli/slash/fleet.js +22 -0
  42. package/dist_v2/cli/slash/help.d.ts +9 -0
  43. package/dist_v2/cli/slash/help.js +31 -0
  44. package/dist_v2/cli/slash/history.d.ts +7 -0
  45. package/dist_v2/cli/slash/history.js +42 -0
  46. package/dist_v2/cli/slash/index.d.ts +30 -0
  47. package/dist_v2/cli/slash/index.js +52 -0
  48. package/dist_v2/cli/slash/init.d.ts +8 -0
  49. package/dist_v2/cli/slash/init.js +57 -0
  50. package/dist_v2/cli/slash/keys.d.ts +8 -0
  51. package/dist_v2/cli/slash/keys.js +101 -0
  52. package/dist_v2/cli/slash/login.d.ts +10 -0
  53. package/dist_v2/cli/slash/login.js +47 -0
  54. package/dist_v2/cli/slash/memory.d.ts +8 -0
  55. package/dist_v2/cli/slash/memory.js +101 -0
  56. package/dist_v2/cli/slash/mode.d.ts +8 -0
  57. package/dist_v2/cli/slash/mode.js +30 -0
  58. package/dist_v2/cli/slash/models.d.ts +8 -0
  59. package/dist_v2/cli/slash/models.js +73 -0
  60. package/dist_v2/cli/slash/resume.d.ts +8 -0
  61. package/dist_v2/cli/slash/resume.js +24 -0
  62. package/dist_v2/cli/slash/session.d.ts +8 -0
  63. package/dist_v2/cli/slash/session.js +74 -0
  64. package/dist_v2/cli/slash/setup.d.ts +8 -0
  65. package/dist_v2/cli/slash/setup.js +50 -0
  66. package/dist_v2/cli/slash/status.d.ts +7 -0
  67. package/dist_v2/cli/slash/status.js +37 -0
  68. package/dist_v2/cli/slash/theme.d.ts +9 -0
  69. package/dist_v2/cli/slash/theme.js +53 -0
  70. package/dist_v2/cli/slash/types.d.ts +14 -0
  71. package/dist_v2/cli/slash/types.js +9 -0
  72. package/dist_v2/cli/slash/upgrade.d.ts +9 -0
  73. package/dist_v2/cli/slash/upgrade.js +66 -0
  74. package/dist_v2/cli/slash.d.ts +72 -0
  75. package/dist_v2/cli/slash.js +77 -0
  76. package/dist_v2/cli/subcommands/ask.d.ts +17 -0
  77. package/dist_v2/cli/subcommands/ask.js +76 -0
  78. package/dist_v2/cli/subcommands/audit.d.ts +15 -0
  79. package/dist_v2/cli/subcommands/audit.js +128 -0
  80. package/dist_v2/cli/subcommands/chat.d.ts +13 -0
  81. package/dist_v2/cli/subcommands/chat.js +72 -0
  82. package/dist_v2/cli/subcommands/compact.d.ts +14 -0
  83. package/dist_v2/cli/subcommands/compact.js +114 -0
  84. package/dist_v2/cli/subcommands/doctor.d.ts +11 -0
  85. package/dist_v2/cli/subcommands/doctor.js +103 -0
  86. package/dist_v2/cli/subcommands/export-session.d.ts +10 -0
  87. package/dist_v2/cli/subcommands/export-session.js +60 -0
  88. package/dist_v2/cli/subcommands/import-session.d.ts +11 -0
  89. package/dist_v2/cli/subcommands/import-session.js +77 -0
  90. package/dist_v2/cli/subcommands/index.d.ts +40 -0
  91. package/dist_v2/cli/subcommands/index.js +38 -0
  92. package/dist_v2/cli/subcommands/init.d.ts +10 -0
  93. package/dist_v2/cli/subcommands/init.js +74 -0
  94. package/dist_v2/cli/subcommands/keys.d.ts +12 -0
  95. package/dist_v2/cli/subcommands/keys.js +136 -0
  96. package/dist_v2/cli/subcommands/login.d.ts +10 -0
  97. package/dist_v2/cli/subcommands/login.js +60 -0
  98. package/dist_v2/cli/subcommands/logout.d.ts +10 -0
  99. package/dist_v2/cli/subcommands/logout.js +21 -0
  100. package/dist_v2/cli/subcommands/models.d.ts +14 -0
  101. package/dist_v2/cli/subcommands/models.js +144 -0
  102. package/dist_v2/cli/subcommands/setup.d.ts +11 -0
  103. package/dist_v2/cli/subcommands/setup.js +107 -0
  104. package/dist_v2/cli/subcommands/stats.d.ts +13 -0
  105. package/dist_v2/cli/subcommands/stats.js +148 -0
  106. package/dist_v2/cli/subcommands/status.d.ts +14 -0
  107. package/dist_v2/cli/subcommands/status.js +91 -0
  108. package/dist_v2/cli/submit-paper.d.ts +15 -0
  109. package/dist_v2/cli/submit-paper.js +68 -0
  110. package/dist_v2/context/_fts.d.ts +62 -0
  111. package/dist_v2/context/_fts.js +195 -0
  112. package/dist_v2/context/branch.d.ts +18 -0
  113. package/dist_v2/context/branch.js +66 -0
  114. package/dist_v2/context/compaction.d.ts +26 -0
  115. package/dist_v2/context/compaction.js +120 -0
  116. package/dist_v2/context/index.d.ts +5 -0
  117. package/dist_v2/context/index.js +6 -0
  118. package/dist_v2/context/knowledge.d.ts +38 -0
  119. package/dist_v2/context/knowledge.js +146 -0
  120. package/dist_v2/context/memory.d.ts +80 -0
  121. package/dist_v2/context/memory.js +276 -0
  122. package/dist_v2/context/mode.d.ts +25 -0
  123. package/dist_v2/context/mode.js +81 -0
  124. package/dist_v2/context/session.d.ts +56 -0
  125. package/dist_v2/context/session.js +108 -0
  126. package/dist_v2/daemon/index.d.ts +2 -0
  127. package/dist_v2/daemon/index.js +3 -0
  128. package/dist_v2/daemon/protocol.d.ts +73 -0
  129. package/dist_v2/daemon/protocol.js +6 -0
  130. package/dist_v2/daemon/server.d.ts +35 -0
  131. package/dist_v2/daemon/server.js +191 -0
  132. package/dist_v2/eval/index.d.ts +5 -0
  133. package/dist_v2/eval/index.js +6 -0
  134. package/dist_v2/eval/regression.d.ts +14 -0
  135. package/dist_v2/eval/regression.js +106 -0
  136. package/dist_v2/eval/reporter.d.ts +7 -0
  137. package/dist_v2/eval/reporter.js +34 -0
  138. package/dist_v2/eval/swe-bench.d.ts +18 -0
  139. package/dist_v2/eval/swe-bench.js +23 -0
  140. package/dist_v2/eval/terminal-bench.d.ts +13 -0
  141. package/dist_v2/eval/terminal-bench.js +19 -0
  142. package/dist_v2/eval/types.d.ts +36 -0
  143. package/dist_v2/eval/types.js +5 -0
  144. package/dist_v2/fleet/apply-back.d.ts +27 -0
  145. package/dist_v2/fleet/apply-back.js +191 -0
  146. package/dist_v2/fleet/cli-command.d.ts +61 -0
  147. package/dist_v2/fleet/cli-command.js +329 -0
  148. package/dist_v2/fleet/index.d.ts +21 -0
  149. package/dist_v2/fleet/index.js +21 -0
  150. package/dist_v2/fleet/runner.d.ts +28 -0
  151. package/dist_v2/fleet/runner.js +347 -0
  152. package/dist_v2/fleet/tripleshot.d.ts +21 -0
  153. package/dist_v2/fleet/tripleshot.js +222 -0
  154. package/dist_v2/fleet/types.d.ts +193 -0
  155. package/dist_v2/fleet/types.js +24 -0
  156. package/dist_v2/fleet/worktree.d.ts +51 -0
  157. package/dist_v2/fleet/worktree.js +176 -0
  158. package/dist_v2/hooks/index.d.ts +1 -0
  159. package/dist_v2/hooks/index.js +2 -0
  160. package/dist_v2/hooks/registry.d.ts +21 -0
  161. package/dist_v2/hooks/registry.js +40 -0
  162. package/dist_v2/index.d.ts +12 -0
  163. package/dist_v2/index.js +11 -0
  164. package/dist_v2/integrations/arniko-client.d.ts +42 -0
  165. package/dist_v2/integrations/arniko-client.js +86 -0
  166. package/dist_v2/integrations/auth.d.ts +45 -0
  167. package/dist_v2/integrations/auth.js +54 -0
  168. package/dist_v2/integrations/billing.d.ts +71 -0
  169. package/dist_v2/integrations/billing.js +107 -0
  170. package/dist_v2/integrations/bucky-client.d.ts +105 -0
  171. package/dist_v2/integrations/bucky-client.js +76 -0
  172. package/dist_v2/integrations/deploy-client.d.ts +60 -0
  173. package/dist_v2/integrations/deploy-client.js +87 -0
  174. package/dist_v2/integrations/device-auth.d.ts +48 -0
  175. package/dist_v2/integrations/device-auth.js +192 -0
  176. package/dist_v2/integrations/entitlements.d.ts +34 -0
  177. package/dist_v2/integrations/entitlements.js +43 -0
  178. package/dist_v2/integrations/http.d.ts +22 -0
  179. package/dist_v2/integrations/http.js +114 -0
  180. package/dist_v2/integrations/index.d.ts +8 -0
  181. package/dist_v2/integrations/index.js +15 -0
  182. package/dist_v2/intelligence/cost.d.ts +28 -0
  183. package/dist_v2/intelligence/cost.js +58 -0
  184. package/dist_v2/intelligence/error-classifier.d.ts +8 -0
  185. package/dist_v2/intelligence/error-classifier.js +71 -0
  186. package/dist_v2/intelligence/index.d.ts +5 -0
  187. package/dist_v2/intelligence/index.js +6 -0
  188. package/dist_v2/intelligence/prices.d.ts +13 -0
  189. package/dist_v2/intelligence/prices.js +26 -0
  190. package/dist_v2/intelligence/smart-router.d.ts +21 -0
  191. package/dist_v2/intelligence/smart-router.js +59 -0
  192. package/dist_v2/intelligence/telemetry.d.ts +22 -0
  193. package/dist_v2/intelligence/telemetry.js +31 -0
  194. package/dist_v2/kernel/agent-loop.d.ts +32 -0
  195. package/dist_v2/kernel/agent-loop.js +151 -0
  196. package/dist_v2/kernel/event-stream.d.ts +18 -0
  197. package/dist_v2/kernel/event-stream.js +102 -0
  198. package/dist_v2/kernel/index.d.ts +4 -0
  199. package/dist_v2/kernel/index.js +5 -0
  200. package/dist_v2/kernel/message.d.ts +29 -0
  201. package/dist_v2/kernel/message.js +118 -0
  202. package/dist_v2/kernel/types.d.ts +206 -0
  203. package/dist_v2/kernel/types.js +9 -0
  204. package/dist_v2/mcp/client.d.ts +44 -0
  205. package/dist_v2/mcp/client.js +63 -0
  206. package/dist_v2/mcp/index.d.ts +3 -0
  207. package/dist_v2/mcp/index.js +4 -0
  208. package/dist_v2/mcp/tool-bridge.d.ts +11 -0
  209. package/dist_v2/mcp/tool-bridge.js +33 -0
  210. package/dist_v2/mcp/transport.d.ts +29 -0
  211. package/dist_v2/mcp/transport.js +73 -0
  212. package/dist_v2/parity/index.d.ts +3 -0
  213. package/dist_v2/parity/index.js +4 -0
  214. package/dist_v2/parity/mock-openai-compat.d.ts +15 -0
  215. package/dist_v2/parity/mock-openai-compat.js +35 -0
  216. package/dist_v2/parity/runner.d.ts +21 -0
  217. package/dist_v2/parity/runner.js +76 -0
  218. package/dist_v2/parity/scenarios.d.ts +20 -0
  219. package/dist_v2/parity/scenarios.js +70 -0
  220. package/dist_v2/providers/anthropic.d.ts +21 -0
  221. package/dist_v2/providers/anthropic.js +191 -0
  222. package/dist_v2/providers/dispatch.d.ts +11 -0
  223. package/dist_v2/providers/dispatch.js +45 -0
  224. package/dist_v2/providers/fireworks.d.ts +18 -0
  225. package/dist_v2/providers/fireworks.js +44 -0
  226. package/dist_v2/providers/gemini.d.ts +19 -0
  227. package/dist_v2/providers/gemini.js +188 -0
  228. package/dist_v2/providers/http.d.ts +41 -0
  229. package/dist_v2/providers/http.js +188 -0
  230. package/dist_v2/providers/iface.d.ts +18 -0
  231. package/dist_v2/providers/iface.js +18 -0
  232. package/dist_v2/providers/index.d.ts +39 -0
  233. package/dist_v2/providers/index.js +51 -0
  234. package/dist_v2/providers/nvidia.d.ts +27 -0
  235. package/dist_v2/providers/nvidia.js +142 -0
  236. package/dist_v2/providers/ollama.d.ts +15 -0
  237. package/dist_v2/providers/ollama.js +37 -0
  238. package/dist_v2/providers/openai-compat.d.ts +29 -0
  239. package/dist_v2/providers/openai-compat.js +239 -0
  240. package/dist_v2/providers/openai.d.ts +20 -0
  241. package/dist_v2/providers/openai.js +107 -0
  242. package/dist_v2/providers/openrouter.d.ts +24 -0
  243. package/dist_v2/providers/openrouter.js +69 -0
  244. package/dist_v2/safety/approval-bus.d.ts +26 -0
  245. package/dist_v2/safety/approval-bus.js +48 -0
  246. package/dist_v2/safety/audit-log.d.ts +27 -0
  247. package/dist_v2/safety/audit-log.js +71 -0
  248. package/dist_v2/safety/index.d.ts +4 -0
  249. package/dist_v2/safety/index.js +5 -0
  250. package/dist_v2/safety/policy.d.ts +32 -0
  251. package/dist_v2/safety/policy.js +131 -0
  252. package/dist_v2/safety/sandbox/bwrap.d.ts +11 -0
  253. package/dist_v2/safety/sandbox/bwrap.js +52 -0
  254. package/dist_v2/safety/sandbox/iface.d.ts +29 -0
  255. package/dist_v2/safety/sandbox/iface.js +8 -0
  256. package/dist_v2/safety/sandbox/index.d.ts +7 -0
  257. package/dist_v2/safety/sandbox/index.js +8 -0
  258. package/dist_v2/safety/sandbox/landlock.d.ts +17 -0
  259. package/dist_v2/safety/sandbox/landlock.js +26 -0
  260. package/dist_v2/safety/sandbox/noop.d.ts +12 -0
  261. package/dist_v2/safety/sandbox/noop.js +52 -0
  262. package/dist_v2/safety/sandbox/seatbelt.d.ts +11 -0
  263. package/dist_v2/safety/sandbox/seatbelt.js +49 -0
  264. package/dist_v2/safety/sandbox/select.d.ts +6 -0
  265. package/dist_v2/safety/sandbox/select.js +42 -0
  266. package/dist_v2/safety/sandbox/windows.d.ts +13 -0
  267. package/dist_v2/safety/sandbox/windows.js +22 -0
  268. package/dist_v2/skills/index.d.ts +3 -0
  269. package/dist_v2/skills/index.js +4 -0
  270. package/dist_v2/skills/loader.d.ts +38 -0
  271. package/dist_v2/skills/loader.js +102 -0
  272. package/dist_v2/skills/matcher.d.ts +14 -0
  273. package/dist_v2/skills/matcher.js +72 -0
  274. package/dist_v2/skills/runtime.d.ts +13 -0
  275. package/dist_v2/skills/runtime.js +40 -0
  276. package/dist_v2/subagents/delegator.d.ts +36 -0
  277. package/dist_v2/subagents/delegator.js +82 -0
  278. package/dist_v2/subagents/index.d.ts +2 -0
  279. package/dist_v2/subagents/index.js +3 -0
  280. package/dist_v2/subagents/pool.d.ts +18 -0
  281. package/dist_v2/subagents/pool.js +31 -0
  282. package/dist_v2/tools/browser.d.ts +27 -0
  283. package/dist_v2/tools/browser.js +179 -0
  284. package/dist_v2/tools/checkpoint.d.ts +25 -0
  285. package/dist_v2/tools/checkpoint.js +222 -0
  286. package/dist_v2/tools/cron.d.ts +32 -0
  287. package/dist_v2/tools/cron.js +160 -0
  288. package/dist_v2/tools/diff.d.ts +18 -0
  289. package/dist_v2/tools/diff.js +117 -0
  290. package/dist_v2/tools/exec.d.ts +19 -0
  291. package/dist_v2/tools/exec.js +49 -0
  292. package/dist_v2/tools/fs-edit.d.ts +11 -0
  293. package/dist_v2/tools/fs-edit.js +81 -0
  294. package/dist_v2/tools/fs-ls.d.ts +7 -0
  295. package/dist_v2/tools/fs-ls.js +57 -0
  296. package/dist_v2/tools/fs-read.d.ts +7 -0
  297. package/dist_v2/tools/fs-read.js +60 -0
  298. package/dist_v2/tools/fs-write.d.ts +8 -0
  299. package/dist_v2/tools/fs-write.js +46 -0
  300. package/dist_v2/tools/git.d.ts +8 -0
  301. package/dist_v2/tools/git.js +57 -0
  302. package/dist_v2/tools/index.d.ts +25 -0
  303. package/dist_v2/tools/index.js +39 -0
  304. package/dist_v2/tools/multimodal.d.ts +41 -0
  305. package/dist_v2/tools/multimodal.js +381 -0
  306. package/dist_v2/tools/permission.d.ts +27 -0
  307. package/dist_v2/tools/permission.js +43 -0
  308. package/dist_v2/tools/registry.d.ts +44 -0
  309. package/dist_v2/tools/registry.js +62 -0
  310. package/dist_v2/tools/search-glob.d.ts +7 -0
  311. package/dist_v2/tools/search-glob.js +98 -0
  312. package/dist_v2/tools/search-grep.d.ts +7 -0
  313. package/dist_v2/tools/search-grep.js +109 -0
  314. package/dist_v2/tools/shell.d.ts +10 -0
  315. package/dist_v2/tools/shell.js +76 -0
  316. package/dist_v2/tools/task.d.ts +8 -0
  317. package/dist_v2/tools/task.js +37 -0
  318. package/dist_v2/tui/approval.d.ts +7 -0
  319. package/dist_v2/tui/approval.js +55 -0
  320. package/dist_v2/tui/index.d.ts +4 -0
  321. package/dist_v2/tui/index.js +5 -0
  322. package/dist_v2/tui/ink/App.d.ts +39 -0
  323. package/dist_v2/tui/ink/App.js +206 -0
  324. package/dist_v2/tui/ink/components/AtFileComplete.d.ts +25 -0
  325. package/dist_v2/tui/ink/components/AtFileComplete.js +158 -0
  326. package/dist_v2/tui/ink/components/HelpOverlay.d.ts +24 -0
  327. package/dist_v2/tui/ink/components/HelpOverlay.js +130 -0
  328. package/dist_v2/tui/ink/components/InputBox.d.ts +35 -0
  329. package/dist_v2/tui/ink/components/InputBox.js +153 -0
  330. package/dist_v2/tui/ink/components/Logo.d.ts +12 -0
  331. package/dist_v2/tui/ink/components/Logo.js +27 -0
  332. package/dist_v2/tui/ink/components/ModelPicker.d.ts +26 -0
  333. package/dist_v2/tui/ink/components/ModelPicker.js +80 -0
  334. package/dist_v2/tui/ink/components/PasteCollapse.d.ts +36 -0
  335. package/dist_v2/tui/ink/components/PasteCollapse.js +59 -0
  336. package/dist_v2/tui/ink/components/StatusBar.d.ts +18 -0
  337. package/dist_v2/tui/ink/components/StatusBar.js +41 -0
  338. package/dist_v2/tui/ink/components/StreamingText.d.ts +14 -0
  339. package/dist_v2/tui/ink/components/StreamingText.js +11 -0
  340. package/dist_v2/tui/ink/components/ThinkingBlock.d.ts +13 -0
  341. package/dist_v2/tui/ink/components/ThinkingBlock.js +13 -0
  342. package/dist_v2/tui/ink/components/ToolBox.d.ts +20 -0
  343. package/dist_v2/tui/ink/components/ToolBox.js +63 -0
  344. package/dist_v2/tui/ink/components/vim-bindings.d.ts +43 -0
  345. package/dist_v2/tui/ink/components/vim-bindings.js +135 -0
  346. package/dist_v2/tui/ink/index.d.ts +39 -0
  347. package/dist_v2/tui/ink/index.js +47 -0
  348. package/dist_v2/tui/ink/use-event-projection.d.ts +51 -0
  349. package/dist_v2/tui/ink/use-event-projection.js +126 -0
  350. package/dist_v2/tui/ink/use-overlays.d.ts +24 -0
  351. package/dist_v2/tui/ink/use-overlays.js +50 -0
  352. package/dist_v2/tui/renderer.d.ts +19 -0
  353. package/dist_v2/tui/renderer.js +64 -0
  354. package/dist_v2/tui/status-bar.d.ts +12 -0
  355. package/dist_v2/tui/status-bar.js +16 -0
  356. package/dist_v2/tui/theme.d.ts +27 -0
  357. package/dist_v2/tui/theme.js +56 -0
  358. package/dist_v2/utils/json-repair.d.ts +7 -0
  359. package/dist_v2/utils/json-repair.js +45 -0
  360. package/package.json +113 -0
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Shared OpenAI-compatible /chat/completions streaming adapter.
3
+ *
4
+ * Most providers (NIM, OpenRouter, OpenAI, local model runners) speak the
5
+ * same SSE wire format: a stream of `data: {...}` lines carrying chat
6
+ * completion deltas, terminated by `data: [DONE]`. This file parses that
7
+ * stream into canonical AgentEvents. All provider adapters that speak the
8
+ * OpenAI-compatible dialect use this helper; they differ only in base
9
+ * URL, model roster, and per-model request shaping.
10
+ */
11
+ import { streamSSE } from './http.js';
12
+ import { ProviderError } from './iface.js';
13
+ import { repairJSON } from '../utils/json-repair.js';
14
+ export async function* streamChatCompletions(opts) {
15
+ const body = {
16
+ model: opts.model,
17
+ messages: toOpenAIMessages(opts.messages),
18
+ stream: true,
19
+ stream_options: { include_usage: true },
20
+ };
21
+ if (opts.temperature !== undefined)
22
+ body.temperature = opts.temperature;
23
+ if (opts.maxTokens !== undefined)
24
+ body.max_tokens = opts.maxTokens;
25
+ if (opts.tools && opts.tools.length > 0) {
26
+ body.tools = toOpenAITools(opts.tools, opts.sanitizeToolDescriptions);
27
+ if (opts.toolChoice && opts.toolChoice !== 'auto')
28
+ body.tool_choice = opts.toolChoice;
29
+ }
30
+ if (opts.extraBody)
31
+ Object.assign(body, opts.extraBody);
32
+ const state = new StreamState(opts.includeThinking ?? false);
33
+ for await (const payload of streamSSE({
34
+ providerName: opts.providerName,
35
+ url: opts.endpoint,
36
+ apiKey: opts.apiKey,
37
+ body,
38
+ extraHeaders: opts.extraHeaders,
39
+ signal: opts.signal,
40
+ timeoutMs: opts.timeoutMs,
41
+ })) {
42
+ if (payload === '[DONE]')
43
+ break;
44
+ let chunk;
45
+ try {
46
+ chunk = JSON.parse(payload);
47
+ }
48
+ catch {
49
+ const repaired = repairJSON(payload);
50
+ if (!repaired || !repaired.choices)
51
+ continue;
52
+ chunk = repaired;
53
+ }
54
+ yield* state.ingest(chunk);
55
+ }
56
+ yield* state.finalise();
57
+ }
58
+ function toOpenAIMessages(messages) {
59
+ const out = [];
60
+ for (const msg of messages) {
61
+ if (msg.role === 'tool')
62
+ continue;
63
+ if (typeof msg.content === 'string') {
64
+ out.push({ role: msg.role === 'assistant' ? 'assistant' : msg.role, content: msg.content });
65
+ continue;
66
+ }
67
+ const parts = msg.content;
68
+ if (msg.role === 'assistant') {
69
+ const texts = [];
70
+ const toolCalls = [];
71
+ for (const p of parts) {
72
+ if (p.type === 'text')
73
+ texts.push(p.text);
74
+ else if (p.type === 'tool_use') {
75
+ toolCalls.push({
76
+ id: p.id,
77
+ type: 'function',
78
+ function: { name: p.name, arguments: JSON.stringify(p.input ?? {}) },
79
+ });
80
+ }
81
+ }
82
+ out.push({
83
+ role: 'assistant',
84
+ content: texts.length > 0 ? texts.join('') : null,
85
+ tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
86
+ });
87
+ continue;
88
+ }
89
+ const results = parts.filter(p => p.type === 'tool_result');
90
+ const texts = parts
91
+ .filter((p) => p.type === 'text')
92
+ .map(p => p.text);
93
+ if (texts.length > 0)
94
+ out.push({ role: msg.role === 'system' ? 'system' : 'user', content: texts.join('') });
95
+ for (const r of results) {
96
+ if (r.type !== 'tool_result')
97
+ continue;
98
+ out.push({
99
+ role: 'tool',
100
+ tool_call_id: r.toolUseId,
101
+ content: r.content,
102
+ });
103
+ }
104
+ }
105
+ return out;
106
+ }
107
+ function toOpenAITools(tools, sanitize) {
108
+ return tools.map(t => ({
109
+ type: 'function',
110
+ function: {
111
+ name: t.name,
112
+ description: sanitize ? sanitize(t.description) : t.description,
113
+ parameters: t.inputSchema ?? { type: 'object', properties: {} },
114
+ },
115
+ }));
116
+ }
117
+ class StreamState {
118
+ includeThinking;
119
+ textOpen = false;
120
+ thinkingOpen = false;
121
+ toolOpen = new Map();
122
+ toolIndexToId = new Map();
123
+ usageEmitted = false;
124
+ constructor(includeThinking) {
125
+ this.includeThinking = includeThinking;
126
+ }
127
+ *ingest(chunk) {
128
+ const choice = chunk.choices?.[0];
129
+ if (!choice) {
130
+ yield* this.maybeEmitUsage(chunk);
131
+ return;
132
+ }
133
+ const delta = choice.delta ?? {};
134
+ if (this.includeThinking && typeof delta.reasoning_content === 'string') {
135
+ const r = delta.reasoning_content ?? '';
136
+ if (r.length > 0) {
137
+ if (!this.thinkingOpen) {
138
+ yield { type: 'thinking_start' };
139
+ this.thinkingOpen = true;
140
+ }
141
+ yield { type: 'thinking_delta', delta: r };
142
+ }
143
+ }
144
+ if (typeof delta.content === 'string' && delta.content.length > 0) {
145
+ if (this.thinkingOpen) {
146
+ yield { type: 'thinking_end' };
147
+ this.thinkingOpen = false;
148
+ }
149
+ if (!this.textOpen) {
150
+ yield { type: 'text_start' };
151
+ this.textOpen = true;
152
+ }
153
+ yield { type: 'text_delta', delta: delta.content };
154
+ }
155
+ if (delta.tool_calls) {
156
+ for (const tc of delta.tool_calls) {
157
+ const index = tc.index ?? 0;
158
+ let id = this.toolIndexToId.get(index);
159
+ if (tc.id && tc.id.length > 0) {
160
+ id = tc.id;
161
+ this.toolIndexToId.set(index, id);
162
+ }
163
+ if (!id)
164
+ continue;
165
+ let entry = this.toolOpen.get(id);
166
+ if (!entry) {
167
+ const name = tc.function?.name ?? '';
168
+ entry = { name, bufferedJson: '' };
169
+ this.toolOpen.set(id, entry);
170
+ if (this.textOpen) {
171
+ yield { type: 'text_end' };
172
+ this.textOpen = false;
173
+ }
174
+ if (this.thinkingOpen) {
175
+ yield { type: 'thinking_end' };
176
+ this.thinkingOpen = false;
177
+ }
178
+ yield { type: 'toolcall_start', id, name };
179
+ }
180
+ else if (!entry.name && tc.function?.name) {
181
+ entry.name = tc.function.name;
182
+ }
183
+ const argsDelta = tc.function?.arguments ?? '';
184
+ if (argsDelta.length > 0) {
185
+ entry.bufferedJson += argsDelta;
186
+ yield { type: 'toolcall_delta', id, deltaJson: argsDelta };
187
+ }
188
+ }
189
+ }
190
+ if (choice.finish_reason) {
191
+ yield* this.closeOpen();
192
+ }
193
+ yield* this.maybeEmitUsage(chunk);
194
+ }
195
+ *finalise() {
196
+ yield* this.closeOpen();
197
+ }
198
+ *closeOpen() {
199
+ if (this.textOpen) {
200
+ yield { type: 'text_end' };
201
+ this.textOpen = false;
202
+ }
203
+ if (this.thinkingOpen) {
204
+ yield { type: 'thinking_end' };
205
+ this.thinkingOpen = false;
206
+ }
207
+ for (const [id, entry] of this.toolOpen) {
208
+ const input = parseArguments(entry.bufferedJson);
209
+ yield { type: 'toolcall_end', id, input };
210
+ }
211
+ this.toolOpen.clear();
212
+ }
213
+ *maybeEmitUsage(chunk) {
214
+ if (this.usageEmitted)
215
+ return;
216
+ const usage = chunk.usage;
217
+ if (!usage)
218
+ return;
219
+ this.usageEmitted = true;
220
+ yield {
221
+ type: 'usage',
222
+ inputTokens: usage.prompt_tokens ?? 0,
223
+ outputTokens: usage.completion_tokens ?? 0,
224
+ cachedTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
225
+ };
226
+ }
227
+ }
228
+ function parseArguments(json) {
229
+ if (!json)
230
+ return {};
231
+ try {
232
+ return JSON.parse(json);
233
+ }
234
+ catch {
235
+ return repairJSON(json);
236
+ }
237
+ }
238
+ void ProviderError;
239
+ //# sourceMappingURL=openai-compat.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * OpenAI provider (native /chat/completions over the api.openai.com host).
3
+ * Thin wrapper; most logic lives in the shared openai-compat adapter.
4
+ */
5
+ import type { AgentEvent } from '../kernel/types.js';
6
+ import type { Provider, StreamRequest, ProviderConfig, ImageGenRequest, ImageGenResult } from './iface.js';
7
+ export declare class OpenAIProvider implements Provider {
8
+ readonly id = "openai";
9
+ private readonly apiKey;
10
+ private readonly baseUrl;
11
+ private readonly timeoutMs;
12
+ private readonly organization?;
13
+ constructor(config: ProviderConfig & {
14
+ organization?: string;
15
+ });
16
+ supportsTools(modelId: string): boolean;
17
+ supportsThinking(modelId: string): boolean;
18
+ stream(req: StreamRequest): AsyncIterable<AgentEvent>;
19
+ generateImage(req: ImageGenRequest, signal?: AbortSignal): Promise<ImageGenResult>;
20
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * OpenAI provider (native /chat/completions over the api.openai.com host).
3
+ * Thin wrapper; most logic lives in the shared openai-compat adapter.
4
+ */
5
+ import { ProviderError } from './iface.js';
6
+ import { postJSON } from './http.js';
7
+ import { streamChatCompletions } from './openai-compat.js';
8
+ const DEFAULT_BASE = 'https://api.openai.com/v1';
9
+ const DEFAULT_IMAGE_MODEL = 'dall-e-3';
10
+ const IMAGE_GEN_TIMEOUT_MS = 30_000;
11
+ const REASONING_PREFIXES = ['o1', 'o3', 'o4'];
12
+ export class OpenAIProvider {
13
+ id = 'openai';
14
+ apiKey;
15
+ baseUrl;
16
+ timeoutMs;
17
+ organization;
18
+ constructor(config) {
19
+ this.apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? '';
20
+ if (!this.apiKey)
21
+ throw new ProviderError('OPENAI_API_KEY is required', this.id);
22
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE).replace(/\/+$/, '');
23
+ this.timeoutMs = config.timeoutMs ?? 60_000;
24
+ this.organization = config.organization;
25
+ }
26
+ supportsTools(modelId) {
27
+ const m = modelId.replace(/^openai\//, '');
28
+ return m.startsWith('gpt-') || m.startsWith('o1') || m.startsWith('o3') || m.startsWith('o4');
29
+ }
30
+ supportsThinking(modelId) {
31
+ const m = modelId.replace(/^openai\//, '');
32
+ return REASONING_PREFIXES.some(p => m.startsWith(p));
33
+ }
34
+ stream(req) {
35
+ const model = req.model.replace(/^openai\//, '');
36
+ const extraHeaders = {};
37
+ if (this.organization)
38
+ extraHeaders['OpenAI-Organization'] = this.organization;
39
+ return streamChatCompletions({
40
+ providerName: this.id,
41
+ endpoint: `${this.baseUrl}/chat/completions`,
42
+ apiKey: this.apiKey,
43
+ model,
44
+ messages: req.messages,
45
+ tools: this.supportsTools(req.model) ? req.tools : undefined,
46
+ temperature: req.temperature,
47
+ maxTokens: req.maxTokens,
48
+ signal: req.signal,
49
+ timeoutMs: this.timeoutMs,
50
+ includeThinking: this.supportsThinking(req.model),
51
+ extraHeaders,
52
+ });
53
+ }
54
+ async generateImage(req, signal) {
55
+ const model = normalizeImageModel(req.model) ?? DEFAULT_IMAGE_MODEL;
56
+ const size = pickDalleSize(req.width ?? 1024, req.height ?? 1024);
57
+ const body = {
58
+ model,
59
+ prompt: req.prompt,
60
+ n: 1,
61
+ size,
62
+ response_format: 'b64_json',
63
+ };
64
+ const extraHeaders = {};
65
+ if (this.organization)
66
+ extraHeaders['OpenAI-Organization'] = this.organization;
67
+ const parsed = await postJSON({
68
+ url: `${this.baseUrl}/images/generations`,
69
+ apiKey: this.apiKey,
70
+ body,
71
+ providerName: this.id,
72
+ signal,
73
+ timeoutMs: IMAGE_GEN_TIMEOUT_MS,
74
+ extraHeaders: Object.keys(extraHeaders).length > 0 ? extraHeaders : undefined,
75
+ });
76
+ const base64 = parsed.data?.[0]?.b64_json;
77
+ if (!base64) {
78
+ throw new ProviderError('OpenAI image response missing b64_json payload', this.id);
79
+ }
80
+ return { base64, mimeType: 'image/png', model };
81
+ }
82
+ }
83
+ function normalizeImageModel(input) {
84
+ if (!input)
85
+ return undefined;
86
+ const lower = input.toLowerCase().replace(/^openai\//, '');
87
+ if (lower === 'dalle' || lower === 'dall-e' || lower === 'dall-e-3')
88
+ return 'dall-e-3';
89
+ if (lower === 'dall-e-2')
90
+ return 'dall-e-2';
91
+ return input;
92
+ }
93
+ /**
94
+ * DALL-E 3 accepts exactly: 1024x1024, 1792x1024, 1024x1792. Map (w,h)
95
+ * to the nearest landscape/portrait/square based on aspect ratio.
96
+ */
97
+ function pickDalleSize(width, height) {
98
+ if (width <= 0 || height <= 0)
99
+ return '1024x1024';
100
+ const ratio = width / height;
101
+ if (ratio > 1.2)
102
+ return '1792x1024';
103
+ if (ratio < 0.83)
104
+ return '1024x1792';
105
+ return '1024x1024';
106
+ }
107
+ //# sourceMappingURL=openai.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * OpenRouter provider. OpenAI-compatible, with three conveniences:
3
+ * - Includes the free tier Ling model used for code generation.
4
+ * - Emits provider-identifying headers that the OpenRouter console
5
+ * surfaces (HTTP-Referer, X-Title).
6
+ * - Supports free-tier models via the ":free" suffix.
7
+ */
8
+ import type { AgentEvent } from '../kernel/types.js';
9
+ import type { Provider, StreamRequest, ProviderConfig } from './iface.js';
10
+ export declare class OpenRouterProvider implements Provider {
11
+ readonly id = "openrouter";
12
+ private readonly apiKey;
13
+ private readonly baseUrl;
14
+ private readonly timeoutMs;
15
+ private readonly appName;
16
+ private readonly appUrl;
17
+ constructor(config: ProviderConfig & {
18
+ appName?: string;
19
+ appUrl?: string;
20
+ });
21
+ supportsTools(modelId: string): boolean;
22
+ supportsThinking(modelId: string): boolean;
23
+ stream(req: StreamRequest): AsyncIterable<AgentEvent>;
24
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * OpenRouter provider. OpenAI-compatible, with three conveniences:
3
+ * - Includes the free tier Ling model used for code generation.
4
+ * - Emits provider-identifying headers that the OpenRouter console
5
+ * surfaces (HTTP-Referer, X-Title).
6
+ * - Supports free-tier models via the ":free" suffix.
7
+ */
8
+ import { ProviderError } from './iface.js';
9
+ import { streamChatCompletions } from './openai-compat.js';
10
+ const DEFAULT_BASE = 'https://openrouter.ai/api/v1';
11
+ const TOOL_SUPPORT = [
12
+ /^inclusionai\/ling/,
13
+ /^anthropic\//,
14
+ /^openai\//,
15
+ /^google\/gemini/,
16
+ /^mistralai\//,
17
+ /^meta-llama\//,
18
+ /^qwen\//,
19
+ /^deepseek\//,
20
+ /^moonshotai\//,
21
+ /^minimaxai\//,
22
+ /^z-ai\//,
23
+ ];
24
+ const THINKING_PATTERNS = [/^deepseek-ai\//, /^anthropic\/claude-opus/, /^openai\/o[1-9]/];
25
+ export class OpenRouterProvider {
26
+ id = 'openrouter';
27
+ apiKey;
28
+ baseUrl;
29
+ timeoutMs;
30
+ appName;
31
+ appUrl;
32
+ constructor(config) {
33
+ this.apiKey = config.apiKey ?? process.env.OPENROUTER_API_KEY ?? '';
34
+ if (!this.apiKey)
35
+ throw new ProviderError('OPENROUTER_API_KEY is required', this.id);
36
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE).replace(/\/+$/, '');
37
+ this.timeoutMs = config.timeoutMs ?? 60_000;
38
+ this.appName = config.appName ?? 'dirgha-cli';
39
+ this.appUrl = config.appUrl ?? 'https://dirgha.ai';
40
+ }
41
+ supportsTools(modelId) {
42
+ const base = modelId.replace(/:free$/, '').replace(/^openrouter\//, '');
43
+ return TOOL_SUPPORT.some(rx => rx.test(base));
44
+ }
45
+ supportsThinking(modelId) {
46
+ return THINKING_PATTERNS.some(rx => rx.test(modelId));
47
+ }
48
+ stream(req) {
49
+ const model = req.model.replace(/^openrouter\//, '');
50
+ return streamChatCompletions({
51
+ providerName: this.id,
52
+ endpoint: `${this.baseUrl}/chat/completions`,
53
+ apiKey: this.apiKey,
54
+ model,
55
+ messages: req.messages,
56
+ tools: this.supportsTools(req.model) ? req.tools : undefined,
57
+ temperature: req.temperature,
58
+ maxTokens: req.maxTokens,
59
+ signal: req.signal,
60
+ timeoutMs: this.timeoutMs,
61
+ includeThinking: this.supportsThinking(req.model),
62
+ extraHeaders: {
63
+ 'HTTP-Referer': this.appUrl,
64
+ 'X-Title': this.appName,
65
+ },
66
+ });
67
+ }
68
+ }
69
+ //# sourceMappingURL=openrouter.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Approval bus. Pluggable subscribers receive ApprovalRequests; the
3
+ * first subscriber whose response is non-undefined wins. When no
4
+ * subscriber responds, the bus defaults to deny-once (safe default).
5
+ * An always-audited subscriber is attached automatically so every
6
+ * decision is logged regardless of which UI handled it.
7
+ */
8
+ import type { ApprovalBus } from '../kernel/types.js';
9
+ export interface ApprovalRequest {
10
+ id: string;
11
+ tool: string;
12
+ summary: string;
13
+ diff?: string;
14
+ reason?: string;
15
+ }
16
+ export type ApprovalResponse = 'approve' | 'deny' | 'approve_once' | 'deny_always';
17
+ export type ApprovalSubscriber = (req: ApprovalRequest) => Promise<ApprovalResponse | undefined>;
18
+ export interface ConfigurableApprovalBus extends ApprovalBus {
19
+ subscribe(subscriber: ApprovalSubscriber): () => void;
20
+ setRequiresApprovalPredicate(fn: (toolName: string, input: unknown) => boolean): void;
21
+ allowToolAlways(toolName: string): void;
22
+ denyToolAlways(toolName: string): void;
23
+ }
24
+ export declare function createApprovalBus(options?: {
25
+ alwaysApprove?: string[];
26
+ }): ConfigurableApprovalBus;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Approval bus. Pluggable subscribers receive ApprovalRequests; the
3
+ * first subscriber whose response is non-undefined wins. When no
4
+ * subscriber responds, the bus defaults to deny-once (safe default).
5
+ * An always-audited subscriber is attached automatically so every
6
+ * decision is logged regardless of which UI handled it.
7
+ */
8
+ export function createApprovalBus(options = {}) {
9
+ const subscribers = new Set();
10
+ const approve = new Set(options.alwaysApprove ?? []);
11
+ const deny = new Set();
12
+ let requiresApproval = (toolName, _input) => !approve.has(toolName) && !deny.has(toolName);
13
+ const bus = {
14
+ requiresApproval(toolName, _input) {
15
+ if (deny.has(toolName))
16
+ return true;
17
+ if (approve.has(toolName))
18
+ return false;
19
+ return requiresApproval(toolName, _input);
20
+ },
21
+ async request(req) {
22
+ if (deny.has(req.tool))
23
+ return 'deny_always';
24
+ if (approve.has(req.tool))
25
+ return 'approve_once';
26
+ for (const sub of subscribers) {
27
+ const response = await sub(req);
28
+ if (response !== undefined) {
29
+ if (response === 'deny_always')
30
+ deny.add(req.tool);
31
+ if (response === 'approve_once')
32
+ approve.add(req.tool);
33
+ return response;
34
+ }
35
+ }
36
+ return 'deny';
37
+ },
38
+ subscribe(subscriber) {
39
+ subscribers.add(subscriber);
40
+ return () => { subscribers.delete(subscriber); };
41
+ },
42
+ setRequiresApprovalPredicate(fn) { requiresApproval = fn; },
43
+ allowToolAlways(toolName) { approve.add(toolName); deny.delete(toolName); },
44
+ denyToolAlways(toolName) { deny.add(toolName); approve.delete(toolName); },
45
+ };
46
+ return bus;
47
+ }
48
+ //# sourceMappingURL=approval-bus.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Append-only, hash-chained audit log. Every entry is a JSON object
3
+ * carrying `prevHash` and `hash`; verify() walks the chain and detects
4
+ * tampering.
5
+ */
6
+ export type AuditKind = 'tool_call' | 'approval' | 'policy_decision' | 'error' | 'model_call' | 'session_start' | 'session_end';
7
+ export interface AuditEntry {
8
+ id: string;
9
+ ts: string;
10
+ sessionId?: string;
11
+ kind: AuditKind;
12
+ payload: unknown;
13
+ prevHash: string;
14
+ hash: string;
15
+ }
16
+ export interface AuditLog {
17
+ record(kind: AuditKind, payload: unknown, sessionId?: string): Promise<void>;
18
+ read(date?: string): Promise<AuditEntry[]>;
19
+ verify(date?: string): Promise<{
20
+ valid: boolean;
21
+ brokenAt?: string;
22
+ }>;
23
+ }
24
+ export interface AuditLogOptions {
25
+ directory?: string;
26
+ }
27
+ export declare function createAuditLog(opts?: AuditLogOptions): AuditLog;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Append-only, hash-chained audit log. Every entry is a JSON object
3
+ * carrying `prevHash` and `hash`; verify() walks the chain and detects
4
+ * tampering.
5
+ */
6
+ import { appendFile, mkdir, readFile, stat } from 'node:fs/promises';
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { join } from 'node:path';
9
+ import { homedir } from 'node:os';
10
+ export function createAuditLog(opts = {}) {
11
+ const dir = opts.directory ?? join(homedir(), '.dirgha', 'audit');
12
+ let lastHash = 'GENESIS';
13
+ return {
14
+ async record(kind, payload, sessionId) {
15
+ await ensure(dir);
16
+ const entry = {
17
+ id: randomUUID(),
18
+ ts: new Date().toISOString(),
19
+ sessionId,
20
+ kind,
21
+ payload,
22
+ prevHash: lastHash,
23
+ hash: '',
24
+ };
25
+ entry.hash = computeHash(lastHash, kind, entry.ts, sessionId, payload);
26
+ lastHash = entry.hash;
27
+ await appendFile(join(dir, fileFor()), `${JSON.stringify(entry)}\n`, 'utf8');
28
+ },
29
+ async read(date) {
30
+ const path = join(dir, fileFor(date));
31
+ const text = await readFile(path, 'utf8').catch(() => '');
32
+ const out = [];
33
+ for (const line of text.split('\n')) {
34
+ if (!line.trim())
35
+ continue;
36
+ try {
37
+ out.push(JSON.parse(line));
38
+ }
39
+ catch { /* skip */ }
40
+ }
41
+ return out;
42
+ },
43
+ async verify(date) {
44
+ const entries = await this.read(date);
45
+ let prev = 'GENESIS';
46
+ for (const entry of entries) {
47
+ const expected = computeHash(entry.prevHash, entry.kind, entry.ts, entry.sessionId, entry.payload);
48
+ if (entry.prevHash !== prev || entry.hash !== expected) {
49
+ return { valid: false, brokenAt: entry.id };
50
+ }
51
+ prev = entry.hash;
52
+ }
53
+ lastHash = prev;
54
+ return { valid: true };
55
+ },
56
+ };
57
+ }
58
+ function computeHash(prev, kind, ts, sessionId, payload) {
59
+ const body = JSON.stringify({ prev, kind, ts, sessionId, payload });
60
+ return createHash('sha256').update(body).digest('hex');
61
+ }
62
+ function fileFor(date) {
63
+ const d = date ?? new Date().toISOString().slice(0, 10);
64
+ return `${d}.ndjson`;
65
+ }
66
+ async function ensure(dir) {
67
+ const info = await stat(dir).catch(() => undefined);
68
+ if (!info)
69
+ await mkdir(dir, { recursive: true });
70
+ }
71
+ //# sourceMappingURL=audit-log.js.map
@@ -0,0 +1,4 @@
1
+ export * from './policy.js';
2
+ export * from './approval-bus.js';
3
+ export * from './audit-log.js';
4
+ export * from './sandbox/index.js';
@@ -0,0 +1,5 @@
1
+ export * from './policy.js';
2
+ export * from './approval-bus.js';
3
+ export * from './audit-log.js';
4
+ export * from './sandbox/index.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Policy engine. Evaluates a PermissionCheck against an ordered rule
3
+ * list and returns a decision (allow / deny / require_approval). The
4
+ * default ruleset ships in-code; user and project rules are merged at
5
+ * config load time.
6
+ */
7
+ import type { PermissionCheck, PermissionDecision } from '../tools/permission.js';
8
+ export interface PolicyRule {
9
+ id: string;
10
+ applies: {
11
+ tools?: string[];
12
+ actions?: PermissionCheck['action'][];
13
+ };
14
+ when?: PolicyCondition;
15
+ effect: 'allow' | 'deny' | 'require_approval';
16
+ reason: string;
17
+ }
18
+ export interface PolicyCondition {
19
+ pathMatches?: string;
20
+ commandMatches?: string;
21
+ outsideCwd?: boolean;
22
+ startsWith?: string;
23
+ }
24
+ export interface PolicyEngineOptions {
25
+ cwd: string;
26
+ rules?: PolicyRule[];
27
+ }
28
+ export interface PolicyEngine {
29
+ evaluate(req: PermissionCheck): PermissionDecision;
30
+ }
31
+ export declare const DEFAULT_RULES: PolicyRule[];
32
+ export declare function createPolicyEngine(opts: PolicyEngineOptions): PolicyEngine;