strands-darwin 0.0.3

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 (417) hide show
  1. package/README.md +140 -0
  2. package/README.zh-CN.md +140 -0
  3. package/dist/patches/@strands-agents+sdk+1.16.0.patch +1443 -0
  4. package/dist/src/agent/background-delegation.d.ts +67 -0
  5. package/dist/src/agent/background-delegation.js +159 -0
  6. package/dist/src/agent/background-delegation.js.map +1 -0
  7. package/dist/src/agent/call-stats.d.ts +118 -0
  8. package/dist/src/agent/call-stats.js +128 -0
  9. package/dist/src/agent/call-stats.js.map +1 -0
  10. package/dist/src/agent/compact.d.ts +108 -0
  11. package/dist/src/agent/compact.js +192 -0
  12. package/dist/src/agent/compact.js.map +1 -0
  13. package/dist/src/agent/context-anchor.d.ts +64 -0
  14. package/dist/src/agent/context-anchor.js +43 -0
  15. package/dist/src/agent/context-anchor.js.map +1 -0
  16. package/dist/src/agent/cost.d.ts +56 -0
  17. package/dist/src/agent/cost.js +44 -0
  18. package/dist/src/agent/cost.js.map +1 -0
  19. package/dist/src/agent/diagnostics.d.ts +212 -0
  20. package/dist/src/agent/diagnostics.js +374 -0
  21. package/dist/src/agent/diagnostics.js.map +1 -0
  22. package/dist/src/agent/instructions.d.ts +54 -0
  23. package/dist/src/agent/instructions.js +118 -0
  24. package/dist/src/agent/instructions.js.map +1 -0
  25. package/dist/src/agent/max-tokens-recovery.d.ts +17 -0
  26. package/dist/src/agent/max-tokens-recovery.js +65 -0
  27. package/dist/src/agent/max-tokens-recovery.js.map +1 -0
  28. package/dist/src/agent/model-call-budget.d.ts +8 -0
  29. package/dist/src/agent/model-call-budget.js +24 -0
  30. package/dist/src/agent/model-call-budget.js.map +1 -0
  31. package/dist/src/agent/model-retry.d.ts +134 -0
  32. package/dist/src/agent/model-retry.js +256 -0
  33. package/dist/src/agent/model-retry.js.map +1 -0
  34. package/dist/src/agent/permission-rules.d.ts +47 -0
  35. package/dist/src/agent/permission-rules.js +260 -0
  36. package/dist/src/agent/permission-rules.js.map +1 -0
  37. package/dist/src/agent/permission.d.ts +361 -0
  38. package/dist/src/agent/permission.js +797 -0
  39. package/dist/src/agent/permission.js.map +1 -0
  40. package/dist/src/agent/prompt-cache.d.ts +66 -0
  41. package/dist/src/agent/prompt-cache.js +194 -0
  42. package/dist/src/agent/prompt-cache.js.map +1 -0
  43. package/dist/src/agent/refusal.d.ts +20 -0
  44. package/dist/src/agent/refusal.js +23 -0
  45. package/dist/src/agent/refusal.js.map +1 -0
  46. package/dist/src/agent/retry-guard.d.ts +26 -0
  47. package/dist/src/agent/retry-guard.js +193 -0
  48. package/dist/src/agent/retry-guard.js.map +1 -0
  49. package/dist/src/agent/rewind.d.ts +29 -0
  50. package/dist/src/agent/rewind.js +118 -0
  51. package/dist/src/agent/rewind.js.map +1 -0
  52. package/dist/src/agent/runtime.d.ts +814 -0
  53. package/dist/src/agent/runtime.js +1596 -0
  54. package/dist/src/agent/runtime.js.map +1 -0
  55. package/dist/src/agent/safety-classifier.d.ts +11 -0
  56. package/dist/src/agent/safety-classifier.js +0 -0
  57. package/dist/src/agent/safety-classifier.js.map +1 -0
  58. package/dist/src/agent/sdk-logging.d.ts +49 -0
  59. package/dist/src/agent/sdk-logging.js +110 -0
  60. package/dist/src/agent/sdk-logging.js.map +1 -0
  61. package/dist/src/agent/session.d.ts +102 -0
  62. package/dist/src/agent/session.js +244 -0
  63. package/dist/src/agent/session.js.map +1 -0
  64. package/dist/src/agent/stream-resumption.d.ts +16 -0
  65. package/dist/src/agent/stream-resumption.js +33 -0
  66. package/dist/src/agent/stream-resumption.js.map +1 -0
  67. package/dist/src/agent/system-prompt.d.ts +50 -0
  68. package/dist/src/agent/system-prompt.js +161 -0
  69. package/dist/src/agent/system-prompt.js.map +1 -0
  70. package/dist/src/agent/thinking.d.ts +99 -0
  71. package/dist/src/agent/thinking.js +145 -0
  72. package/dist/src/agent/thinking.js.map +1 -0
  73. package/dist/src/agent/usage.d.ts +132 -0
  74. package/dist/src/agent/usage.js +233 -0
  75. package/dist/src/agent/usage.js.map +1 -0
  76. package/dist/src/agent/working-context.d.ts +51 -0
  77. package/dist/src/agent/working-context.js +160 -0
  78. package/dist/src/agent/working-context.js.map +1 -0
  79. package/dist/src/agents/child-recipe.d.ts +33 -0
  80. package/dist/src/agents/child-recipe.js +98 -0
  81. package/dist/src/agents/child-recipe.js.map +1 -0
  82. package/dist/src/agents/concurrency-limit.d.ts +25 -0
  83. package/dist/src/agents/concurrency-limit.js +43 -0
  84. package/dist/src/agents/concurrency-limit.js.map +1 -0
  85. package/dist/src/agents/dispatch-registry.d.ts +180 -0
  86. package/dist/src/agents/dispatch-registry.js +289 -0
  87. package/dist/src/agents/dispatch-registry.js.map +1 -0
  88. package/dist/src/agents/failed-child-text.d.ts +44 -0
  89. package/dist/src/agents/failed-child-text.js +69 -0
  90. package/dist/src/agents/failed-child-text.js.map +1 -0
  91. package/dist/src/agents/loader.d.ts +26 -0
  92. package/dist/src/agents/loader.js +134 -0
  93. package/dist/src/agents/loader.js.map +1 -0
  94. package/dist/src/agents/report-projection.d.ts +31 -0
  95. package/dist/src/agents/report-projection.js +125 -0
  96. package/dist/src/agents/report-projection.js.map +1 -0
  97. package/dist/src/agents/subagent-tool.d.ts +61 -0
  98. package/dist/src/agents/subagent-tool.js +180 -0
  99. package/dist/src/agents/subagent-tool.js.map +1 -0
  100. package/dist/src/agents/workflow-tool.d.ts +85 -0
  101. package/dist/src/agents/workflow-tool.js +530 -0
  102. package/dist/src/agents/workflow-tool.js.map +1 -0
  103. package/dist/src/cli-args.d.ts +39 -0
  104. package/dist/src/cli-args.js +198 -0
  105. package/dist/src/cli-args.js.map +1 -0
  106. package/dist/src/cli-doctor.d.ts +26 -0
  107. package/dist/src/cli-doctor.js +398 -0
  108. package/dist/src/cli-doctor.js.map +1 -0
  109. package/dist/src/cli-main.d.ts +1 -0
  110. package/dist/src/cli-main.js +279 -0
  111. package/dist/src/cli-main.js.map +1 -0
  112. package/dist/src/cli-sessions.d.ts +17 -0
  113. package/dist/src/cli-sessions.js +136 -0
  114. package/dist/src/cli-sessions.js.map +1 -0
  115. package/dist/src/cli-trajectory.d.ts +37 -0
  116. package/dist/src/cli-trajectory.js +303 -0
  117. package/dist/src/cli-trajectory.js.map +1 -0
  118. package/dist/src/cli-usage.d.ts +18 -0
  119. package/dist/src/cli-usage.js +53 -0
  120. package/dist/src/cli-usage.js.map +1 -0
  121. package/dist/src/cli.d.ts +2 -0
  122. package/dist/src/cli.js +29 -0
  123. package/dist/src/cli.js.map +1 -0
  124. package/dist/src/commands/custom-commands.d.ts +43 -0
  125. package/dist/src/commands/custom-commands.js +155 -0
  126. package/dist/src/commands/custom-commands.js.map +1 -0
  127. package/dist/src/commands/workflow-command.d.ts +26 -0
  128. package/dist/src/commands/workflow-command.js +56 -0
  129. package/dist/src/commands/workflow-command.js.map +1 -0
  130. package/dist/src/config.d.ts +463 -0
  131. package/dist/src/config.js +1457 -0
  132. package/dist/src/config.js.map +1 -0
  133. package/dist/src/context-overflow-error.d.ts +7 -0
  134. package/dist/src/context-overflow-error.js +26 -0
  135. package/dist/src/context-overflow-error.js.map +1 -0
  136. package/dist/src/dev-repl.d.ts +1 -0
  137. package/dist/src/dev-repl.js +365 -0
  138. package/dist/src/dev-repl.js.map +1 -0
  139. package/dist/src/headless-protocol.d.ts +147 -0
  140. package/dist/src/headless-protocol.js +359 -0
  141. package/dist/src/headless-protocol.js.map +1 -0
  142. package/dist/src/headless-runner.d.ts +30 -0
  143. package/dist/src/headless-runner.js +405 -0
  144. package/dist/src/headless-runner.js.map +1 -0
  145. package/dist/src/headless-stdin.d.ts +28 -0
  146. package/dist/src/headless-stdin.js +78 -0
  147. package/dist/src/headless-stdin.js.map +1 -0
  148. package/dist/src/headless.d.ts +106 -0
  149. package/dist/src/headless.js +229 -0
  150. package/dist/src/headless.js.map +1 -0
  151. package/dist/src/hooks/codex-hook-runner.d.ts +92 -0
  152. package/dist/src/hooks/codex-hook-runner.js +446 -0
  153. package/dist/src/hooks/codex-hook-runner.js.map +1 -0
  154. package/dist/src/hooks/codex-hooks.d.ts +23 -0
  155. package/dist/src/hooks/codex-hooks.js +152 -0
  156. package/dist/src/hooks/codex-hooks.js.map +1 -0
  157. package/dist/src/hooks/hook-process.d.ts +23 -0
  158. package/dist/src/hooks/hook-process.js +241 -0
  159. package/dist/src/hooks/hook-process.js.map +1 -0
  160. package/dist/src/hooks/lifecycle-hooks.d.ts +37 -0
  161. package/dist/src/hooks/lifecycle-hooks.js +153 -0
  162. package/dist/src/hooks/lifecycle-hooks.js.map +1 -0
  163. package/dist/src/hooks/tool-hooks.d.ts +63 -0
  164. package/dist/src/hooks/tool-hooks.js +350 -0
  165. package/dist/src/hooks/tool-hooks.js.map +1 -0
  166. package/dist/src/mcp/codegraph-preflight.d.ts +29 -0
  167. package/dist/src/mcp/codegraph-preflight.js +232 -0
  168. package/dist/src/mcp/codegraph-preflight.js.map +1 -0
  169. package/dist/src/mcp/registry.d.ts +133 -0
  170. package/dist/src/mcp/registry.js +209 -0
  171. package/dist/src/mcp/registry.js.map +1 -0
  172. package/dist/src/mcp/web-search-empty-results.d.ts +14 -0
  173. package/dist/src/mcp/web-search-empty-results.js +94 -0
  174. package/dist/src/mcp/web-search-empty-results.js.map +1 -0
  175. package/dist/src/memory/command.d.ts +11 -0
  176. package/dist/src/memory/command.js +253 -0
  177. package/dist/src/memory/command.js.map +1 -0
  178. package/dist/src/memory/controller.d.ts +51 -0
  179. package/dist/src/memory/controller.js +316 -0
  180. package/dist/src/memory/controller.js.map +1 -0
  181. package/dist/src/memory/prompt.d.ts +4 -0
  182. package/dist/src/memory/prompt.js +22 -0
  183. package/dist/src/memory/prompt.js.map +1 -0
  184. package/dist/src/memory/scheduler.d.ts +33 -0
  185. package/dist/src/memory/scheduler.js +134 -0
  186. package/dist/src/memory/scheduler.js.map +1 -0
  187. package/dist/src/memory/state.d.ts +112 -0
  188. package/dist/src/memory/state.js +355 -0
  189. package/dist/src/memory/state.js.map +1 -0
  190. package/dist/src/memory/store.d.ts +19 -0
  191. package/dist/src/memory/store.js +130 -0
  192. package/dist/src/memory/store.js.map +1 -0
  193. package/dist/src/memory/tools.d.ts +29 -0
  194. package/dist/src/memory/tools.js +22 -0
  195. package/dist/src/memory/tools.js.map +1 -0
  196. package/dist/src/memory/validation.d.ts +33 -0
  197. package/dist/src/memory/validation.js +159 -0
  198. package/dist/src/memory/validation.js.map +1 -0
  199. package/dist/src/npm-package/generate-patch.d.ts +23 -0
  200. package/dist/src/npm-package/generate-patch.js +88 -0
  201. package/dist/src/npm-package/generate-patch.js.map +1 -0
  202. package/dist/src/npm-package/patch-package-format.d.ts +43 -0
  203. package/dist/src/npm-package/patch-package-format.js +66 -0
  204. package/dist/src/npm-package/patch-package-format.js.map +1 -0
  205. package/dist/src/paths.d.ts +39 -0
  206. package/dist/src/paths.js +105 -0
  207. package/dist/src/paths.js.map +1 -0
  208. package/dist/src/pricing/cost.d.ts +182 -0
  209. package/dist/src/pricing/cost.js +215 -0
  210. package/dist/src/pricing/cost.js.map +1 -0
  211. package/dist/src/pricing/model-prices.d.ts +112 -0
  212. package/dist/src/pricing/model-prices.js +320 -0
  213. package/dist/src/pricing/model-prices.js.map +1 -0
  214. package/dist/src/sdk-patch-preflight.d.ts +23 -0
  215. package/dist/src/sdk-patch-preflight.js +71 -0
  216. package/dist/src/sdk-patch-preflight.js.map +1 -0
  217. package/dist/src/skills/builtin/commit-message/SKILL.md +45 -0
  218. package/dist/src/skills/builtin/commit-message/references/types.md +8 -0
  219. package/dist/src/skills/builtin/developer/SKILL.md +107 -0
  220. package/dist/src/skills/builtin/self-evolution-research/SKILL.md +150 -0
  221. package/dist/src/skills/builtin/self-evolution-research/scripts/roll-research-path.mjs +208 -0
  222. package/dist/src/skills/builtin/self-reflection/SKILL.md +172 -0
  223. package/dist/src/skills/builtin/self-reflection/references/reflection-template.md +90 -0
  224. package/dist/src/skills/builtin/self-reflection/scripts/locate-trajectory.mjs +175 -0
  225. package/dist/src/skills/loader.d.ts +26 -0
  226. package/dist/src/skills/loader.js +186 -0
  227. package/dist/src/skills/loader.js.map +1 -0
  228. package/dist/src/skills/plugin.d.ts +34 -0
  229. package/dist/src/skills/plugin.js +137 -0
  230. package/dist/src/skills/plugin.js.map +1 -0
  231. package/dist/src/skills/prompt.d.ts +8 -0
  232. package/dist/src/skills/prompt.js +214 -0
  233. package/dist/src/skills/prompt.js.map +1 -0
  234. package/dist/src/skills/resource-safety.d.ts +15 -0
  235. package/dist/src/skills/resource-safety.js +149 -0
  236. package/dist/src/skills/resource-safety.js.map +1 -0
  237. package/dist/src/tools/background-bash.d.ts +95 -0
  238. package/dist/src/tools/background-bash.js +639 -0
  239. package/dist/src/tools/background-bash.js.map +1 -0
  240. package/dist/src/tools/background-tail.d.ts +28 -0
  241. package/dist/src/tools/background-tail.js +75 -0
  242. package/dist/src/tools/background-tail.js.map +1 -0
  243. package/dist/src/tools/background-wait-contract.d.ts +4 -0
  244. package/dist/src/tools/background-wait-contract.js +7 -0
  245. package/dist/src/tools/background-wait-contract.js.map +1 -0
  246. package/dist/src/tools/file-editor-serial.d.ts +24 -0
  247. package/dist/src/tools/file-editor-serial.js +99 -0
  248. package/dist/src/tools/file-editor-serial.js.map +1 -0
  249. package/dist/src/tools/image-viewer.d.ts +43 -0
  250. package/dist/src/tools/image-viewer.js +256 -0
  251. package/dist/src/tools/image-viewer.js.map +1 -0
  252. package/dist/src/tools/update-plan.d.ts +30 -0
  253. package/dist/src/tools/update-plan.js +65 -0
  254. package/dist/src/tools/update-plan.js.map +1 -0
  255. package/dist/src/tools/web-fetch.d.ts +70 -0
  256. package/dist/src/tools/web-fetch.js +667 -0
  257. package/dist/src/tools/web-fetch.js.map +1 -0
  258. package/dist/src/trajectory/export.d.ts +31 -0
  259. package/dist/src/trajectory/export.js +116 -0
  260. package/dist/src/trajectory/export.js.map +1 -0
  261. package/dist/src/trajectory/fork.d.ts +19 -0
  262. package/dist/src/trajectory/fork.js +110 -0
  263. package/dist/src/trajectory/fork.js.map +1 -0
  264. package/dist/src/trajectory/memory-tool.d.ts +20 -0
  265. package/dist/src/trajectory/memory-tool.js +98 -0
  266. package/dist/src/trajectory/memory-tool.js.map +1 -0
  267. package/dist/src/trajectory/prompt-history.d.ts +62 -0
  268. package/dist/src/trajectory/prompt-history.js +256 -0
  269. package/dist/src/trajectory/prompt-history.js.map +1 -0
  270. package/dist/src/trajectory/reader.d.ts +21 -0
  271. package/dist/src/trajectory/reader.js +62 -0
  272. package/dist/src/trajectory/reader.js.map +1 -0
  273. package/dist/src/trajectory/record.d.ts +417 -0
  274. package/dist/src/trajectory/record.js +394 -0
  275. package/dist/src/trajectory/record.js.map +1 -0
  276. package/dist/src/trajectory/replay.d.ts +74 -0
  277. package/dist/src/trajectory/replay.js +285 -0
  278. package/dist/src/trajectory/replay.js.map +1 -0
  279. package/dist/src/trajectory/resume-recap.d.ts +43 -0
  280. package/dist/src/trajectory/resume-recap.js +68 -0
  281. package/dist/src/trajectory/resume-recap.js.map +1 -0
  282. package/dist/src/trajectory/search.d.ts +40 -0
  283. package/dist/src/trajectory/search.js +127 -0
  284. package/dist/src/trajectory/search.js.map +1 -0
  285. package/dist/src/trajectory/spend.d.ts +157 -0
  286. package/dist/src/trajectory/spend.js +264 -0
  287. package/dist/src/trajectory/spend.js.map +1 -0
  288. package/dist/src/trajectory/stream.d.ts +30 -0
  289. package/dist/src/trajectory/stream.js +30 -0
  290. package/dist/src/trajectory/stream.js.map +1 -0
  291. package/dist/src/trajectory/writer.d.ts +310 -0
  292. package/dist/src/trajectory/writer.js +636 -0
  293. package/dist/src/trajectory/writer.js.map +1 -0
  294. package/dist/src/tui/App.d.ts +109 -0
  295. package/dist/src/tui/App.js +2660 -0
  296. package/dist/src/tui/App.js.map +1 -0
  297. package/dist/src/tui/InputBox.d.ts +90 -0
  298. package/dist/src/tui/InputBox.js +129 -0
  299. package/dist/src/tui/InputBox.js.map +1 -0
  300. package/dist/src/tui/MarkdownText.d.ts +16 -0
  301. package/dist/src/tui/MarkdownText.js +117 -0
  302. package/dist/src/tui/MarkdownText.js.map +1 -0
  303. package/dist/src/tui/MessageList.d.ts +27 -0
  304. package/dist/src/tui/MessageList.js +61 -0
  305. package/dist/src/tui/MessageList.js.map +1 -0
  306. package/dist/src/tui/PermissionPrompt.d.ts +18 -0
  307. package/dist/src/tui/PermissionPrompt.js +114 -0
  308. package/dist/src/tui/PermissionPrompt.js.map +1 -0
  309. package/dist/src/tui/PlanChecklist.d.ts +7 -0
  310. package/dist/src/tui/PlanChecklist.js +12 -0
  311. package/dist/src/tui/PlanChecklist.js.map +1 -0
  312. package/dist/src/tui/QueuedMessages.d.ts +8 -0
  313. package/dist/src/tui/QueuedMessages.js +24 -0
  314. package/dist/src/tui/QueuedMessages.js.map +1 -0
  315. package/dist/src/tui/StartupScreen.d.ts +25 -0
  316. package/dist/src/tui/StartupScreen.js +51 -0
  317. package/dist/src/tui/StartupScreen.js.map +1 -0
  318. package/dist/src/tui/ToolCallPanel.d.ts +33 -0
  319. package/dist/src/tui/ToolCallPanel.js +112 -0
  320. package/dist/src/tui/ToolCallPanel.js.map +1 -0
  321. package/dist/src/tui/WelcomeHeader.d.ts +30 -0
  322. package/dist/src/tui/WelcomeHeader.js +69 -0
  323. package/dist/src/tui/WelcomeHeader.js.map +1 -0
  324. package/dist/src/tui/background-tool-presentation.d.ts +22 -0
  325. package/dist/src/tui/background-tool-presentation.js +209 -0
  326. package/dist/src/tui/background-tool-presentation.js.map +1 -0
  327. package/dist/src/tui/busy-suffix.d.ts +37 -0
  328. package/dist/src/tui/busy-suffix.js +39 -0
  329. package/dist/src/tui/busy-suffix.js.map +1 -0
  330. package/dist/src/tui/clipboard-image.d.ts +18 -0
  331. package/dist/src/tui/clipboard-image.js +109 -0
  332. package/dist/src/tui/clipboard-image.js.map +1 -0
  333. package/dist/src/tui/context-format.d.ts +43 -0
  334. package/dist/src/tui/context-format.js +71 -0
  335. package/dist/src/tui/context-format.js.map +1 -0
  336. package/dist/src/tui/copy-command.d.ts +68 -0
  337. package/dist/src/tui/copy-command.js +182 -0
  338. package/dist/src/tui/copy-command.js.map +1 -0
  339. package/dist/src/tui/edit-diff.d.ts +135 -0
  340. package/dist/src/tui/edit-diff.js +356 -0
  341. package/dist/src/tui/edit-diff.js.map +1 -0
  342. package/dist/src/tui/frame-budget.d.ts +351 -0
  343. package/dist/src/tui/frame-budget.js +446 -0
  344. package/dist/src/tui/frame-budget.js.map +1 -0
  345. package/dist/src/tui/help-format.d.ts +17 -0
  346. package/dist/src/tui/help-format.js +38 -0
  347. package/dist/src/tui/help-format.js.map +1 -0
  348. package/dist/src/tui/live-text.d.ts +51 -0
  349. package/dist/src/tui/live-text.js +154 -0
  350. package/dist/src/tui/live-text.js.map +1 -0
  351. package/dist/src/tui/markdown.d.ts +62 -0
  352. package/dist/src/tui/markdown.js +244 -0
  353. package/dist/src/tui/markdown.js.map +1 -0
  354. package/dist/src/tui/mcp-format.d.ts +28 -0
  355. package/dist/src/tui/mcp-format.js +67 -0
  356. package/dist/src/tui/mcp-format.js.map +1 -0
  357. package/dist/src/tui/path-completion.d.ts +119 -0
  358. package/dist/src/tui/path-completion.js +305 -0
  359. package/dist/src/tui/path-completion.js.map +1 -0
  360. package/dist/src/tui/permission-queue.d.ts +61 -0
  361. package/dist/src/tui/permission-queue.js +129 -0
  362. package/dist/src/tui/permission-queue.js.map +1 -0
  363. package/dist/src/tui/plan-format.d.ts +9 -0
  364. package/dist/src/tui/plan-format.js +30 -0
  365. package/dist/src/tui/plan-format.js.map +1 -0
  366. package/dist/src/tui/prompt-completion.d.ts +22 -0
  367. package/dist/src/tui/prompt-completion.js +46 -0
  368. package/dist/src/tui/prompt-completion.js.map +1 -0
  369. package/dist/src/tui/prompt-editor.d.ts +102 -0
  370. package/dist/src/tui/prompt-editor.js +379 -0
  371. package/dist/src/tui/prompt-editor.js.map +1 -0
  372. package/dist/src/tui/prompt-history-search.d.ts +53 -0
  373. package/dist/src/tui/prompt-history-search.js +123 -0
  374. package/dist/src/tui/prompt-history-search.js.map +1 -0
  375. package/dist/src/tui/prompt-queue.d.ts +58 -0
  376. package/dist/src/tui/prompt-queue.js +74 -0
  377. package/dist/src/tui/prompt-queue.js.map +1 -0
  378. package/dist/src/tui/prompt-recall.d.ts +74 -0
  379. package/dist/src/tui/prompt-recall.js +90 -0
  380. package/dist/src/tui/prompt-recall.js.map +1 -0
  381. package/dist/src/tui/react-environment.d.ts +11 -0
  382. package/dist/src/tui/react-environment.js +24 -0
  383. package/dist/src/tui/react-environment.js.map +1 -0
  384. package/dist/src/tui/rewind-search.d.ts +34 -0
  385. package/dist/src/tui/rewind-search.js +68 -0
  386. package/dist/src/tui/rewind-search.js.map +1 -0
  387. package/dist/src/tui/shell-command.d.ts +114 -0
  388. package/dist/src/tui/shell-command.js +310 -0
  389. package/dist/src/tui/shell-command.js.map +1 -0
  390. package/dist/src/tui/spend-advisory.d.ts +52 -0
  391. package/dist/src/tui/spend-advisory.js +64 -0
  392. package/dist/src/tui/spend-advisory.js.map +1 -0
  393. package/dist/src/tui/status-format.d.ts +120 -0
  394. package/dist/src/tui/status-format.js +192 -0
  395. package/dist/src/tui/status-format.js.map +1 -0
  396. package/dist/src/tui/subagent-format.d.ts +49 -0
  397. package/dist/src/tui/subagent-format.js +146 -0
  398. package/dist/src/tui/subagent-format.js.map +1 -0
  399. package/dist/src/tui/task-format.d.ts +29 -0
  400. package/dist/src/tui/task-format.js +87 -0
  401. package/dist/src/tui/task-format.js.map +1 -0
  402. package/dist/src/tui/terminal-bell.d.ts +20 -0
  403. package/dist/src/tui/terminal-bell.js +33 -0
  404. package/dist/src/tui/terminal-bell.js.map +1 -0
  405. package/dist/src/tui/tool-detail-presentation.d.ts +60 -0
  406. package/dist/src/tui/tool-detail-presentation.js +206 -0
  407. package/dist/src/tui/tool-detail-presentation.js.map +1 -0
  408. package/dist/src/tui/turn-state.d.ts +195 -0
  409. package/dist/src/tui/turn-state.js +548 -0
  410. package/dist/src/tui/turn-state.js.map +1 -0
  411. package/dist/src/tui/visual-language.d.ts +45 -0
  412. package/dist/src/tui/visual-language.js +57 -0
  413. package/dist/src/tui/visual-language.js.map +1 -0
  414. package/dist/src/version.d.ts +7 -0
  415. package/dist/src/version.js +38 -0
  416. package/dist/src/version.js.map +1 -0
  417. package/package.json +60 -0
@@ -0,0 +1,1457 @@
1
+ /**
2
+ * Configuration loading and model construction.
3
+ *
4
+ * Switching provider is a config-file change only — nothing else in the codebase
5
+ * names a provider.
6
+ */
7
+ import { lstat, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises';
8
+ import { mkdirSync } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { BedrockModel } from '@strands-agents/sdk';
11
+ import { isValidRule } from './agent/permission-rules.js';
12
+ import { APPROVAL_MODES, isApprovalMode } from './agent/permission.js';
13
+ import { anthropicCacheConfig, bedrockCacheConfig, planPromptCache, PROMPT_CACHE_TTLS, } from './agent/prompt-cache.js';
14
+ import { claudeThinkingFields, DEFAULT_THINKING_EFFORT, isThinkingEffort, openaiThinkingParams, planThinking, THINKING_EFFORTS, } from './agent/thinking.js';
15
+ import { decodeCodexHooks, CODEX_HOOK_EVENTS } from './hooks/codex-hooks.js';
16
+ import { darwinDir, hookExtensionRoots, userDarwinDir, userProjectDir } from './paths.js';
17
+ /** Raised for malformed or unusable configuration. Always carries a fix hint. */
18
+ export class ConfigError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = 'ConfigError';
22
+ }
23
+ }
24
+ export const PROVIDERS = ['bedrock', 'anthropic', 'openai'];
25
+ /**
26
+ * Which OpenAI API the `openai` provider speaks. Declared here rather than
27
+ * imported from the SDK's `OpenAIApi`: that module's types pull in the optional
28
+ * `openai` peer dependency, which a Bedrock-only install does not have.
29
+ */
30
+ export const OPENAI_API_MODES = ['chat', 'responses'];
31
+ export const CONFIG_FILENAME = 'config.json';
32
+ /**
33
+ * Keys that describe *which model to talk to and how*. In the array form these
34
+ * may only appear inside a `models` entry; at the root they are the single-model
35
+ * form. Listed rather than inferred because the two forms are validated by the
36
+ * same function and the error messages name the key that is in the wrong place.
37
+ *
38
+ * Exported (read-only) so `spike/verify-config.ts` can walk the documented key
39
+ * tables against the schema: with unknown keys refused, a key the docs promise
40
+ * but this list lacks would be a documented setting nobody can write.
41
+ */
42
+ export const MODEL_KEYS = [
43
+ 'provider',
44
+ 'name',
45
+ 'model',
46
+ 'region',
47
+ 'apiKeyEnv',
48
+ 'baseUrl',
49
+ 'bedrockMantle',
50
+ 'openaiApi',
51
+ 'maxTokens',
52
+ 'contextWindowLimit',
53
+ 'thinkingEffort',
54
+ 'promptCache',
55
+ 'promptCacheTtl',
56
+ 'classifierModel',
57
+ 'requestTimeoutMs',
58
+ ];
59
+ /**
60
+ * Keys that describe *the session*, not the model: they outlive a model switch
61
+ * and so always live at the root, never in a `models` entry. A permission mode
62
+ * that silently applied to one model and not another would be a security
63
+ * surprise, which is why an entry carrying one is rejected rather than ignored.
64
+ */
65
+ export const SESSION_KEYS = [
66
+ 'permissionMode',
67
+ 'hooks',
68
+ 'summaryRatio',
69
+ 'preserveRecentMessages',
70
+ 'contextWarnRatio',
71
+ 'contextOffload',
72
+ 'maxResultTokens',
73
+ 'terminalBell',
74
+ 'trajectory',
75
+ 'diagnostics',
76
+ 'memory',
77
+ 'memoryHorizonDays',
78
+ 'maxConcurrentSubagents',
79
+ 'systemPrompt',
80
+ ];
81
+ /**
82
+ * `~/.darwin/config.json`, derived and nothing else: no directory is created.
83
+ *
84
+ * The readers (`loadConfig`, the hook-layer loader, `darwin doctor`) resolve the
85
+ * path through this so that *reading* configuration never leaves a `~/.darwin`
86
+ * behind — an offline diagnostic run, or a `--help`-adjacent inspection in a
87
+ * pristine HOME, must be byte-identical before and after.
88
+ */
89
+ export function configFilePath() {
90
+ return path.join(userDarwinDir(), CONFIG_FILENAME);
91
+ }
92
+ /** `~/.darwin/config.json`, with its parent directory ensured. The optional argument remains for source compatibility. */
93
+ export function configPath(_projectRoot) {
94
+ const file = configFilePath();
95
+ // Callers historically wrote fixtures directly to this returned path.
96
+ // Ensuring the parent synchronously keeps that API usable after the move home.
97
+ // Writers (`saveThinkingEffort`, `saveEnabledModel`) and fixture-writing spikes
98
+ // use this form; readers use `configFilePath()`.
99
+ mkdirSync(path.dirname(file), { recursive: true });
100
+ return file;
101
+ }
102
+ /**
103
+ * Default ceiling on concurrently running child dispatches. Equal to the
104
+ * `workflow` tool's `MAX_WORKFLOW_NODES` so the largest permitted DAG still fits
105
+ * an idle registry; `maxConcurrentSubagents` in config overrides it.
106
+ */
107
+ export const DEFAULT_MAX_CONCURRENT_SUBAGENTS = 8;
108
+ const DEFAULTS = {
109
+ provider: 'bedrock',
110
+ model: 'global.anthropic.claude-opus-5',
111
+ maxTokens: 64_000,
112
+ summaryRatio: 0.8,
113
+ preserveRecentMessages: 10,
114
+ permissionMode: 'default',
115
+ promptCache: true,
116
+ thinkingEffort: DEFAULT_THINKING_EFFORT,
117
+ contextWarnRatio: 0.8,
118
+ contextOffload: true,
119
+ terminalBell: false,
120
+ memory: true,
121
+ memoryHorizonDays: 28,
122
+ maxConcurrentSubagents: DEFAULT_MAX_CONCURRENT_SUBAGENTS,
123
+ };
124
+ /**
125
+ * The catalogue a run starts with when there is no config file: the same entries a
126
+ * hand-written `models` array would describe, in the same order, so `/model` works
127
+ * out of the box instead of offering the one model the flat defaults imply.
128
+ *
129
+ * Two deliberate departures from a file a user would write. Region is left unset
130
+ * on the Bedrock entries — all of them are `global.` inference profiles, so
131
+ * `AWS_REGION` should still decide where a run talks, which a pinned region here
132
+ * would silently override. And the values an entry shares with {@link DEFAULTS}
133
+ * are referenced rather than restated (`requestTimeoutMs` is omitted outright, as
134
+ * {@link DEFAULT_REQUEST_TIMEOUT_MS} already supplies it): a preset that spells
135
+ * out a default is a second copy of it to keep in sync.
136
+ */
137
+ const DEFAULT_MODELS = [
138
+ {
139
+ name: 'claude-sonnet-5',
140
+ provider: 'bedrock',
141
+ model: 'global.anthropic.claude-sonnet-5',
142
+ maxTokens: DEFAULTS.maxTokens,
143
+ promptCache: DEFAULTS.promptCache,
144
+ thinkingEffort: DEFAULTS.thinkingEffort,
145
+ },
146
+ {
147
+ name: 'claude-haiku-4.5',
148
+ provider: 'bedrock',
149
+ model: 'global.anthropic.claude-haiku-4-5-20251001-v1:0',
150
+ // The cheap seat, and the one entry that is not a reasoning-first model: a
151
+ // smaller budget and less thinking is the point of reaching for it.
152
+ maxTokens: 16_000,
153
+ promptCache: DEFAULTS.promptCache,
154
+ thinkingEffort: 'medium',
155
+ },
156
+ {
157
+ name: 'claude-fable-5',
158
+ provider: 'bedrock',
159
+ model: 'global.anthropic.claude-fable-5',
160
+ maxTokens: DEFAULTS.maxTokens,
161
+ promptCache: DEFAULTS.promptCache,
162
+ thinkingEffort: DEFAULTS.thinkingEffort,
163
+ },
164
+ {
165
+ name: 'claude-fable-5.1',
166
+ provider: 'bedrock',
167
+ model: 'global.anthropic.claude-fable-5-1',
168
+ maxTokens: DEFAULTS.maxTokens,
169
+ promptCache: DEFAULTS.promptCache,
170
+ thinkingEffort: DEFAULTS.thinkingEffort,
171
+ },
172
+ {
173
+ name: 'claude-opus-5',
174
+ // The enabled entry, by construction: {@link defaultConfig} marks whichever
175
+ // entry carries DEFAULTS.model, so the flat fallbacks and the catalogue can
176
+ // never name different models.
177
+ provider: 'bedrock',
178
+ model: DEFAULTS.model,
179
+ maxTokens: DEFAULTS.maxTokens,
180
+ promptCache: DEFAULTS.promptCache,
181
+ thinkingEffort: DEFAULTS.thinkingEffort,
182
+ },
183
+ {
184
+ name: 'gpt-5.6-sol',
185
+ provider: 'openai',
186
+ model: 'openai.gpt-5.6-sol',
187
+ // Pinned, unlike the Bedrock entries: the Mantle catalog is per-region and
188
+ // this model is served in us-east-1 only, so AWS_REGION must not decide it.
189
+ // `responses` is mandatory too — the model refuses Chat Completions outright.
190
+ region: 'us-east-1',
191
+ bedrockMantle: true,
192
+ openaiApi: 'responses',
193
+ maxTokens: DEFAULTS.maxTokens,
194
+ promptCache: DEFAULTS.promptCache,
195
+ thinkingEffort: DEFAULTS.thinkingEffort,
196
+ },
197
+ ];
198
+ const DEFAULT_REGION = 'us-west-2';
199
+ /**
200
+ * Default idle timeout for one Bedrock streaming request, in milliseconds. The
201
+ * Strands SDK's own default is 120s, which long quiet stretches (deep adaptive
202
+ * thinking, a loaded endpoint) have been seen to exceed — darwin widens it to
203
+ * 180s. Per-model override: `requestTimeoutMs`.
204
+ */
205
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 180_000;
206
+ /**
207
+ * The inline preview the context offloader keeps for each offloaded result, in
208
+ * tokens — the SDK's `DEFAULT_PREVIEW_TOKENS`, mirrored here because darwin never
209
+ * overrides it and `maxResultTokens` has to clear it.
210
+ *
211
+ * Measured, not assumed: the plugin throws `previewTokens must be less than
212
+ * maxResultTokens` on `previewTokens >= maxResultTokens`, so a threshold equal to
213
+ * this value is rejected and this + 1 is the smallest usable one. Threading a
214
+ * `previewTokens` config field is deliberately out of scope: one validated
215
+ * threshold covers the need until someone asks for two.
216
+ */
217
+ export const OFFLOAD_PREVIEW_TOKENS = 1_000;
218
+ /**
219
+ * Darwin's default offload threshold, above the SDK's own 2500 on purpose.
220
+ *
221
+ * A result between 2500 and this value offloads with poor return: the
222
+ * 1000-token preview stays in context regardless, so offloading saves only the
223
+ * remainder per round, while an agent that needs the content pays one full
224
+ * retrieval round — a complete context replay — to get it back (the issue-#8
225
+ * single-small-tool round pattern). `maxResultTokens` in config still overrides
226
+ * in either direction.
227
+ */
228
+ export const DEFAULT_MAX_RESULT_TOKENS = 5_000;
229
+ /** Context windows the installed SDK knows only for unprefixed OpenAI IDs. */
230
+ const OPENAI_CONTEXT_WINDOW_LIMITS = {
231
+ 'gpt-5.6': 1_050_000,
232
+ 'gpt-5.6-sol': 1_050_000,
233
+ 'gpt-5.6-terra': 1_050_000,
234
+ 'gpt-5.6-luna': 1_050_000,
235
+ 'gpt-5.5': 1_050_000,
236
+ 'gpt-5.5-pro': 1_050_000,
237
+ 'gpt-5.4': 1_050_000,
238
+ 'gpt-5.4-pro': 1_050_000,
239
+ };
240
+ /** Mantle catalog IDs carry `openai.`; normalize it before the metadata lookup. */
241
+ export function openAIContextWindowLimit(modelId) {
242
+ const normalized = modelId.startsWith('openai.') ? modelId.slice('openai.'.length) : modelId;
243
+ return OPENAI_CONTEXT_WINDOW_LIMITS[normalized];
244
+ }
245
+ /** Bedrock rejects bare model ids; only cross-region inference profiles work. */
246
+ const BEDROCK_PROFILE_PREFIXES = ['us.', 'eu.', 'apac.', 'global.'];
247
+ export function resolveRegion(configured) {
248
+ return (configured ??
249
+ process.env['AWS_REGION'] ??
250
+ process.env['AWS_DEFAULT_REGION'] ??
251
+ DEFAULT_REGION);
252
+ }
253
+ /**
254
+ * The base URL the `anthropic` provider will talk to: `baseUrl` from the config,
255
+ * else a non-empty `ANTHROPIC_BASE_URL`, else undefined — meaning the Anthropic
256
+ * client's own default (`https://api.anthropic.com`).
257
+ *
258
+ * Resolved here rather than left to the client (which reads the same env var by
259
+ * itself) for the same reason `region` is: one place decides, so a spike can
260
+ * assert the decision without a network and a future status surface can print it.
261
+ */
262
+ export function resolveAnthropicBaseUrl(config) {
263
+ if (config.baseUrl !== undefined)
264
+ return config.baseUrl;
265
+ const fromEnv = process.env['ANTHROPIC_BASE_URL'];
266
+ return fromEnv === undefined || fromEnv === '' ? undefined : fromEnv;
267
+ }
268
+ /** Conventional env var the Anthropic client reads when no `apiKeyEnv` is set. */
269
+ const ANTHROPIC_API_KEY_ENV = 'ANTHROPIC_API_KEY';
270
+ /**
271
+ * Completes a flat config with the one-entry catalogue it implies.
272
+ *
273
+ * The single-model form and a hand-built config both describe exactly one choice,
274
+ * and deriving it here rather than writing it out keeps the catalogue from ever
275
+ * disagreeing with the fields beside it.
276
+ */
277
+ export function withSoleChoice(config) {
278
+ return {
279
+ ...config,
280
+ modelChoices: [{ index: 0, name: config.name ?? config.model, enabled: true, fields: config }],
281
+ };
282
+ }
283
+ /**
284
+ * The config a run starts with when there is no config file: {@link DEFAULTS} for
285
+ * the session half, {@link DEFAULT_MODELS} for the catalogue, and the entry naming
286
+ * `DEFAULTS.model` in effect.
287
+ *
288
+ * Built the same way {@link validate} builds the array form, so a run with no file
289
+ * and a run with a file describing these entries are the same run — the only
290
+ * difference being which one the *user* can edit.
291
+ */
292
+ function defaultConfig() {
293
+ const choices = DEFAULT_MODELS.map((fields, index) => ({
294
+ index,
295
+ name: fields.name ?? fields.model,
296
+ enabled: fields.model === DEFAULTS.model,
297
+ fields,
298
+ }));
299
+ const enabled = choices.find((choice) => choice.enabled);
300
+ // Not a ConfigError: there is no file to fix. Only a bad edit to DEFAULT_MODELS
301
+ // or DEFAULTS.model can reach here, which is why it throws rather than picking
302
+ // an entry — starting on a model nobody chose is worse than failing loudly.
303
+ if (enabled === undefined) {
304
+ throw new Error(`DEFAULT_MODELS has no entry for the default model ${DEFAULTS.model}`);
305
+ }
306
+ return { ...DEFAULTS, ...enabled.fields, modelChoices: choices };
307
+ }
308
+ /**
309
+ * Rebuilds a config around a different {@link ModelChoice}, keeping the session.
310
+ *
311
+ * Built from the session keys up rather than spread over the old config: spreading
312
+ * would leave the *previous* model's optional fields behind — a switch away from a
313
+ * Mantle entry would keep its `region` and `openaiApi`, silently configuring the
314
+ * new model with the old one's transport. That is the same leak the loader is
315
+ * tested against, so it must not reappear at switch time.
316
+ *
317
+ * The session half is copied through {@link SESSION_KEYS} so this function and the
318
+ * validator cannot disagree about which keys survive a model change.
319
+ */
320
+ export function withModelChoice(config, target) {
321
+ const session = {};
322
+ for (const key of SESSION_KEYS) {
323
+ if (config[key] !== undefined)
324
+ session[key] = config[key];
325
+ }
326
+ return {
327
+ // Safe: SESSION_KEYS are exactly the keys of SessionFields, and the required
328
+ // ones are always present on a validated AppConfig.
329
+ ...session,
330
+ ...target.fields,
331
+ modelChoices: config.modelChoices.map((choice) => ({ ...choice, enabled: choice.index === target.index })),
332
+ };
333
+ }
334
+ /**
335
+ * Loads `~/.darwin/config.json` from `projectRoot`. A missing file is normal — the
336
+ * defaults are a working Bedrock setup, with the whole {@link DEFAULT_MODELS}
337
+ * catalogue `/model` can switch between. A present but malformed file is an
338
+ * error, since silently ignoring it would hide the user's intent.
339
+ */
340
+ export async function loadConfig(projectRoot) {
341
+ // A reader: derive the path without creating `~/.darwin` (see `configFilePath`).
342
+ const file = configFilePath();
343
+ let raw;
344
+ try {
345
+ raw = await readFile(file, 'utf8');
346
+ }
347
+ catch (error) {
348
+ if (isFileNotFound(error))
349
+ return defaultConfig();
350
+ throw new ConfigError(`Could not read ${file}: ${describe(error)}`);
351
+ }
352
+ let parsed;
353
+ try {
354
+ parsed = JSON.parse(raw);
355
+ }
356
+ catch (error) {
357
+ throw new ConfigError(`${file} is not valid JSON: ${describe(error)}`);
358
+ }
359
+ // Checked here rather than in validate(): rules live in a project-keyed file
360
+ // under ~/.darwin/projects/, so only the caller's projectRoot can name the
361
+ // destination — and "move them somewhere" is not an instruction a user can act on.
362
+ if (isRecord(parsed) && parsed['permissionRules'] !== undefined) {
363
+ throw new ConfigError(`${file}: "permissionRules" are project-scoped and are never read from the global config. ` +
364
+ `Move them to ${permissionRulesPath(projectRoot)}.`);
365
+ }
366
+ const embeddedHooksActive = !(await pathExists(globalHooksPath())) && !(await hookDirectoryHasJson(userDarwinDir()));
367
+ return validate(parsed, file, embeddedHooksActive);
368
+ }
369
+ function validate(parsed, configPath, validateEmbeddedHooks = true) {
370
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
371
+ throw new ConfigError(`${configPath} must contain a JSON object.`);
372
+ }
373
+ const input = parsed;
374
+ const session = validateSessionFields(input, configPath, validateEmbeddedHooks);
375
+ // The array form is a *file* format, not a second runtime shape: the enabled
376
+ // entry is resolved here and the result is the same flat AppConfig the
377
+ // single-model form produces, so nothing downstream knows which form was used.
378
+ //
379
+ // Unknown keys are refused last: every known key has been type-checked and
380
+ // every misplaced known key already named with where it belongs, so those
381
+ // more specific messages keep precedence.
382
+ if (input['models'] === undefined) {
383
+ const fields = validateModelFields(input, configPath);
384
+ refuseUnknownKeys(input, configPath);
385
+ return withSoleChoice({ ...fields, ...session });
386
+ }
387
+ const choices = validateModelChoices(input, configPath);
388
+ refuseUnknownKeys(input, configPath);
389
+ const enabled = choices.find((choice) => choice.enabled);
390
+ return { ...enabled.fields, ...session, modelChoices: choices };
391
+ }
392
+ /** The keys a config root may carry: both halves plus the array form's container. */
393
+ const ROOT_KEYS = [...SESSION_KEYS, ...MODEL_KEYS, 'models'];
394
+ /** The keys one `models` entry may carry: the model half plus its switch. */
395
+ const ENTRY_KEYS = [...MODEL_KEYS, 'enable'];
396
+ /** Largest edit distance at which a known key is offered as "did you mean". */
397
+ const MAX_SUGGESTION_DISTANCE = 2;
398
+ /** Unknown keys named per message, so a pasted foreign file cannot flood the terminal. */
399
+ const MAX_UNKNOWN_KEYS_NAMED = 10;
400
+ /**
401
+ * Refuses every key the schema does not know, at the root and inside `models`
402
+ * entries, in one message.
403
+ *
404
+ * Refused rather than ignored: a key in neither half is never read, so
405
+ * `"thinkingEfort": "high"` would silently keep the default effort and
406
+ * `"promptCahce": false` would silently keep billing cache writes — the user
407
+ * wrote intent and got the opposite with no signal. All unknown keys are
408
+ * reported together so one fix-and-retry cycle covers the file, and the nearest
409
+ * known key is offered when one is within {@link MAX_SUGGESTION_DISTANCE}.
410
+ * There is deliberately no `$schema`/comment escape hatch: the file has one
411
+ * reader, and an accepted-but-ignored key is exactly the class this removes.
412
+ */
413
+ function refuseUnknownKeys(root, configPath) {
414
+ const unknown = [];
415
+ const collect = (record, known, where) => {
416
+ for (const key of Object.keys(record)) {
417
+ if (known.includes(key))
418
+ continue;
419
+ const suggestion = nearestKnownKey(key, known);
420
+ unknown.push(`${JSON.stringify(boundedKey(key))} ${where}` +
421
+ (suggestion === undefined ? '' : ` (did you mean ${JSON.stringify(suggestion)}?)`));
422
+ }
423
+ };
424
+ collect(root, ROOT_KEYS, 'at the top level');
425
+ const models = root['models'];
426
+ if (Array.isArray(models)) {
427
+ models.forEach((entry, index) => {
428
+ if (!isRecord(entry))
429
+ return;
430
+ const name = entry['name'];
431
+ const label = typeof name === 'string' && name !== '' ? `models[${index}] (${JSON.stringify(name)})` : `models[${index}]`;
432
+ collect(entry, ENTRY_KEYS, `in ${label}`);
433
+ });
434
+ }
435
+ if (unknown.length === 0)
436
+ return;
437
+ const named = unknown.slice(0, MAX_UNKNOWN_KEYS_NAMED);
438
+ const more = unknown.length - named.length;
439
+ throw new ConfigError(`${configPath}: unknown ${unknown.length === 1 ? 'key' : 'keys'} ${named.join(', ')}` +
440
+ `${more > 0 ? `, … and ${more} more` : ''}. ` +
441
+ `Unknown keys are refused rather than ignored, because a misspelled setting would silently ` +
442
+ `leave the default in effect — fix the spelling or remove ${unknown.length === 1 ? 'it' : 'them'}.`);
443
+ }
444
+ /** The key as the message shows it: long foreign keys are cut so the line stays readable. */
445
+ function boundedKey(key) {
446
+ const MAX = 64;
447
+ return key.length > MAX ? `${key.slice(0, MAX - 1)}…` : key;
448
+ }
449
+ /**
450
+ * The known key closest to `key` within {@link MAX_SUGGESTION_DISTANCE}, compared
451
+ * case-insensitively so `permissionmode` finds `permissionMode`. Ties go to the
452
+ * earlier key in declaration order, so the suggestion is deterministic.
453
+ */
454
+ function nearestKnownKey(key, known) {
455
+ const needle = key.toLowerCase();
456
+ let best;
457
+ for (const candidate of known) {
458
+ // Length alone rules most candidates out, which also bounds the DP below to
459
+ // strings within two characters of a known key's length.
460
+ if (Math.abs(candidate.length - needle.length) > MAX_SUGGESTION_DISTANCE)
461
+ continue;
462
+ const distance = editDistance(needle, candidate.toLowerCase());
463
+ if (distance <= MAX_SUGGESTION_DISTANCE && (best === undefined || distance < best.distance)) {
464
+ best = { key: candidate, distance };
465
+ }
466
+ }
467
+ return best?.key;
468
+ }
469
+ /**
470
+ * Optimal string alignment (restricted Damerau-Levenshtein) distance: insertions,
471
+ * deletions, substitutions and adjacent transpositions each cost one, so the
472
+ * common typos — a dropped letter (`thinkingEfort`), a swapped pair
473
+ * (`promptCahce`) — are one edit away from the key they meant.
474
+ */
475
+ function editDistance(a, b) {
476
+ const rows = a.length + 1;
477
+ const cols = b.length + 1;
478
+ const d = Array.from({ length: rows }, () => new Array(cols).fill(0));
479
+ for (let i = 0; i < rows; i++)
480
+ d[i][0] = i;
481
+ for (let j = 0; j < cols; j++)
482
+ d[0][j] = j;
483
+ for (let i = 1; i < rows; i++) {
484
+ for (let j = 1; j < cols; j++) {
485
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
486
+ let value = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
487
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
488
+ value = Math.min(value, d[i - 2][j - 2] + 1);
489
+ }
490
+ d[i][j] = value;
491
+ }
492
+ }
493
+ return d[a.length][b.length];
494
+ }
495
+ /**
496
+ * Validates every entry of a `models` array and marks the enabled one.
497
+ *
498
+ * *Every* entry, not just the enabled one: `/model` switches to a disabled entry
499
+ * without re-reading the file, so a typo in one would otherwise surface as a
500
+ * broken switch mid-session instead of a refusal to start.
501
+ */
502
+ function validateModelChoices(input, configPath) {
503
+ const entries = modelEntries(input, configPath);
504
+ const enabledIndex = selectEnabledIndex(entries, configPath);
505
+ const choices = entries.map((entry, index) => {
506
+ const fields = validateModelFields(entry, `${configPath} models[${index}]`);
507
+ return { index, name: fields.name ?? fields.model, enabled: index === enabledIndex, fields };
508
+ });
509
+ // Names address entries in `/model`, so a duplicate would make one of them
510
+ // unreachable — refused rather than silently resolved to the first match.
511
+ const seen = new Map();
512
+ for (const choice of choices) {
513
+ const key = choice.name.toLowerCase();
514
+ const first = seen.get(key);
515
+ if (first !== undefined) {
516
+ throw new ConfigError(`${configPath}: models[${first}] and models[${choice.index}] are both called ` +
517
+ `${JSON.stringify(choice.name)}. Give one of them a distinct "name".`);
518
+ }
519
+ seen.set(key, choice.index);
520
+ }
521
+ return choices;
522
+ }
523
+ /**
524
+ * Reads and structurally checks the `models` array: every entry an object, in the
525
+ * right half of the file, with a boolean `enable`. No field validation here —
526
+ * that is {@link validateModelFields}, so both file forms share it.
527
+ */
528
+ function modelEntries(root, configPath) {
529
+ const models = root['models'];
530
+ if (!Array.isArray(models)) {
531
+ throw new ConfigError(`${configPath}: "models" must be an array of model configurations, ` +
532
+ `e.g. [{ "enable": true, "provider": "bedrock", "model": "us.anthropic.claude-sonnet-4-6" }].`);
533
+ }
534
+ if (models.length === 0) {
535
+ throw new ConfigError(`${configPath}: "models" is empty — list at least one model configuration.`);
536
+ }
537
+ // Rejected rather than merged: with entries present there is no sensible
538
+ // precedence between a root-level model key and an entry's, and inventing one
539
+ // would mean the file no longer says which model is in effect.
540
+ const strays = MODEL_KEYS.filter((key) => root[key] !== undefined);
541
+ if (strays.length > 0) {
542
+ throw new ConfigError(`${configPath}: ${strays.map((key) => JSON.stringify(key)).join(', ')} ` +
543
+ `${strays.length === 1 ? 'belongs' : 'belong'} inside a "models" entry, not next to "models". ` +
544
+ `Move ${strays.length === 1 ? 'it' : 'them'} into the entry you want ${strays.length === 1 ? 'it' : 'them'} to apply to.`);
545
+ }
546
+ return models.map((entry, index) => {
547
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
548
+ throw new ConfigError(`${configPath}: models[${index}] must be a JSON object.`);
549
+ }
550
+ const record = entry;
551
+ const misplaced = SESSION_KEYS.filter((key) => record[key] !== undefined);
552
+ if (misplaced.length > 0) {
553
+ throw new ConfigError(`${configPath}: models[${index}] carries ${misplaced.map((key) => JSON.stringify(key)).join(', ')}, ` +
554
+ `which ${misplaced.length === 1 ? 'applies' : 'apply'} to the whole session, not to one model. ` +
555
+ `Move ${misplaced.length === 1 ? 'it' : 'them'} to the top level.`);
556
+ }
557
+ const enable = record['enable'];
558
+ if (enable !== undefined && typeof enable !== 'boolean') {
559
+ throw new ConfigError(`${configPath}: models[${index}]: "enable" must be true or false.`);
560
+ }
561
+ return record;
562
+ });
563
+ }
564
+ /**
565
+ * Finds the position of the one enabled entry.
566
+ *
567
+ * Exactly one, never "the first one that is enabled": a config with two models
568
+ * switched on is a mistake with a price attached, and quietly picking one would
569
+ * bill the user for a model they did not think they were using. Zero enabled is
570
+ * refused for the same reason — falling back to the built-in default would run a
571
+ * model the file does not even mention.
572
+ */
573
+ function selectEnabledIndex(entries, configPath) {
574
+ const enabled = entries.filter((entry) => entry['enable'] === true);
575
+ if (enabled.length === 0) {
576
+ throw new ConfigError(`${configPath}: no model is enabled — set "enable": true on exactly one of the ` +
577
+ `${entries.length} entries in "models" (${entries.map(labelOf).join(', ')}).`);
578
+ }
579
+ if (enabled.length > 1) {
580
+ throw new ConfigError(`${configPath}: ${enabled.length} models are enabled (${enabled.map(labelOf).join(', ')}). ` +
581
+ `Exactly one entry may have "enable": true.`);
582
+ }
583
+ return entries.indexOf(enabled[0]);
584
+ }
585
+ /** How an entry is named in an error message: its model id, else its position. */
586
+ function labelOf(entry) {
587
+ const model = entry['model'];
588
+ return typeof model === 'string' && model !== '' ? JSON.stringify(model) : '<no "model">';
589
+ }
590
+ /**
591
+ * Validates the model-scoped keys of `input`, which is either the config root
592
+ * (single-model form) or one `models` entry. Shared deliberately: the two forms
593
+ * must accept exactly the same fields, or the array form would quietly be a
594
+ * second, weaker dialect.
595
+ */
596
+ function validateModelFields(input, where) {
597
+ const provider = input['provider'] ?? DEFAULTS.provider;
598
+ if (!isProvider(provider)) {
599
+ throw new ConfigError(`${where}: unknown provider ${JSON.stringify(provider)}. Expected one of ${PROVIDERS.join(', ')}.`);
600
+ }
601
+ // Rejected rather than clamped, unlike an unsupported-but-real level: a typo is
602
+ // not intent, and silently thinking at some other depth than the file says is
603
+ // both a cost and a quality surprise.
604
+ const thinkingEffort = input['thinkingEffort'] ?? DEFAULTS.thinkingEffort;
605
+ if (!isThinkingEffort(thinkingEffort)) {
606
+ throw new ConfigError(`${where}: unknown thinkingEffort ${JSON.stringify(thinkingEffort)}. ` +
607
+ `Expected one of ${THINKING_EFFORTS.join(', ')}.`);
608
+ }
609
+ const fields = {
610
+ provider,
611
+ thinkingEffort,
612
+ model: stringField(input, 'model', where) ?? DEFAULTS.model,
613
+ maxTokens: numberField(input, 'maxTokens', where, { min: 1 }) ?? DEFAULTS.maxTokens,
614
+ promptCache: booleanField(input, 'promptCache', where) ?? DEFAULTS.promptCache,
615
+ };
616
+ // Whole tokens only: the SDK divides by it for utilization and the TUI prints it
617
+ // grouped, so a fraction would be both meaningless and ugly.
618
+ const contextWindowLimit = numberField(input, 'contextWindowLimit', where, { min: 1 });
619
+ if (contextWindowLimit !== undefined) {
620
+ if (!Number.isInteger(contextWindowLimit)) {
621
+ throw new ConfigError(`${where}: "contextWindowLimit" must be a whole number of tokens, got ${contextWindowLimit}.`);
622
+ }
623
+ fields.contextWindowLimit = contextWindowLimit;
624
+ }
625
+ // Checked rather than passed through: an unsupported TTL is only rejected once
626
+ // the first request reaches Bedrock, as an opaque ValidationException.
627
+ const promptCacheTtl = input['promptCacheTtl'];
628
+ if (promptCacheTtl !== undefined) {
629
+ if (!isPromptCacheTtl(promptCacheTtl)) {
630
+ throw new ConfigError(`${where}: unknown promptCacheTtl ${JSON.stringify(promptCacheTtl)}. ` +
631
+ `Expected one of ${PROMPT_CACHE_TTLS.join(', ')}.`);
632
+ }
633
+ fields.promptCacheTtl = promptCacheTtl;
634
+ }
635
+ const region = stringField(input, 'region', where);
636
+ if (region !== undefined)
637
+ fields.region = region;
638
+ const name = stringField(input, 'name', where);
639
+ if (name !== undefined)
640
+ fields.name = name;
641
+ const apiKeyEnv = stringField(input, 'apiKeyEnv', where);
642
+ if (apiKeyEnv !== undefined)
643
+ fields.apiKeyEnv = apiKeyEnv;
644
+ // Anthropic-only, and checked as a URL here: the client would accept any string
645
+ // and fail on the first request with a fetch error that names neither the file
646
+ // nor the key.
647
+ const baseUrl = stringField(input, 'baseUrl', where);
648
+ if (baseUrl !== undefined) {
649
+ if (provider !== 'anthropic') {
650
+ throw new ConfigError(`${where}: "baseUrl" only applies to provider "anthropic" (this one sets ${JSON.stringify(provider)}).`);
651
+ }
652
+ if (!isHttpUrl(baseUrl)) {
653
+ throw new ConfigError(`${where}: "baseUrl" must be an http: or https: URL, got ${JSON.stringify(baseUrl)}.`);
654
+ }
655
+ fields.baseUrl = baseUrl;
656
+ }
657
+ // Rejected here rather than left to the SDK, which throws the same conflict as
658
+ // a bare Error naming neither the file nor the two keys the user wrote.
659
+ const bedrockMantle = booleanField(input, 'bedrockMantle', where);
660
+ if (bedrockMantle !== undefined) {
661
+ if (bedrockMantle && provider !== 'openai') {
662
+ throw new ConfigError(`${where}: "bedrockMantle" only applies to provider "openai" (this one sets ${JSON.stringify(provider)}). ` +
663
+ `Bedrock's own models are reached with provider "bedrock".`);
664
+ }
665
+ if (bedrockMantle && apiKeyEnv !== undefined) {
666
+ throw new ConfigError(`${where}: "bedrockMantle" and "apiKeyEnv" are mutually exclusive — ` +
667
+ `Mantle mints its own bearer token from AWS credentials. Remove "apiKeyEnv".`);
668
+ }
669
+ fields.bedrockMantle = bedrockMantle;
670
+ }
671
+ const openaiApi = input['openaiApi'];
672
+ if (openaiApi !== undefined) {
673
+ if (!isOpenAIApiMode(openaiApi)) {
674
+ throw new ConfigError(`${where}: unknown openaiApi ${JSON.stringify(openaiApi)}. ` +
675
+ `Expected one of ${OPENAI_API_MODES.join(', ')}.`);
676
+ }
677
+ if (provider !== 'openai') {
678
+ throw new ConfigError(`${where}: "openaiApi" only applies to provider "openai" (this one sets ${JSON.stringify(provider)}).`);
679
+ }
680
+ fields.openaiApi = openaiApi;
681
+ }
682
+ const classifierModel = stringField(input, 'classifierModel', where);
683
+ if (classifierModel !== undefined)
684
+ fields.classifierModel = classifierModel;
685
+ // Bedrock-only, rejected elsewhere rather than ignored: the other providers'
686
+ // clients have their own timeout mechanisms this value never reaches, and a
687
+ // timeout the user believes is in effect but is not would surface exactly like
688
+ // the hang it was written to bound.
689
+ const requestTimeoutMs = numberField(input, 'requestTimeoutMs', where, { min: 1 });
690
+ if (requestTimeoutMs !== undefined) {
691
+ if (provider !== 'bedrock') {
692
+ throw new ConfigError(`${where}: "requestTimeoutMs" only applies to provider "bedrock" (this one sets ${JSON.stringify(provider)}).`);
693
+ }
694
+ fields.requestTimeoutMs = requestTimeoutMs;
695
+ }
696
+ return fields;
697
+ }
698
+ /** Validates the keys that belong to the session rather than to a model. */
699
+ function validateSessionFields(input, configPath, validateEmbeddedHooks) {
700
+ const permissionMode = input['permissionMode'] ?? DEFAULTS.permissionMode;
701
+ if (!isApprovalMode(permissionMode)) {
702
+ throw new ConfigError(`${configPath}: unknown permissionMode ${JSON.stringify(permissionMode)}. ` +
703
+ `Expected one of ${APPROVAL_MODES.join(', ')}.`);
704
+ }
705
+ const fields = {
706
+ permissionMode,
707
+ summaryRatio: numberField(input, 'summaryRatio', configPath, { min: 0, max: 1 }) ?? DEFAULTS.summaryRatio,
708
+ preserveRecentMessages: numberField(input, 'preserveRecentMessages', configPath, { min: 0 }) ??
709
+ DEFAULTS.preserveRecentMessages,
710
+ contextWarnRatio: numberField(input, 'contextWarnRatio', configPath, { min: 0, max: 1 }) ??
711
+ DEFAULTS.contextWarnRatio,
712
+ contextOffload: booleanField(input, 'contextOffload', configPath) ?? DEFAULTS.contextOffload,
713
+ terminalBell: booleanField(input, 'terminalBell', configPath) ?? DEFAULTS.terminalBell,
714
+ memoryHorizonDays: integerField(input, 'memoryHorizonDays', configPath, { min: 0, max: 365 }) ??
715
+ DEFAULTS.memoryHorizonDays,
716
+ // Positive whole number, no upper bound: the cap only refuses fan-out, and a
717
+ // user raising it deliberately is not a mistake the loader can recognize.
718
+ maxConcurrentSubagents: integerField(input, 'maxConcurrentSubagents', configPath, { min: 1 }) ??
719
+ DEFAULTS.maxConcurrentSubagents,
720
+ };
721
+ // On unless switched off. Recording changes nothing the model sees. Stored rather
722
+ // than defaulted away so `false` stays distinguishable from absent for anything
723
+ // that reports what a run is doing.
724
+ const trajectory = booleanField(input, 'trajectory', configPath);
725
+ if (trajectory !== undefined)
726
+ fields.trajectory = trajectory;
727
+ // Off unless asked for: unlike default-on oversized-result offload, the SDK's
728
+ // debug output interpolates provider payloads, so a log the user did not ask
729
+ // for could hold conversation-derived material they did not expect on disk. Stored
730
+ // rather than defaulted away so `false` stays distinguishable from absent.
731
+ const diagnostics = booleanField(input, 'diagnostics', configPath);
732
+ if (diagnostics !== undefined)
733
+ fields.diagnostics = diagnostics;
734
+ // On while its durable source is available. An explicit trajectory opt-out also
735
+ // opts out of memory when `memory` is omitted, preserving previously valid private
736
+ // configurations; an explicit request for memory without that source is still an
737
+ // actionable error rather than a silent override.
738
+ const configuredMemory = booleanField(input, 'memory', configPath);
739
+ if (configuredMemory === true && trajectory === false) {
740
+ throw new ConfigError(`${configPath}: "memory" requires trajectory recording; remove "trajectory": false or disable memory.`);
741
+ }
742
+ fields.memory = configuredMemory ?? (trajectory === false ? false : DEFAULTS.memory);
743
+ // Only meaningful with offloading on, and rejected otherwise rather than
744
+ // ignored: a threshold the user believes is in effect but is not would look
745
+ // exactly like the context bloat it was written to bound.
746
+ const maxResultTokens = numberField(input, 'maxResultTokens', configPath, { min: 1 });
747
+ if (maxResultTokens !== undefined) {
748
+ if (!fields.contextOffload) {
749
+ throw new ConfigError(`${configPath}: "maxResultTokens" only applies when "contextOffload" is true.`);
750
+ }
751
+ // The offloader keeps an inline preview out of every offloaded result and
752
+ // refuses a threshold that does not leave room for it (measured: the SDK
753
+ // throws when previewTokens >= maxResultTokens, with previewTokens
754
+ // defaulting to OFFLOAD_PREVIEW_TOKENS). Darwin never overrides the preview
755
+ // size, so the floor is fixed — caught here as a ConfigError rather than
756
+ // surfacing later as a raw constructor throw during startup.
757
+ if (maxResultTokens <= OFFLOAD_PREVIEW_TOKENS) {
758
+ throw new ConfigError(`${configPath}: "maxResultTokens" must be greater than ${OFFLOAD_PREVIEW_TOKENS} ` +
759
+ `(the inline preview kept for each offloaded result), so the smallest usable value is ` +
760
+ `${OFFLOAD_PREVIEW_TOKENS + 1}.`);
761
+ }
762
+ fields.maxResultTokens = maxResultTokens;
763
+ }
764
+ else if (fields.contextOffload) {
765
+ // Darwin's own default, deliberately above the SDK's 2500: results between
766
+ // the two thresholds offload poorly — the mandatory 1000-token preview stays
767
+ // in context anyway, so the per-round saving is small, while reading the rest
768
+ // costs a full retrieval round (one complete context replay). Raising the
769
+ // floor trades a few KB of retained context per result for fewer
770
+ // retrieve-round trips (issue #8). Resolved only when offloading is on, so
771
+ // `contextOffload: false` keeps the field absent instead of contradicting it.
772
+ fields.maxResultTokens = DEFAULT_MAX_RESULT_TOKENS;
773
+ }
774
+ // Retained as a deprecated global fallback for ~/.darwin/hooks.json. Runtime
775
+ // policy loading owns execution; carrying it here preserves /model semantics.
776
+ const hooks = input['hooks'];
777
+ if (hooks !== undefined) {
778
+ // A shadowed embedded hook is intentionally not schema-validated, but keep a
779
+ // neutral placeholder in the session shape so /model cannot reactivate the
780
+ // unchecked payload later in this runtime.
781
+ fields.hooks = validateEmbeddedHooks ? hooksField(hooks, configPath) : {};
782
+ }
783
+ // Whitespace-only would pass the non-empty check and silently leave the agent
784
+ // with no instructions at all, which nobody configures on purpose.
785
+ const systemPrompt = stringField(input, 'systemPrompt', configPath);
786
+ if (systemPrompt !== undefined) {
787
+ if (systemPrompt.trim() === '') {
788
+ throw new ConfigError(`${configPath}: "systemPrompt" must not be blank.`);
789
+ }
790
+ fields.systemPrompt = systemPrompt;
791
+ }
792
+ return fields;
793
+ }
794
+ const HOOK_EVENTS = [
795
+ 'PreToolUse',
796
+ 'PostToolUse',
797
+ 'TurnComplete',
798
+ 'PermissionRequest',
799
+ ];
800
+ function hooksField(value, configPath) {
801
+ const where = `${configPath}: "hooks"`;
802
+ if (!isRecord(value))
803
+ throw new ConfigError(`${where} must be an object.`);
804
+ for (const key of Object.keys(value)) {
805
+ if (!HOOK_EVENTS.includes(key)) {
806
+ throw new ConfigError(`${where}.${key} is not supported. Expected ${HOOK_EVENTS.join(', ')}.`);
807
+ }
808
+ }
809
+ const result = {};
810
+ for (const event of HOOK_EVENTS) {
811
+ const groups = value[event];
812
+ if (groups === undefined)
813
+ continue;
814
+ if (!Array.isArray(groups)) {
815
+ throw new ConfigError(`${where}.${event} must be an array of matcher groups.`);
816
+ }
817
+ result[event] = groups.map((group, index) => hookGroupField(group, `${where}.${event}[${index}]`));
818
+ }
819
+ return result;
820
+ }
821
+ function hookGroupField(value, where) {
822
+ if (!isRecord(value))
823
+ throw new ConfigError(`${where} must be an object.`);
824
+ for (const key of Object.keys(value)) {
825
+ if (key !== 'matcher' && key !== 'hooks') {
826
+ throw new ConfigError(`${where}.${key} is not supported. Expected matcher or hooks.`);
827
+ }
828
+ }
829
+ const matcher = value['matcher'];
830
+ if (typeof matcher !== 'string' || matcher.trim() === '') {
831
+ throw new ConfigError(`${where}.matcher must be a nonblank string.`);
832
+ }
833
+ const hooks = value['hooks'];
834
+ if (!Array.isArray(hooks) || hooks.length === 0) {
835
+ throw new ConfigError(`${where}.hooks must be a nonempty array of command hooks.`);
836
+ }
837
+ return {
838
+ matcher,
839
+ hooks: hooks.map((hook, index) => hookCommandField(hook, `${where}.hooks[${index}]`)),
840
+ };
841
+ }
842
+ function hookCommandField(value, where) {
843
+ if (!isRecord(value))
844
+ throw new ConfigError(`${where} must be an object.`);
845
+ for (const key of Object.keys(value)) {
846
+ if (key !== 'type' && key !== 'command') {
847
+ throw new ConfigError(`${where}.${key} is not supported. Expected type or command.`);
848
+ }
849
+ }
850
+ if (value['type'] !== 'command') {
851
+ throw new ConfigError(`${where}.type must be "command".`);
852
+ }
853
+ const command = value['command'];
854
+ if (typeof command !== 'string' || command.trim() === '') {
855
+ throw new ConfigError(`${where}.command must be a nonblank string.`);
856
+ }
857
+ return { type: 'command', command };
858
+ }
859
+ function isRecord(value) {
860
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
861
+ }
862
+ /**
863
+ * Validates `permissionRules`. A typo here is not harmless in either direction:
864
+ * an unparseable rule would silently never match (the user believes they are no
865
+ * longer being asked), so it is rejected like every other bad config value.
866
+ */
867
+ function allowRulesField(value, configPath) {
868
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
869
+ throw new ConfigError(`${configPath}: "permissionRules" must be an object, e.g. { "allow": ["bash:pnpm *"] }.`);
870
+ }
871
+ const allow = value['allow'];
872
+ if (allow === undefined)
873
+ return [];
874
+ if (!Array.isArray(allow)) {
875
+ throw new ConfigError(`${configPath}: "permissionRules.allow" must be an array of rule strings.`);
876
+ }
877
+ for (const entry of allow) {
878
+ if (typeof entry !== 'string' || !isValidRule(entry)) {
879
+ throw new ConfigError(`${configPath}: ${JSON.stringify(entry)} is not a permission rule. ` +
880
+ `Use "<tool>" for a whole tool or "<tool>:<pattern>" for a wildcard, ` +
881
+ `e.g. "bash:pnpm *" or "fileEditor:src/**".`);
882
+ }
883
+ }
884
+ return [...allow];
885
+ }
886
+ export const PERMISSION_RULES_FILENAME = 'permission-rules.json';
887
+ export const HOOKS_FILENAME = 'hooks.json';
888
+ export function permissionRulesPath(projectRoot) {
889
+ return path.join(userProjectDir(projectRoot), PERMISSION_RULES_FILENAME);
890
+ }
891
+ export function globalHooksPath() {
892
+ return path.join(userDarwinDir(), HOOKS_FILENAME);
893
+ }
894
+ export function projectHooksPath(projectRoot) {
895
+ return path.join(darwinDir(projectRoot), HOOKS_FILENAME);
896
+ }
897
+ /** Loads project-scoped rules and all executable hook extension layers. */
898
+ export async function loadProjectPolicy(projectRoot) {
899
+ const primaryRules = permissionRulesPath(projectRoot);
900
+ const legacyProject = path.join(darwinDir(projectRoot), CONFIG_FILENAME);
901
+ const primaryRecord = await readOptionalRecord(primaryRules);
902
+ const legacyRecord = primaryRecord === undefined ? await readOptionalRecord(legacyProject) : undefined;
903
+ const allowRules = primaryRecord === undefined
904
+ ? legacyRecord?.['permissionRules'] === undefined
905
+ ? []
906
+ : allowRulesField(legacyRecord['permissionRules'], legacyProject)
907
+ : allowRulesField(primaryRecord, primaryRules);
908
+ // Load in policy order. Besides making failure selection deterministic when
909
+ // several active files are invalid, this keeps diagnostics aligned with the
910
+ // exact Pre wrapper order stated to the user.
911
+ const loaded = [];
912
+ for (const layer of hookExtensionRoots(projectRoot)) {
913
+ loaded.push(await loadHookLayer(layer, projectRoot));
914
+ }
915
+ const active = loaded.flatMap((layer) => layer.sources);
916
+ const portable = loaded.flatMap((layer) => layer.codexSources);
917
+ const preToolUse = active.flatMap((source) => source.hooks.PreToolUse ?? []);
918
+ const postToolUse = [...active].reverse().flatMap((source) => source.hooks.PostToolUse ?? []);
919
+ const turnComplete = active.flatMap((source) => source.hooks.TurnComplete ?? []);
920
+ const permissionRequest = active.flatMap((source) => source.hooks.PermissionRequest ?? []);
921
+ const hooks = active.length === 0 ? undefined : {
922
+ ...(preToolUse.length === 0 ? {} : { PreToolUse: preToolUse }),
923
+ ...(postToolUse.length === 0 ? {} : { PostToolUse: postToolUse }),
924
+ ...(turnComplete.length === 0 ? {} : { TurnComplete: turnComplete }),
925
+ ...(permissionRequest.length === 0 ? {} : { PermissionRequest: permissionRequest }),
926
+ };
927
+ const codexHooks = portable.length === 0 ? undefined : Object.fromEntries(CODEX_HOOK_EVENTS.flatMap((event) => {
928
+ const groups = event === 'PostToolUse'
929
+ ? [...portable].reverse().flatMap((source) => source.hooks[event] ?? [])
930
+ : portable.flatMap((source) => source.hooks[event] ?? []);
931
+ return groups.length === 0 ? [] : [[event, groups]];
932
+ }));
933
+ return {
934
+ allowRules,
935
+ hooks,
936
+ codexHooks,
937
+ toolHookLayers: loaded.flatMap((layer) => [
938
+ ...layer.codexSources.map((source) => ({ dialect: 'codex', file: source.file, hooks: source.hooks })),
939
+ ...layer.sources.map((source) => ({ dialect: 'native', file: source.file, hooks: source.hooks })),
940
+ ]),
941
+ hookSources: loaded.flatMap((layer) => [
942
+ ...layer.codexSources.map((source) => source.file),
943
+ ...layer.sources.map((source) => source.file),
944
+ ]),
945
+ hookShadowNotices: loaded.flatMap((layer) => layer.notice === undefined ? [] : [layer.notice]),
946
+ legacyRules: primaryRecord === undefined && legacyRecord?.['permissionRules'] !== undefined,
947
+ };
948
+ }
949
+ async function loadHookLayer(layer, projectRoot) {
950
+ const codexSources = [];
951
+ if (layer.kind === 'agents') {
952
+ const portableFile = path.join(layer.root, HOOKS_FILENAME);
953
+ try {
954
+ const portableRecord = await readOptionalRecord(portableFile);
955
+ if (portableRecord !== undefined) {
956
+ codexSources.push({ file: portableFile, hooks: decodeCodexHooks(portableRecord, portableFile) });
957
+ }
958
+ }
959
+ catch (error) {
960
+ if (error instanceof ConfigError)
961
+ throw error;
962
+ throw new ConfigError(`${portableFile} could not be loaded: ${describe(error)}`);
963
+ }
964
+ }
965
+ const directory = path.join(layer.root, 'hooks');
966
+ let entries;
967
+ try {
968
+ entries = await readdir(directory, { withFileTypes: true });
969
+ }
970
+ catch (error) {
971
+ if (!isFileNotFound(error))
972
+ throw new ConfigError(`${directory} could not be loaded: ${describe(error)}`);
973
+ entries = [];
974
+ }
975
+ const jsonEntries = entries
976
+ .filter((entry) => path.extname(entry.name).toLowerCase() === '.json')
977
+ .sort((left, right) => left.name.localeCompare(right.name));
978
+ const sources = [];
979
+ for (const entry of jsonEntries) {
980
+ const discovered = path.join(directory, entry.name);
981
+ try {
982
+ if (!entry.isFile() && !entry.isSymbolicLink()) {
983
+ throw new Error('hook JSON entry is not a regular file or a symbolic link');
984
+ }
985
+ if (entry.isSymbolicLink()) {
986
+ const target = await realpath(discovered);
987
+ if (!(await lstat(target)).isFile())
988
+ throw new Error(`symlink target is not a regular file: ${target}`);
989
+ }
990
+ // Validate and report the configured direct-child path, not only its current
991
+ // target. This also avoids pinning a later policy read to a stale symlink.
992
+ const record = await readRequiredRecord(discovered);
993
+ sources.push({ file: discovered, hooks: hooksField(record, discovered) });
994
+ }
995
+ catch (error) {
996
+ if (error instanceof ConfigError) {
997
+ throw new ConfigError(`${discovered} could not be loaded: ${error.message}`);
998
+ }
999
+ throw new ConfigError(`${discovered} could not be loaded: ${describe(error)}`);
1000
+ }
1001
+ }
1002
+ if (layer.kind === 'agents')
1003
+ return { sources, codexSources };
1004
+ const legacyFile = layer.scope === 'global' ? globalHooksPath() : projectHooksPath(projectRoot);
1005
+ // Read-only inspection: never create `~/.darwin` on the policy path either.
1006
+ const configFile = layer.scope === 'global' ? configFilePath() : path.join(darwinDir(projectRoot), CONFIG_FILENAME);
1007
+ const legacyFileExists = await pathExists(legacyFile);
1008
+ if (sources.length > 0) {
1009
+ // Shadowed legacy input is notice-only. In particular, an invalid project
1010
+ // migration file cannot veto the authoritative directory policy. The global
1011
+ // config has already been parsed by loadConfig(), so it is safe to inspect;
1012
+ // the project migration file may be malformed and remains notice-only.
1013
+ const embeddedExists = layer.scope === 'global'
1014
+ ? (await readOptionalRecord(configFile))?.['hooks'] !== undefined
1015
+ : await readOptionalRecord(configFile)
1016
+ .then((record) => record?.['hooks'] !== undefined)
1017
+ .catch(() => false);
1018
+ const shadowed = [legacyFileExists ? legacyFile : undefined, embeddedExists ? `${configFile}: hooks` : undefined]
1019
+ .filter((value) => value !== undefined);
1020
+ return {
1021
+ sources,
1022
+ codexSources,
1023
+ ...(shadowed.length === 0 ? {} : {
1024
+ notice: { layer: `${layer.scope} .darwin`, directory, shadowed },
1025
+ }),
1026
+ };
1027
+ }
1028
+ if (legacyFileExists) {
1029
+ const record = await readRequiredRecord(legacyFile);
1030
+ return { sources: [{ file: legacyFile, hooks: hooksField(record, legacyFile) }], codexSources };
1031
+ }
1032
+ const configRecord = await readOptionalRecord(configFile);
1033
+ const embedded = hooksFromRecord(configRecord, configFile);
1034
+ return embedded === undefined
1035
+ ? { sources: [], codexSources }
1036
+ : { sources: [{ file: configFile, hooks: embedded }], codexSources };
1037
+ }
1038
+ async function readRequiredRecord(file) {
1039
+ const record = await readOptionalRecord(file);
1040
+ if (record === undefined)
1041
+ throw new ConfigError(`${file} does not exist.`);
1042
+ return record;
1043
+ }
1044
+ async function pathExists(file) {
1045
+ try {
1046
+ await lstat(file);
1047
+ return true;
1048
+ }
1049
+ catch (error) {
1050
+ if (isFileNotFound(error))
1051
+ return false;
1052
+ throw new ConfigError(`${file} could not be inspected: ${describe(error)}`);
1053
+ }
1054
+ }
1055
+ async function hookDirectoryHasJson(extensionRoot) {
1056
+ try {
1057
+ const entries = await readdir(path.join(extensionRoot, 'hooks'), { withFileTypes: true });
1058
+ // Any direct *.json entry makes the directory authoritative. loadHookLayer()
1059
+ // then validates its type/target and fails closed instead of reviving legacy
1060
+ // policy because the malformed entry happened not to be a regular file.
1061
+ return entries.some((entry) => path.extname(entry.name).toLowerCase() === '.json');
1062
+ }
1063
+ catch (error) {
1064
+ if (isFileNotFound(error))
1065
+ return false;
1066
+ throw new ConfigError(`${path.join(extensionRoot, 'hooks')} could not be loaded: ${describe(error)}`);
1067
+ }
1068
+ }
1069
+ /** Adds one project-scoped allow rule, promoting legacy rules on first write. */
1070
+ export async function appendAllowRule(projectRoot, rule) {
1071
+ if (!isValidRule(rule)) {
1072
+ throw new ConfigError(`Refusing to save ${JSON.stringify(rule)}: it is not a permission rule.`);
1073
+ }
1074
+ const policy = await loadProjectPolicy(projectRoot);
1075
+ const allow = [...policy.allowRules];
1076
+ if (!allow.includes(rule))
1077
+ allow.push(rule);
1078
+ await writeConfigRecord(permissionRulesPath(projectRoot), { allow });
1079
+ }
1080
+ /**
1081
+ * Persists a revocation: removes the given rules from the project-scoped file,
1082
+ * promoting legacy rules on first write exactly like {@link appendAllowRule}.
1083
+ *
1084
+ * Filter-only by construction — what is written is the set the loader already
1085
+ * reported as in force, minus the revoked rules. There is no path through here
1086
+ * that can add or rewrite a rule, so a bug in a caller costs at most an extra
1087
+ * prompt, never a silent widening.
1088
+ */
1089
+ export async function removeAllowRules(projectRoot, rules) {
1090
+ const policy = await loadProjectPolicy(projectRoot);
1091
+ const allow = policy.allowRules.filter((rule) => !rules.includes(rule));
1092
+ await writeConfigRecord(permissionRulesPath(projectRoot), { allow });
1093
+ }
1094
+ function hooksFromRecord(record, file) {
1095
+ return record?.['hooks'] === undefined ? undefined : hooksField(record['hooks'], file);
1096
+ }
1097
+ async function readOptionalRecord(file) {
1098
+ try {
1099
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
1100
+ if (!isRecord(parsed))
1101
+ throw new Error('top-level value must be an object');
1102
+ return parsed;
1103
+ }
1104
+ catch (error) {
1105
+ if (isFileNotFound(error))
1106
+ return undefined;
1107
+ throw new ConfigError(`${file} could not be loaded: ${describe(error)}`);
1108
+ }
1109
+ }
1110
+ /**
1111
+ * Persists `thinkingEffort` in `~/.darwin/config.json`, so a level chosen with
1112
+ * `/effort` is still in effect next session.
1113
+ *
1114
+ * In the array form the level is written into the *enabled* entry, not the root:
1115
+ * `thinkingEffort` is model-scoped, and a root-level copy would be rejected on
1116
+ * the next load as a stray model key — turning a convenience into a config that
1117
+ * refuses to start.
1118
+ *
1119
+ * Merged into the raw JSON for the same reason as {@link appendAllowRule}: writing
1120
+ * back a loaded {@link AppConfig} would freeze today's defaults into the user's
1121
+ * file and drop any key this version does not know about. The caller has already
1122
+ * applied the level to the running model, so a failed write costs the memory of
1123
+ * the choice and nothing else — which is why this throws rather than swallowing.
1124
+ */
1125
+ export async function saveThinkingEffort(projectRoot, effort) {
1126
+ if (!isThinkingEffort(effort)) {
1127
+ throw new ConfigError(`Refusing to save ${JSON.stringify(effort)}: it is not a thinking effort level.`);
1128
+ }
1129
+ const file = configPath(projectRoot);
1130
+ const { record } = await readConfigRecord(file);
1131
+ // Reuses the loader's own selection so the level cannot land on a different
1132
+ // entry than the session is running: one rule for "which model is enabled".
1133
+ const entries = record['models'] === undefined ? undefined : modelEntries(record, file);
1134
+ const target = entries === undefined ? record : entries[selectEnabledIndex(entries, file)];
1135
+ target['thinkingEffort'] = effort;
1136
+ await writeConfigRecord(file, record);
1137
+ }
1138
+ /**
1139
+ * Moves `enable: true` to the entry at `index`, switching every other entry off,
1140
+ * so a `/model` change is still in effect next session.
1141
+ *
1142
+ * Writes `false` explicitly rather than deleting the key: an entry that visibly
1143
+ * says `"enable": false` is the switch this format is built around, and a file
1144
+ * where the off entries simply lack the key reads as if they were never
1145
+ * considered.
1146
+ *
1147
+ * With no config file, `/model` is switching the built-in catalogue, so the first
1148
+ * switch materializes that catalogue as a `models` array. A present flat or empty
1149
+ * file remains explicit user configuration and is never converted implicitly.
1150
+ *
1151
+ * Raw-JSON merge and throw-don't-swallow for the same reasons as
1152
+ * {@link saveThinkingEffort}: the caller has already switched the live model, so a
1153
+ * failed write costs only the memory of the choice.
1154
+ */
1155
+ export async function saveEnabledModel(projectRoot, index) {
1156
+ const file = configPath(projectRoot);
1157
+ const { record, existed } = await readConfigRecord(file);
1158
+ if (record['models'] === undefined) {
1159
+ if (existed) {
1160
+ throw new ConfigError(`${file} configures a single model, so there is nothing to switch between. ` +
1161
+ `Move it into a "models" array to keep more than one configuration.`);
1162
+ }
1163
+ record['models'] = DEFAULT_MODELS.map((fields, choiceIndex) => ({
1164
+ ...fields,
1165
+ enable: choiceIndex === index,
1166
+ }));
1167
+ }
1168
+ const entries = modelEntries(record, file);
1169
+ const target = entries[index];
1170
+ if (target === undefined) {
1171
+ throw new ConfigError(`${file}: there is no models[${index}] to enable (${entries.length} entries).`);
1172
+ }
1173
+ for (const entry of entries)
1174
+ entry['enable'] = entry === target;
1175
+ await writeConfigRecord(file, record);
1176
+ }
1177
+ /** Writes the config file back, creating `.darwin/` when this is the first write. */
1178
+ async function writeConfigRecord(file, record) {
1179
+ await mkdir(path.dirname(file), { recursive: true });
1180
+ await writeFile(file, `${JSON.stringify(record, null, 2)}\n`, 'utf8');
1181
+ }
1182
+ /** The config file as a plain object, plus whether a user-owned file existed. */
1183
+ async function readConfigRecord(file) {
1184
+ let raw;
1185
+ try {
1186
+ raw = await readFile(file, 'utf8');
1187
+ }
1188
+ catch (error) {
1189
+ if (isFileNotFound(error))
1190
+ return { record: {}, existed: false };
1191
+ throw new ConfigError(`Could not read ${file}: ${describe(error)}`);
1192
+ }
1193
+ if (raw.trim() === '')
1194
+ return { record: {}, existed: true };
1195
+ let parsed;
1196
+ try {
1197
+ parsed = JSON.parse(raw);
1198
+ }
1199
+ catch (error) {
1200
+ throw new ConfigError(`${file} is not valid JSON: ${describe(error)}`);
1201
+ }
1202
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1203
+ throw new ConfigError(`${file} must contain a JSON object.`);
1204
+ }
1205
+ return { record: parsed, existed: true };
1206
+ }
1207
+ /**
1208
+ * Builds the SDK model for the configured provider.
1209
+ *
1210
+ * Anthropic and OpenAI live behind dynamic imports because their model modules
1211
+ * require peer dependencies (`@anthropic-ai/sdk`, `openai`) that a Bedrock-only
1212
+ * install does not have. A static import would break the default setup.
1213
+ */
1214
+ export async function createModelFromConfig(config) {
1215
+ switch (config.provider) {
1216
+ case 'bedrock':
1217
+ return createBedrockModel(config);
1218
+ case 'anthropic':
1219
+ return createAnthropicModel(config);
1220
+ case 'openai':
1221
+ return createOpenAIModel(config);
1222
+ }
1223
+ }
1224
+ function createBedrockModel(config) {
1225
+ if (!BEDROCK_PROFILE_PREFIXES.some((prefix) => config.model.startsWith(prefix))) {
1226
+ throw new ConfigError(`Bedrock model ${JSON.stringify(config.model)} is not a cross-region inference profile. ` +
1227
+ `Prefix it with one of ${BEDROCK_PROFILE_PREFIXES.join(', ')} ` +
1228
+ `(e.g. "us.anthropic.claude-sonnet-4-6"). List yours with: ` +
1229
+ `aws bedrock list-inference-profiles --region ${resolveRegion(config.region)}`);
1230
+ }
1231
+ const cacheConfig = bedrockCacheConfig(planPromptCache(config));
1232
+ const thinking = claudeThinkingFields(planThinking(config));
1233
+ return new BedrockModel({
1234
+ region: resolveRegion(config.region),
1235
+ modelId: config.model,
1236
+ maxTokens: config.maxTokens,
1237
+ ...configuredContextWindow(config),
1238
+ // `/context` and proactive context management use Bedrock's native
1239
+ // CountTokensCommand. The SDK caches unsupported/IAM failures and falls back
1240
+ // to its character heuristic, so enabling this cannot break later turns.
1241
+ useNativeTokenCount: true,
1242
+ // Idle timeout for the response stream: no bytes for this long fails the
1243
+ // request as a TimeoutError. Always passed explicitly — the SDK's own 120s
1244
+ // default has been outlived by real turns, so darwin owns the number.
1245
+ clientConfig: {
1246
+ requestHandler: { requestTimeout: config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS },
1247
+ },
1248
+ // Appends a cache point after the tool schemas and to the last user message on
1249
+ // every request. Omitted entirely when caching is off, since `strategy: 'auto'`
1250
+ // on a model that cannot cache makes the SDK warn straight to the console.
1251
+ ...(cacheConfig !== undefined && { cacheConfig }),
1252
+ // Adaptive thinking plus its effort level. The SDK drops the `thinking` key by
1253
+ // itself when a request forces tool use, which Bedrock refuses to combine with
1254
+ // thinking — so this is safe to set once for the whole session.
1255
+ ...(thinking !== undefined && { additionalRequestFields: thinking }),
1256
+ });
1257
+ }
1258
+ async function createAnthropicModel(config) {
1259
+ // Config is validated before the import: a mistake in the user's own file is
1260
+ // reported whether or not the optional peer dependency happens to be installed.
1261
+ const apiKey = readApiKey(config);
1262
+ // Without `apiKeyEnv` the client falls back to ANTHROPIC_API_KEY on its own, but
1263
+ // when that is empty too it throws a bare Error from the constructor; refusing
1264
+ // here keeps a missing credential inside the ConfigError boundary.
1265
+ if (apiKey === undefined) {
1266
+ const conventional = process.env[ANTHROPIC_API_KEY_ENV];
1267
+ if (conventional === undefined || conventional === '') {
1268
+ throw new ConfigError(`Provider "anthropic" needs an API key: set ${ANTHROPIC_API_KEY_ENV} or name another environment variable with "apiKeyEnv".`);
1269
+ }
1270
+ }
1271
+ const baseURL = resolveAnthropicBaseUrl(config);
1272
+ const { AnthropicModel } = await importProviderModule('@strands-agents/sdk/models/anthropic', 'anthropic', '@anthropic-ai/sdk');
1273
+ // `params` is merged into the request body verbatim, which is how the same two
1274
+ // adaptive-thinking fields reach the native API — it has no dedicated option.
1275
+ const thinking = claudeThinkingFields(planThinking(config));
1276
+ const cacheConfig = anthropicCacheConfig(planPromptCache(config));
1277
+ return new AnthropicModel({
1278
+ modelId: config.model,
1279
+ maxTokens: config.maxTokens,
1280
+ ...configuredContextWindow(config),
1281
+ ...(apiKey !== undefined && { apiKey }),
1282
+ // Tools, system prompt and last user message, one TTL — the same three cache
1283
+ // points Bedrock gets; omitted entirely when caching is off.
1284
+ ...(cacheConfig !== undefined && { cacheConfig }),
1285
+ // `clientConfig` is spread into the SDK's own `new Anthropic({...})`, which is
1286
+ // how a Messages-API-compatible endpoint is reached without darwin importing
1287
+ // the client package itself. Omitted entirely when nothing resolved, so the
1288
+ // default install passes exactly what it always has.
1289
+ ...(baseURL !== undefined && { clientConfig: { baseURL } }),
1290
+ ...(thinking !== undefined && { params: thinking }),
1291
+ });
1292
+ }
1293
+ async function createOpenAIModel(config) {
1294
+ const { OpenAIModel } = await importProviderModule('@strands-agents/sdk/models/openai', 'openai', 'openai');
1295
+ const api = openaiApiMode(config);
1296
+ const params = openaiThinkingParams(planThinking(config), api);
1297
+ // Mantle derives both the base URL and the credential, so it replaces the API
1298
+ // key rather than joining it — the SDK rejects being given both. The region is
1299
+ // resolved here rather than left to the SDK's own env lookup so a run cannot
1300
+ // use a different region than the rest of darwin reports: the Mantle catalog is
1301
+ // per-region (`openai.gpt-5.6-sol` is us-east-1 only) and a wrong region shows
1302
+ // up as a 404 naming the model, never the region.
1303
+ const client = config.bedrockMantle === true
1304
+ ? { bedrockMantleConfig: { region: resolveRegion(config.region) } }
1305
+ : optionalApiKey(readApiKey(config));
1306
+ // The user's window beats darwin's Mantle table, which beats the SDK's own.
1307
+ const contextWindowLimit = config.contextWindowLimit ?? openAIContextWindowLimit(config.model);
1308
+ const options = {
1309
+ modelId: config.model,
1310
+ maxTokens: config.maxTokens,
1311
+ ...(contextWindowLimit === undefined ? {} : { contextWindowLimit }),
1312
+ ...client,
1313
+ ...(params !== undefined && { params }),
1314
+ };
1315
+ // Branched on the literal rather than passing `api` through: `OpenAIModelOptions`
1316
+ // is discriminated on it, and a union-typed `api` would widen the options to the
1317
+ // point where a chat-only field on a responses config no longer fails to compile.
1318
+ return api === 'responses' ? new OpenAIModel({ api: 'responses', ...options }) : new OpenAIModel({ api: 'chat', ...options });
1319
+ }
1320
+ /** Which OpenAI API this config speaks. Chat Completions unless asked otherwise. */
1321
+ function openaiApiMode(config) {
1322
+ return config.openaiApi ?? 'chat';
1323
+ }
1324
+ /** The `apiKey` option, or nothing — each provider SDK has its own env fallback. */
1325
+ function optionalApiKey(apiKey) {
1326
+ return apiKey === undefined ? {} : { apiKey };
1327
+ }
1328
+ /**
1329
+ * The `contextWindowLimit` option, or nothing — so an absent field leaves the SDK's
1330
+ * own table lookup exactly as it was (`exactOptionalPropertyTypes` forbids passing
1331
+ * `undefined` explicitly).
1332
+ */
1333
+ function configuredContextWindow(config) {
1334
+ return config.contextWindowLimit === undefined ? {} : { contextWindowLimit: config.contextWindowLimit };
1335
+ }
1336
+ /**
1337
+ * Reconfigures a live model to think at `effort`, returning what it will actually
1338
+ * do (the level may be clamped — see `src/agent/thinking.ts`).
1339
+ *
1340
+ * Reconfiguration rather than reconstruction, because the point of `/effort` is to
1341
+ * change depth *without* losing the conversation: `Model.updateConfig()` merges
1342
+ * into the existing config, so the region, cache config and token budget the model
1343
+ * was built with all stay as they were.
1344
+ *
1345
+ * The provider switch lives here because this file is the only one that names a
1346
+ * provider; the fields themselves come from `src/agent/thinking.ts`.
1347
+ */
1348
+ export function applyThinkingEffort(model, config, effort) {
1349
+ const plan = planThinking(config, effort);
1350
+ // Both keys are provider-specific extensions of BaseModelConfig, which is all
1351
+ // the abstract `Model` exposes; the cast is safe because the provider is known.
1352
+ const updatable = model;
1353
+ switch (config.provider) {
1354
+ case 'bedrock':
1355
+ // Assigning undefined clears it: updateConfig spreads over the old config.
1356
+ updatable.updateConfig({ additionalRequestFields: claudeThinkingFields(plan) });
1357
+ break;
1358
+ case 'anthropic':
1359
+ updatable.updateConfig({ params: claudeThinkingFields(plan) });
1360
+ break;
1361
+ case 'openai':
1362
+ updatable.updateConfig({ params: openaiThinkingParams(plan, openaiApiMode(config)) });
1363
+ break;
1364
+ }
1365
+ return plan;
1366
+ }
1367
+ /** Turns a missing peer dependency into an actionable install instruction. */
1368
+ async function importProviderModule(specifier, provider, peerDep) {
1369
+ try {
1370
+ return (await import(specifier));
1371
+ }
1372
+ catch (error) {
1373
+ throw new ConfigError(`Provider "${provider}" needs the ${peerDep} package, which is not installed. ` +
1374
+ `Run: pnpm add ${peerDep}\nUnderlying error: ${describe(error)}`);
1375
+ }
1376
+ }
1377
+ /**
1378
+ * Reads the API key from the env var named by `apiKeyEnv`. Returning undefined
1379
+ * is fine — each provider SDK falls back to its own conventional env var.
1380
+ */
1381
+ function readApiKey(config) {
1382
+ if (config.apiKeyEnv === undefined)
1383
+ return undefined;
1384
+ const value = process.env[config.apiKeyEnv];
1385
+ if (value === undefined || value === '') {
1386
+ throw new ConfigError(`Config sets apiKeyEnv to ${JSON.stringify(config.apiKeyEnv)} but that environment variable is empty.`);
1387
+ }
1388
+ return value;
1389
+ }
1390
+ function isHttpUrl(value) {
1391
+ try {
1392
+ const { protocol } = new URL(value);
1393
+ return protocol === 'http:' || protocol === 'https:';
1394
+ }
1395
+ catch {
1396
+ return false;
1397
+ }
1398
+ }
1399
+ function isProvider(value) {
1400
+ return typeof value === 'string' && PROVIDERS.includes(value);
1401
+ }
1402
+ function isOpenAIApiMode(value) {
1403
+ return typeof value === 'string' && OPENAI_API_MODES.includes(value);
1404
+ }
1405
+ function isPromptCacheTtl(value) {
1406
+ return typeof value === 'string' && PROMPT_CACHE_TTLS.includes(value);
1407
+ }
1408
+ function booleanField(input, key, configPath) {
1409
+ const value = input[key];
1410
+ if (value === undefined)
1411
+ return undefined;
1412
+ if (typeof value !== 'boolean') {
1413
+ throw new ConfigError(`${configPath}: "${key}" must be true or false.`);
1414
+ }
1415
+ return value;
1416
+ }
1417
+ function stringField(input, key, configPath) {
1418
+ const value = input[key];
1419
+ if (value === undefined)
1420
+ return undefined;
1421
+ if (typeof value !== 'string' || value === '') {
1422
+ throw new ConfigError(`${configPath}: "${key}" must be a non-empty string.`);
1423
+ }
1424
+ return value;
1425
+ }
1426
+ /**
1427
+ * Range is checked here rather than left to the provider: an out-of-range value
1428
+ * either fails much later as an opaque service error (`maxTokens: 0`) or quietly
1429
+ * misbehaves (a `summaryRatio` above 1 summarizes more messages than exist).
1430
+ */
1431
+ function numberField(input, key, configPath, range) {
1432
+ const value = input[key];
1433
+ if (value === undefined)
1434
+ return undefined;
1435
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
1436
+ throw new ConfigError(`${configPath}: "${key}" must be a finite number.`);
1437
+ }
1438
+ if (value < range.min || (range.max !== undefined && value > range.max)) {
1439
+ const bounds = range.max === undefined ? `at least ${range.min}` : `between ${range.min} and ${range.max}`;
1440
+ throw new ConfigError(`${configPath}: "${key}" must be ${bounds}, got ${value}.`);
1441
+ }
1442
+ return value;
1443
+ }
1444
+ function integerField(input, key, configPath, range) {
1445
+ const value = numberField(input, key, configPath, range);
1446
+ if (value !== undefined && !Number.isSafeInteger(value)) {
1447
+ throw new ConfigError(`${configPath}: "${key}" must be a whole number.`);
1448
+ }
1449
+ return value;
1450
+ }
1451
+ function isFileNotFound(error) {
1452
+ return typeof error === 'object' && error !== null && error.code === 'ENOENT';
1453
+ }
1454
+ function describe(error) {
1455
+ return error instanceof Error ? error.message : String(error);
1456
+ }
1457
+ //# sourceMappingURL=config.js.map