@bastani/atomic 0.9.21-alpha.1 → 0.9.21

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 (516) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/CHANGELOG.md +22 -0
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/subagents/src/extension/index.bundle.mjs +292 -60
  7. package/dist/builtin/web-access/package.json +1 -1
  8. package/dist/builtin/workflows/CHANGELOG.md +23 -0
  9. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  10. package/dist/builtin/workflows/builtin/{chunk-cw86srkf.js → chunk-632fxeb8.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-w18kbz63.js → chunk-94f8zfz1.js} +1 -1
  12. package/dist/builtin/workflows/builtin/{chunk-kspvwc24.js → chunk-9cm2ckq2.js} +1 -1
  13. package/dist/builtin/workflows/builtin/{chunk-jaj27rqc.js → chunk-a1ar035d.js} +1 -1
  14. package/dist/builtin/workflows/builtin/{chunk-wh19f5ee.js → chunk-d3xhj946.js} +5 -4
  15. package/dist/builtin/workflows/builtin/{chunk-crw7q5g1.js → chunk-gyjck9z8.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-maqv731g.js → chunk-hj8mh07f.js} +10 -6
  17. package/dist/builtin/workflows/builtin/{chunk-0nrgfbag.js → chunk-kb7s3gx2.js} +1 -1
  18. package/dist/builtin/workflows/builtin/{chunk-73c5tayt.js → chunk-kgn5wz1c.js} +19 -1
  19. package/dist/builtin/workflows/builtin/{chunk-2hak3b7g.js → chunk-nkj4qhj6.js} +1 -1
  20. package/dist/builtin/workflows/builtin/{chunk-bzdvx2xr.js → chunk-r97ndfvt.js} +1 -1
  21. package/dist/builtin/workflows/builtin/{chunk-vkmpdat4.js → chunk-wf876n16.js} +1 -1
  22. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  23. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  24. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  25. package/dist/builtin/workflows/builtin/goal.js +4 -4
  26. package/dist/builtin/workflows/builtin/index.js +12 -12
  27. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  28. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  29. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  30. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  31. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  32. package/dist/builtin/workflows/package.json +1 -1
  33. package/dist/builtin/workflows/src/extension/index.bundle.mjs +40 -11
  34. package/dist/builtin/workflows/src/index.js +9 -3
  35. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +6 -1
  36. package/dist/cli/auth-command.js +5 -0
  37. package/dist/cli/auth-command.js.map +1 -1
  38. package/dist/cli/credential-print.js +2 -0
  39. package/dist/cli/credential-print.js.map +1 -1
  40. package/dist/cli/experimental/command.js +5 -2
  41. package/dist/cli/experimental/command.js.map +1 -1
  42. package/dist/cli.js +1 -1
  43. package/dist/cli.js.map +1 -1
  44. package/dist/config.d.ts +4 -4
  45. package/dist/config.js +4 -4
  46. package/dist/config.js.map +1 -1
  47. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  48. package/dist/core/agent-session-extension-bindings.js +9 -4
  49. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  50. package/dist/core/agent-session-methods.d.ts +4 -4
  51. package/dist/core/agent-session-methods.d.ts.map +1 -1
  52. package/dist/core/agent-session-methods.js.map +1 -1
  53. package/dist/core/agent-session-prompt.d.ts +4 -4
  54. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  55. package/dist/core/agent-session-prompt.js +38 -15
  56. package/dist/core/agent-session-prompt.js.map +1 -1
  57. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  58. package/dist/core/agent-session-runtime.js +14 -9
  59. package/dist/core/agent-session-runtime.js.map +1 -1
  60. package/dist/core/agent-session-types.d.ts +4 -1
  61. package/dist/core/agent-session-types.d.ts.map +1 -1
  62. package/dist/core/agent-session-types.js.map +1 -1
  63. package/dist/core/agent-session.d.ts +1 -1
  64. package/dist/core/agent-session.d.ts.map +1 -1
  65. package/dist/core/agent-session.js +140 -95
  66. package/dist/core/agent-session.js.map +1 -1
  67. package/dist/core/auth-storage-backends.js +2 -3
  68. package/dist/core/auth-storage-backends.js.map +1 -1
  69. package/dist/core/auth-storage.js +4 -1
  70. package/dist/core/auth-storage.js.map +1 -1
  71. package/dist/core/builtin-resource-loader.js +9 -0
  72. package/dist/core/builtin-resource-loader.js.map +1 -1
  73. package/dist/core/cache-warmer.js +8 -1
  74. package/dist/core/cache-warmer.js.map +1 -1
  75. package/dist/core/compaction/range-planner.js +6 -0
  76. package/dist/core/compaction/range-planner.js.map +1 -1
  77. package/dist/core/execution-model-router.d.ts +13 -3
  78. package/dist/core/execution-model-router.d.ts.map +1 -1
  79. package/dist/core/execution-model-router.js +227 -131
  80. package/dist/core/execution-model-router.js.map +1 -1
  81. package/dist/core/export-html/template-js/entries-navigation.js +16 -6
  82. package/dist/core/export-html/template-js/initialization.js +34 -11
  83. package/dist/core/export-html/template.css +10 -0
  84. package/dist/core/export-html/template.js +50 -17
  85. package/dist/core/extensions/context-types.d.ts +2 -0
  86. package/dist/core/extensions/context-types.d.ts.map +1 -1
  87. package/dist/core/extensions/context-types.js.map +1 -1
  88. package/dist/core/extensions/host-input.js +8 -4
  89. package/dist/core/extensions/host-input.js.map +1 -1
  90. package/dist/core/extensions/reactive-widget.js +1 -0
  91. package/dist/core/extensions/reactive-widget.js.map +1 -1
  92. package/dist/core/extensions/runner-context.d.ts +1 -0
  93. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  94. package/dist/core/extensions/runner-context.js +4 -0
  95. package/dist/core/extensions/runner-context.js.map +1 -1
  96. package/dist/core/extensions/runner.d.ts +1 -0
  97. package/dist/core/extensions/runner.d.ts.map +1 -1
  98. package/dist/core/extensions/runner.js +48 -30
  99. package/dist/core/extensions/runner.js.map +1 -1
  100. package/dist/core/extensions/runtime-types.d.ts +1 -0
  101. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  102. package/dist/core/extensions/runtime-types.js.map +1 -1
  103. package/dist/core/extensions/workflow-activity-hub.js +9 -7
  104. package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
  105. package/dist/core/footer-data-provider.js +24 -23
  106. package/dist/core/footer-data-provider.js.map +1 -1
  107. package/dist/core/keybindings.js +1 -0
  108. package/dist/core/keybindings.js.map +1 -1
  109. package/dist/core/mandatory-resource-loader.js +4 -1
  110. package/dist/core/mandatory-resource-loader.js.map +1 -1
  111. package/dist/core/model-config.js +2 -0
  112. package/dist/core/model-config.js.map +1 -1
  113. package/dist/core/model-registry.js +1 -0
  114. package/dist/core/model-registry.js.map +1 -1
  115. package/dist/core/model-resolver-defaults.js +1 -1
  116. package/dist/core/model-resolver-defaults.js.map +1 -1
  117. package/dist/core/{model-routing-task.d.ts → model-routing-bytes.d.ts} +1 -4
  118. package/dist/core/model-routing-bytes.d.ts.map +1 -0
  119. package/dist/core/model-routing-bytes.js +33 -0
  120. package/dist/core/model-routing-bytes.js.map +1 -0
  121. package/dist/core/model-routing-candidates.d.ts +42 -0
  122. package/dist/core/model-routing-candidates.d.ts.map +1 -0
  123. package/dist/core/model-routing-candidates.js +309 -0
  124. package/dist/core/model-routing-candidates.js.map +1 -0
  125. package/dist/core/model-routing-constraints.d.ts +4 -0
  126. package/dist/core/model-routing-constraints.d.ts.map +1 -1
  127. package/dist/core/model-routing-constraints.js +13 -1
  128. package/dist/core/model-routing-constraints.js.map +1 -1
  129. package/dist/core/model-routing-debug.d.ts +9 -0
  130. package/dist/core/model-routing-debug.d.ts.map +1 -0
  131. package/dist/core/model-routing-debug.js +14 -0
  132. package/dist/core/model-routing-debug.js.map +1 -0
  133. package/dist/core/model-routing-evals.d.ts +50 -0
  134. package/dist/core/model-routing-evals.d.ts.map +1 -0
  135. package/dist/core/model-routing-evals.js +190 -0
  136. package/dist/core/model-routing-evals.js.map +1 -0
  137. package/dist/core/model-routing-needs.d.ts +75 -0
  138. package/dist/core/model-routing-needs.d.ts.map +1 -0
  139. package/dist/core/model-routing-needs.js +176 -0
  140. package/dist/core/model-routing-needs.js.map +1 -0
  141. package/dist/core/model-runtime-streaming.js +3 -0
  142. package/dist/core/model-runtime-streaming.js.map +1 -1
  143. package/dist/core/model-runtime.js +26 -14
  144. package/dist/core/model-runtime.js.map +1 -1
  145. package/dist/core/models-store.js +2 -3
  146. package/dist/core/models-store.js.map +1 -1
  147. package/dist/core/output-guard.js +1 -0
  148. package/dist/core/output-guard.js.map +1 -1
  149. package/dist/core/package-manager-paths.d.ts +2 -1
  150. package/dist/core/package-manager-paths.d.ts.map +1 -1
  151. package/dist/core/package-manager-paths.js +4 -3
  152. package/dist/core/package-manager-paths.js.map +1 -1
  153. package/dist/core/package-manager.js +1 -0
  154. package/dist/core/package-manager.js.map +1 -1
  155. package/dist/core/resource-loader-assets.d.ts.map +1 -1
  156. package/dist/core/resource-loader-assets.js +9 -7
  157. package/dist/core/resource-loader-assets.js.map +1 -1
  158. package/dist/core/resource-loader-core.js +49 -0
  159. package/dist/core/resource-loader-core.js.map +1 -1
  160. package/dist/core/runtime-credentials.js +2 -1
  161. package/dist/core/runtime-credentials.js.map +1 -1
  162. package/dist/core/session-cwd.js +1 -0
  163. package/dist/core/session-cwd.js.map +1 -1
  164. package/dist/core/session-manager-archive.d.ts.map +1 -1
  165. package/dist/core/session-manager-archive.js +4 -2
  166. package/dist/core/session-manager-archive.js.map +1 -1
  167. package/dist/core/session-manager-core.js +11 -7
  168. package/dist/core/session-manager-core.js.map +1 -1
  169. package/dist/core/session-manager-storage.d.ts +10 -4
  170. package/dist/core/session-manager-storage.d.ts.map +1 -1
  171. package/dist/core/session-manager-storage.js +12 -6
  172. package/dist/core/session-manager-storage.js.map +1 -1
  173. package/dist/core/settings-manager-basic-accessors.d.ts +2 -1
  174. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  175. package/dist/core/settings-manager-basic-accessors.js +21 -0
  176. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  177. package/dist/core/settings-manager-core.js +13 -7
  178. package/dist/core/settings-manager-core.js.map +1 -1
  179. package/dist/core/settings-manager.d.ts +1 -1
  180. package/dist/core/settings-manager.d.ts.map +1 -1
  181. package/dist/core/settings-manager.js.map +1 -1
  182. package/dist/core/settings-storage.js +6 -0
  183. package/dist/core/settings-storage.js.map +1 -1
  184. package/dist/core/settings-types.d.ts +8 -0
  185. package/dist/core/settings-types.d.ts.map +1 -1
  186. package/dist/core/settings-types.js.map +1 -1
  187. package/dist/core/structured-output/index.d.ts.map +1 -1
  188. package/dist/core/structured-output/index.js +4 -1
  189. package/dist/core/structured-output/index.js.map +1 -1
  190. package/dist/core/structured-output/invalid-output.js +1 -0
  191. package/dist/core/structured-output/invalid-output.js.map +1 -1
  192. package/dist/core/tasks/agent-adapter.js +5 -3
  193. package/dist/core/tasks/agent-adapter.js.map +1 -1
  194. package/dist/core/tasks/child-command-owner.js +3 -7
  195. package/dist/core/tasks/child-command-owner.js.map +1 -1
  196. package/dist/core/tasks/completion.js +5 -1
  197. package/dist/core/tasks/completion.js.map +1 -1
  198. package/dist/core/tasks/owner-store.js +12 -8
  199. package/dist/core/tasks/owner-store.js.map +1 -1
  200. package/dist/core/tasks/supervisor.js +14 -35
  201. package/dist/core/tasks/supervisor.js.map +1 -1
  202. package/dist/core/tools/ask-user-question/state/build-questionnaire.js +13 -4
  203. package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -1
  204. package/dist/core/tools/ask-user-question/state/questionnaire-session.js +11 -1
  205. package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -1
  206. package/dist/core/tools/ask-user-question/view/components/chat-row-view.js +1 -0
  207. package/dist/core/tools/ask-user-question/view/components/chat-row-view.js.map +1 -1
  208. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js +1 -0
  209. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -1
  210. package/dist/core/tools/ask-user-question/view/components/option-list-view.js +1 -0
  211. package/dist/core/tools/ask-user-question/view/components/option-list-view.js.map +1 -1
  212. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js +5 -0
  213. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js.map +1 -1
  214. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js +2 -0
  215. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -1
  216. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js +13 -8
  217. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js.map +1 -1
  218. package/dist/core/tools/ask-user-question/view/components/submit-picker.js +1 -0
  219. package/dist/core/tools/ask-user-question/view/components/submit-picker.js.map +1 -1
  220. package/dist/core/tools/ask-user-question/view/components/tab-bar.js +1 -0
  221. package/dist/core/tools/ask-user-question/view/components/tab-bar.js.map +1 -1
  222. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js +30 -24
  223. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js.map +1 -1
  224. package/dist/core/tools/ask-user-question/view/dialog-builder.js +5 -0
  225. package/dist/core/tools/ask-user-question/view/dialog-builder.js.map +1 -1
  226. package/dist/core/tools/ask-user-question/view/props-adapter.js +8 -0
  227. package/dist/core/tools/ask-user-question/view/props-adapter.js.map +1 -1
  228. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js +4 -4
  229. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -1
  230. package/dist/core/tools/bash.js +5 -8
  231. package/dist/core/tools/bash.js.map +1 -1
  232. package/dist/core/tools/edit-batch.js +4 -0
  233. package/dist/core/tools/edit-batch.js.map +1 -1
  234. package/dist/core/tools/edit.js +2 -0
  235. package/dist/core/tools/edit.js.map +1 -1
  236. package/dist/core/tools/file-mutation-coordinator.js +9 -0
  237. package/dist/core/tools/file-mutation-coordinator.js.map +1 -1
  238. package/dist/core/tools/find.js +1 -1
  239. package/dist/core/tools/find.js.map +1 -1
  240. package/dist/core/tools/hashline-engine/fs.js +1 -1
  241. package/dist/core/tools/hashline-engine/fs.js.map +1 -1
  242. package/dist/core/tools/hashline-engine/input.js +4 -0
  243. package/dist/core/tools/hashline-engine/input.js.map +1 -1
  244. package/dist/core/tools/hashline-engine/mismatch.js +6 -0
  245. package/dist/core/tools/hashline-engine/mismatch.js.map +1 -1
  246. package/dist/core/tools/hashline-engine/patcher.js +13 -0
  247. package/dist/core/tools/hashline-engine/patcher.js.map +1 -1
  248. package/dist/core/tools/hashline-engine/recovery.js +1 -0
  249. package/dist/core/tools/hashline-engine/recovery.js.map +1 -1
  250. package/dist/core/tools/output-accumulator.js +20 -13
  251. package/dist/core/tools/output-accumulator.js.map +1 -1
  252. package/dist/core/tools/persisted-output-file.js +9 -3
  253. package/dist/core/tools/persisted-output-file.js.map +1 -1
  254. package/dist/core/tools/resource-selectors.js +1 -0
  255. package/dist/core/tools/resource-selectors.js.map +1 -1
  256. package/dist/core/tools/write.js +1 -0
  257. package/dist/core/tools/write.js.map +1 -1
  258. package/dist/core/trust-manager.js +1 -0
  259. package/dist/core/trust-manager.js.map +1 -1
  260. package/dist/core/workflow-stage-admission.js +17 -10
  261. package/dist/core/workflow-stage-admission.js.map +1 -1
  262. package/dist/extensions/llama/client.js +2 -0
  263. package/dist/extensions/llama/client.js.map +1 -1
  264. package/dist/extensions/llama/huggingface-ui.js +17 -9
  265. package/dist/extensions/llama/huggingface-ui.js.map +1 -1
  266. package/dist/extensions/llama/huggingface.js +2 -0
  267. package/dist/extensions/llama/huggingface.js.map +1 -1
  268. package/dist/extensions/llama/ui.js +11 -3
  269. package/dist/extensions/llama/ui.js.map +1 -1
  270. package/dist/index.d.ts +4 -2
  271. package/dist/index.d.ts.map +1 -1
  272. package/dist/index.js +3 -1
  273. package/dist/index.js.map +1 -1
  274. package/dist/modes/interactive/components/armin.js +10 -6
  275. package/dist/modes/interactive/components/armin.js.map +1 -1
  276. package/dist/modes/interactive/components/assistant-message.js +10 -2
  277. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  278. package/dist/modes/interactive/components/atomic-working-status.js +10 -2
  279. package/dist/modes/interactive/components/atomic-working-status.js.map +1 -1
  280. package/dist/modes/interactive/components/bash-execution.js +9 -4
  281. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  282. package/dist/modes/interactive/components/bordered-loader.js +3 -0
  283. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  284. package/dist/modes/interactive/components/branch-summary-message.js +4 -1
  285. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  286. package/dist/modes/interactive/components/chat-message-renderer.js +2 -1
  287. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  288. package/dist/modes/interactive/components/chat-session-host-state.js +63 -31
  289. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  290. package/dist/modes/interactive/components/chat-session-host.js +8 -1
  291. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  292. package/dist/modes/interactive/components/chat-transcript.js +24 -14
  293. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  294. package/dist/modes/interactive/components/compaction-boundary-message.js +2 -1
  295. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  296. package/dist/modes/interactive/components/config-selector-list.js +15 -6
  297. package/dist/modes/interactive/components/config-selector-list.js.map +1 -1
  298. package/dist/modes/interactive/components/config-selector.js +7 -1
  299. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  300. package/dist/modes/interactive/components/countdown-timer.js +2 -0
  301. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  302. package/dist/modes/interactive/components/custom-editor.js +21 -1
  303. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  304. package/dist/modes/interactive/components/custom-entry.js +4 -1
  305. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  306. package/dist/modes/interactive/components/custom-message.js +9 -1
  307. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  308. package/dist/modes/interactive/components/daxnuts.js +8 -6
  309. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  310. package/dist/modes/interactive/components/dynamic-border.js +1 -0
  311. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  312. package/dist/modes/interactive/components/extension-editor.js +7 -1
  313. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  314. package/dist/modes/interactive/components/extension-input.js +8 -2
  315. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  316. package/dist/modes/interactive/components/extension-selector.js +9 -1
  317. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  318. package/dist/modes/interactive/components/first-time-setup.js +4 -2
  319. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  320. package/dist/modes/interactive/components/footer.js +5 -2
  321. package/dist/modes/interactive/components/footer.js.map +1 -1
  322. package/dist/modes/interactive/components/host-input-form.js +13 -2
  323. package/dist/modes/interactive/components/host-input-form.js.map +1 -1
  324. package/dist/modes/interactive/components/login-dialog.js +9 -3
  325. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  326. package/dist/modes/interactive/components/model-selector.js +24 -12
  327. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  328. package/dist/modes/interactive/components/oauth-selector.js +12 -3
  329. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  330. package/dist/modes/interactive/components/reserved-bottom-overlay.js +11 -2
  331. package/dist/modes/interactive/components/reserved-bottom-overlay.js.map +1 -1
  332. package/dist/modes/interactive/components/scoped-models-selector.js +13 -8
  333. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  334. package/dist/modes/interactive/components/scroll-widget.js +4 -0
  335. package/dist/modes/interactive/components/scroll-widget.js.map +1 -1
  336. package/dist/modes/interactive/components/session-selector-header.js +11 -7
  337. package/dist/modes/interactive/components/session-selector-header.js.map +1 -1
  338. package/dist/modes/interactive/components/session-selector-list.js +25 -12
  339. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  340. package/dist/modes/interactive/components/session-selector.js +23 -15
  341. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  342. package/dist/modes/interactive/components/settings-selector-submenus.js +19 -1
  343. package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
  344. package/dist/modes/interactive/components/settings-selector.js +1 -0
  345. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  346. package/dist/modes/interactive/components/show-images-selector.js +1 -0
  347. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  348. package/dist/modes/interactive/components/skill-invocation-message.js +4 -1
  349. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  350. package/dist/modes/interactive/components/startup-identity.js +8 -3
  351. package/dist/modes/interactive/components/startup-identity.js.map +1 -1
  352. package/dist/modes/interactive/components/task-completion-message.js +2 -0
  353. package/dist/modes/interactive/components/task-completion-message.js.map +1 -1
  354. package/dist/modes/interactive/components/task-detail.js +2 -0
  355. package/dist/modes/interactive/components/task-detail.js.map +1 -1
  356. package/dist/modes/interactive/components/task-inspector.js +22 -12
  357. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  358. package/dist/modes/interactive/components/task-list.js +2 -0
  359. package/dist/modes/interactive/components/task-list.js.map +1 -1
  360. package/dist/modes/interactive/components/task-live-transcript.js +8 -3
  361. package/dist/modes/interactive/components/task-live-transcript.js.map +1 -1
  362. package/dist/modes/interactive/components/task-navigation.js +5 -2
  363. package/dist/modes/interactive/components/task-navigation.js.map +1 -1
  364. package/dist/modes/interactive/components/task-row.js +2 -0
  365. package/dist/modes/interactive/components/task-row.js.map +1 -1
  366. package/dist/modes/interactive/components/theme-selector.js +2 -0
  367. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  368. package/dist/modes/interactive/components/thinking-selector.js +7 -1
  369. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  370. package/dist/modes/interactive/components/tool-execution.js +25 -10
  371. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  372. package/dist/modes/interactive/components/transcript-follow-indicator.js +1 -0
  373. package/dist/modes/interactive/components/transcript-follow-indicator.js.map +1 -1
  374. package/dist/modes/interactive/components/tree-selector-component.js +7 -3
  375. package/dist/modes/interactive/components/tree-selector-component.js.map +1 -1
  376. package/dist/modes/interactive/components/tree-selector-help.js +1 -0
  377. package/dist/modes/interactive/components/tree-selector-help.js.map +1 -1
  378. package/dist/modes/interactive/components/tree-selector-label-input.js +6 -2
  379. package/dist/modes/interactive/components/tree-selector-label-input.js.map +1 -1
  380. package/dist/modes/interactive/components/tree-selector-list.js +4 -0
  381. package/dist/modes/interactive/components/tree-selector-list.js.map +1 -1
  382. package/dist/modes/interactive/components/trust-selector.js +6 -0
  383. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  384. package/dist/modes/interactive/components/user-message-selector.js +6 -3
  385. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  386. package/dist/modes/interactive/components/user-message.js +5 -0
  387. package/dist/modes/interactive/components/user-message.js.map +1 -1
  388. package/dist/modes/interactive/components/working-status.js +1 -0
  389. package/dist/modes/interactive/components/working-status.js.map +1 -1
  390. package/dist/modes/interactive/interactive-autocomplete.js +2 -0
  391. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  392. package/dist/modes/interactive/interactive-extension-runtime.js +1 -0
  393. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  394. package/dist/modes/interactive/interactive-mode-base.js +162 -120
  395. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  396. package/dist/modes/interactive/interactive-mode-helpers.js +3 -0
  397. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  398. package/dist/modes/interactive/interactive-mode-surface.d.ts +0 -6
  399. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  400. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  401. package/dist/modes/interactive/interactive-resource-disclosure.js +0 -4
  402. package/dist/modes/interactive/interactive-resource-disclosure.js.map +1 -1
  403. package/dist/modes/interactive/interactive-resource-rendering.js +0 -12
  404. package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
  405. package/dist/modes/interactive/interactive-startup-chat-container.js +1 -4
  406. package/dist/modes/interactive/interactive-startup-chat-container.js.map +1 -1
  407. package/dist/modes/interactive/model-catalog-refresh.js +1 -3
  408. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
  409. package/dist/modes/interactive/theme/color-utils.d.ts +5 -0
  410. package/dist/modes/interactive/theme/color-utils.d.ts.map +1 -1
  411. package/dist/modes/interactive/theme/color-utils.js +11 -0
  412. package/dist/modes/interactive/theme/color-utils.js.map +1 -1
  413. package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
  414. package/dist/modes/interactive/theme/global-theme.js +4 -3
  415. package/dist/modes/interactive/theme/global-theme.js.map +1 -1
  416. package/dist/modes/interactive/theme/theme-class.js +7 -0
  417. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  418. package/dist/modes/interactive/theme/theme-controller.js +9 -2
  419. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  420. package/dist/modes/interactive-engine/activity-watchdog.js +8 -3
  421. package/dist/modes/interactive-engine/activity-watchdog.js.map +1 -1
  422. package/dist/modes/interactive-engine/engine-custom-ui.js +12 -8
  423. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  424. package/dist/modes/interactive-engine/engine-dialog-host.js +7 -3
  425. package/dist/modes/interactive-engine/engine-dialog-host.js.map +1 -1
  426. package/dist/modes/interactive-engine/engine-health.js +23 -13
  427. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  428. package/dist/modes/interactive-engine/engine-input-form.js +3 -2
  429. package/dist/modes/interactive-engine/engine-input-form.js.map +1 -1
  430. package/dist/modes/interactive-engine/engine-monitor.js +13 -1
  431. package/dist/modes/interactive-engine/engine-monitor.js.map +1 -1
  432. package/dist/modes/interactive-engine/engine-project-trust.js +2 -1
  433. package/dist/modes/interactive-engine/engine-project-trust.js.map +1 -1
  434. package/dist/modes/interactive-engine/engine-render-service.js +7 -4
  435. package/dist/modes/interactive-engine/engine-render-service.js.map +1 -1
  436. package/dist/modes/interactive-engine/engine-session-picker.js +3 -2
  437. package/dist/modes/interactive-engine/engine-session-picker.js.map +1 -1
  438. package/dist/modes/interactive-engine/input-form-host.js +5 -1
  439. package/dist/modes/interactive-engine/input-form-host.js.map +1 -1
  440. package/dist/modes/interactive-engine/isolated-runtime.js +37 -23
  441. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  442. package/dist/modes/interactive-engine/remote-command-catalog.js +4 -3
  443. package/dist/modes/interactive-engine/remote-command-catalog.js.map +1 -1
  444. package/dist/modes/interactive-engine/remote-component.js +24 -12
  445. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  446. package/dist/modes/interactive-engine/remote-frame-clamp.js +3 -3
  447. package/dist/modes/interactive-engine/remote-frame-clamp.js.map +1 -1
  448. package/dist/modes/interactive-engine/remote-model-catalog.js +5 -4
  449. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
  450. package/dist/modes/interactive-engine/remote-queue-pause.js +3 -1
  451. package/dist/modes/interactive-engine/remote-queue-pause.js.map +1 -1
  452. package/dist/modes/interactive-engine/remote-renderer.js +24 -13
  453. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  454. package/dist/modes/interactive-engine/resource-readiness-error.js +1 -0
  455. package/dist/modes/interactive-engine/resource-readiness-error.js.map +1 -1
  456. package/dist/modes/interactive-engine/session-picker-host.js +5 -1
  457. package/dist/modes/interactive-engine/session-picker-host.js.map +1 -1
  458. package/dist/modes/interactive-engine/terminal-mode-controller.js +2 -1
  459. package/dist/modes/interactive-engine/terminal-mode-controller.js.map +1 -1
  460. package/dist/modes/rpc/queued-writer.js +13 -4
  461. package/dist/modes/rpc/queued-writer.js.map +1 -1
  462. package/dist/modes/rpc/rpc-bash-request-owners.js +2 -1
  463. package/dist/modes/rpc/rpc-bash-request-owners.js.map +1 -1
  464. package/dist/modes/rpc/rpc-client-api.d.ts +8 -4
  465. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  466. package/dist/modes/rpc/rpc-client-api.js +10 -3
  467. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  468. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  469. package/dist/modes/rpc/rpc-client.js +35 -22
  470. package/dist/modes/rpc/rpc-client.js.map +1 -1
  471. package/dist/modes/rpc/rpc-command-handler.js +6 -6
  472. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  473. package/dist/modes/rpc/rpc-event-buffer.js +3 -1
  474. package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
  475. package/dist/modes/rpc/rpc-generation-buffer.js +1 -3
  476. package/dist/modes/rpc/rpc-generation-buffer.js.map +1 -1
  477. package/dist/modes/rpc/rpc-keybindings-reload.js +4 -1
  478. package/dist/modes/rpc/rpc-keybindings-reload.js.map +1 -1
  479. package/dist/modes/rpc/rpc-output-buffer.js +3 -4
  480. package/dist/modes/rpc/rpc-output-buffer.js.map +1 -1
  481. package/dist/modes/rpc/rpc-pending-requests.js +1 -3
  482. package/dist/modes/rpc/rpc-pending-requests.js.map +1 -1
  483. package/dist/modes/rpc/rpc-provider-auth.js +3 -1
  484. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  485. package/dist/modes/rpc/rpc-resource-readiness.js +4 -5
  486. package/dist/modes/rpc/rpc-resource-readiness.js.map +1 -1
  487. package/dist/modes/rpc/rpc-session-binding.js +15 -0
  488. package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
  489. package/dist/modes/rpc/rpc-terminal-drain.js +3 -0
  490. package/dist/modes/rpc/rpc-terminal-drain.js.map +1 -1
  491. package/dist/modes/rpc/rpc-types.d.ts +10 -1
  492. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  493. package/dist/modes/rpc/rpc-types.js.map +1 -1
  494. package/docs/models/evals.md +883 -39
  495. package/docs/models/model-selection.md +7 -8
  496. package/docs/rpc/examples.md +1 -1
  497. package/docs/rpc/protocol.md +9 -3
  498. package/docs/sdk/structured-decisions.md +1 -1
  499. package/docs/sdk.md +3 -3
  500. package/docs/settings.md +24 -3
  501. package/docs/subagents/reference.md +22 -4
  502. package/docs/subagents.md +2 -0
  503. package/docs/usage.md +3 -3
  504. package/docs/workflows/api-reference.md +1 -1
  505. package/docs/workflows/authoring.md +1 -7
  506. package/docs/workflows/builtins.md +1 -1
  507. package/docs/workflows/reliable-design.md +1 -1
  508. package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
  509. package/examples/extensions/gondolin/package.json +1 -1
  510. package/examples/rpc-client.ts +1 -1
  511. package/examples/rpc-extension-ui.ts +1 -1
  512. package/npm-shrinkwrap.json +70 -33
  513. package/package.json +6 -7
  514. package/dist/core/model-routing-task.d.ts.map +0 -1
  515. package/dist/core/model-routing-task.js +0 -120
  516. package/dist/core/model-routing-task.js.map +0 -1
@@ -94631,7 +94631,7 @@ var SCOPE_DISCIPLINE_CONTRACT = keepContext([
94631
94631
  `));
94632
94632
  var EVIDENCE_CLOSURE_POLICY = [
94633
94633
  "Convergence flag (stop_review_loop):",
94634
- "- stop_review_loop is the single authoritative convergence signal; the harness trusts it without recomputing approval from findings, priorities, or requirements_traceability.",
94634
+ "- stop_review_loop is the convergence signal. The harness does not recompute approval from requirements_traceability, but it does not count stop_review_loop=true as approval when the same review says the patch is incorrect, reports goal_oracle_satisfied=false, or lists a blocking finding.",
94635
94635
  "- Derive stop_review_loop=false while any objective-relevant blocking work remains: a P0/P1/P2 finding, a required_by_objective finding at any priority including P3, or an unproven implementation/validation requirement.",
94636
94636
  "- Derive stop_review_loop=true when independent verification proves implementation and validation and only non-blocking items remain: consistent_with_objective P3 items, beyond_objective/contradicts_objective observations, an authorized post-approval PR/MR/review action, or reviewer quorum. Never hold it false for those items.",
94637
94637
  "- If the bounded loop ends first, preserve unresolved findings and remaining work for a human rather than relabeling them."
@@ -96509,6 +96509,24 @@ function findingBlocksClosure(finding) {
96509
96509
  return true;
96510
96510
  return priority <= MAX_BLOCKING_PRIORITY;
96511
96511
  }
96512
+ function stopReviewLoopContradictions(verdict) {
96513
+ const contradictions = [];
96514
+ if (verdict.overall_correctness !== "patch is correct") {
96515
+ contradictions.push(`overall_correctness is "${verdict.overall_correctness}"`);
96516
+ }
96517
+ if (verdict.goal_oracle_satisfied === false) {
96518
+ contradictions.push("goal_oracle_satisfied is false");
96519
+ }
96520
+ for (const finding of verdict.findings) {
96521
+ if (findingBlocksClosure(finding)) {
96522
+ contradictions.push(`blocking finding "${finding.title}"`);
96523
+ }
96524
+ }
96525
+ return contradictions;
96526
+ }
96527
+ function contradictedStopReviewLoopGap(contradictions) {
96528
+ return `stop_review_loop=true was not counted as approval because the same review reports ${contradictions.join("; ")}`;
96529
+ }
96512
96530
  function findingConsolidationKey(finding) {
96513
96531
  const normalizedTitle = finding.title.replace(/^\s*\[P[0-3]\]\s*/iu, "").toLowerCase().replace(/\s+/gu, " ").trim();
96514
96532
  return `${finding.code_location?.absolute_file_path ?? ""}::${normalizedTitle}`;
@@ -96762,7 +96780,7 @@ function reduceGoalDecision(ledger, turnReviews, options) {
96762
96780
  ...summary,
96763
96781
  turn: options.turn,
96764
96782
  decision: "complete",
96765
- reason: `Reviewer quorum met: ${completeVotes}/${options.reviewQuorum} reviewers independently reported stop_review_loop=true with no reviewer execution errors.`,
96783
+ reason: `Reviewer quorum met: ${completeVotes}/${options.reviewQuorum} reviewers independently reported stop_review_loop=true with a correct patch, a satisfied goal oracle, no blocking findings, and no reviewer execution errors.`,
96766
96784
  complete_votes: completeVotes,
96767
96785
  review_quorum: options.reviewQuorum
96768
96786
  }
@@ -96900,7 +96918,7 @@ function parsedReviewDecisionFromResult(result, reviewer) {
96900
96918
  };
96901
96919
  }
96902
96920
  function reviewApproved(decision) {
96903
- return decision.stop_review_loop === true && decision.reviewer_error == null;
96921
+ return decision.stop_review_loop === true && decision.reviewer_error == null && stopReviewLoopContradictions(decision).length === 0;
96904
96922
  }
96905
96923
  function reviewerErrorDecision(message) {
96906
96924
  return {
@@ -96933,6 +96951,7 @@ function blockerFromReviewDecision(decision) {
96933
96951
  function reviewDecisionToRecord(args) {
96934
96952
  const blocker = blockerFromReviewDecision(args.decision);
96935
96953
  const approved = reviewApproved(args.decision);
96954
+ const contradictions = args.decision.stop_review_loop === true ? stopReviewLoopContradictions(args.decision) : [];
96936
96955
  const hasFinalActionRemaining = args.allowFinalActionRemaining && finalActionRemaining(args.decision.requirements_traceability);
96937
96956
  const verificationGap = args.decision.verification_remaining.trim();
96938
96957
  const traceabilityGaps = args.decision.requirements_traceability.filter((entry) => entry.status !== "proven").map((entry) => `${entry.status}: ${entry.requirement} — ${entry.evidence}`);
@@ -96940,7 +96959,8 @@ function reviewDecisionToRecord(args) {
96940
96959
  ...args.decision.findings.map((finding) => `[${finding.objective_alignment}] ${finding.title}: ${finding.body}`),
96941
96960
  ...traceabilityGaps,
96942
96961
  ...approved || verificationGap.length === 0 ? [] : [verificationGap],
96943
- ...args.decision.reviewer_error == null ? [] : [`${args.decision.reviewer_error.kind}: ${args.decision.reviewer_error.message}`]
96962
+ ...args.decision.reviewer_error == null ? [] : [`${args.decision.reviewer_error.kind}: ${args.decision.reviewer_error.message}`],
96963
+ ...contradictions.length === 0 ? [] : [contradictedStopReviewLoopGap(contradictions)]
96944
96964
  ];
96945
96965
  const nextAction = approved ? hasFinalActionRemaining ? "pull-request" : "finish" : blocker === null ? "implementation" : "blocked";
96946
96966
  const convergenceDecision = summarizeReviewConvergence({
@@ -99150,7 +99170,7 @@ import { dirname as dirname7, join as join19 } from "node:path";
99150
99170
  import { Type as Type19 } from "typebox";
99151
99171
  // dist/builtin/workflows/builtin/ralph-review-gate.ts
99152
99172
  function reviewDecisionApproved(decision) {
99153
- return decision.stop_review_loop === true && decision.reviewer_error == null;
99173
+ return decision.stop_review_loop === true && decision.reviewer_error == null && stopReviewLoopContradictions(decision).length === 0;
99154
99174
  }
99155
99175
 
99156
99176
  // dist/builtin/workflows/builtin/ralph-core.ts
@@ -109393,7 +109413,9 @@ import { createStructuredOutputCapture, runCallback as runCallback2 } from "@bas
109393
109413
  import {
109394
109414
  AutoRoutingInferenceError,
109395
109415
  convertToLlm,
109396
- parseModelConstraints
109416
+ isModelRoutingDebugEnabled,
109417
+ parseModelConstraints,
109418
+ setsProviders
109397
109419
  } from "@bastani/atomic";
109398
109420
 
109399
109421
  // dist/builtin/workflows/src/runs/shared/model-fallback-candidates.ts
@@ -110134,6 +110156,7 @@ function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendingStage
110134
110156
  fallbackModels: _fallbackModels,
110135
110157
  fallbackThinkingLevels: _fallbackThinkingLevels,
110136
110158
  modelConstraints: _modelConstraints,
110159
+ taskNeeds: _taskNeeds,
110137
110160
  inheritedModelConstraints: _inheritedModelConstraints,
110138
110161
  routerSelection: _routerSelection,
110139
110162
  context,
@@ -110988,7 +111011,9 @@ class StageSessionController {
110988
111011
  stageName: this.opts.stageName,
110989
111012
  constraints,
110990
111013
  signal: this.startupWait.signal,
110991
- selection: options?.routerSelection
111014
+ selection: options?.routerSelection,
111015
+ ...options?.taskNeeds ? { taskNeeds: options.taskNeeds } : {},
111016
+ ...setsProviders(parseModelConstraints(options?.modelConstraints)) ? { overrideProviderSettings: true } : {}
110992
111017
  });
110993
111018
  } catch (error) {
110994
111019
  this.startupWait.signal.throwIfAborted();
@@ -110996,7 +111021,8 @@ class StageSessionController {
110996
111021
  if (!(error instanceof AutoRoutingInferenceError) || error.currentModelRoute === undefined)
110997
111022
  throw error;
110998
111023
  this.modelRoute = error.currentModelRoute;
110999
- this.modelCatalog?.recordWarning?.(`workflows: stage auto routing failed; running "${this.opts.stageName}" on the current chat model ${this.modelRoute.modelOverride}.`);
111024
+ if (isModelRoutingDebugEnabled())
111025
+ this.modelCatalog?.recordWarning?.(`workflows: stage auto routing failed; running "${this.opts.stageName}" on the current chat model ${this.modelRoute.modelOverride}.`);
111000
111026
  }
111001
111027
  this.modelRoute.assertCurrent();
111002
111028
  this.meta.stageOptions = { ...options, model: this.modelRoute.modelOverride };
@@ -116349,6 +116375,7 @@ function workflowModelCatalogFromContext(ctx, resolveLiveContext) {
116349
116375
  ctx: {
116350
116376
  model: current.model,
116351
116377
  getRouterModel: () => current.getRouterModel(),
116378
+ ...current.getModelRouting ? { getModelRouting: () => current.getModelRouting() } : {},
116352
116379
  modelRegistry: {
116353
116380
  getAvailable: () => registry.getAvailable(),
116354
116381
  getAll: () => registry.getAll(),
@@ -116364,7 +116391,9 @@ function workflowModelCatalogFromContext(ctx, resolveLiveContext) {
116364
116391
  agent: { name: input.stageName, description: "Workflow stage" },
116365
116392
  constraints: input.constraints,
116366
116393
  signal: input.signal,
116367
- selection: input.selection
116394
+ selection: input.selection,
116395
+ ...input.taskNeeds ? { taskNeeds: input.taskNeeds } : {},
116396
+ ...input.overrideProviderSettings ? { overrideProviderSettings: true } : {}
116368
116397
  });
116369
116398
  },
116370
116399
  listModels: async () => {
@@ -122051,7 +122080,7 @@ var DEFAULT_PROMPT_GUIDANCE = [
122051
122080
  - Before launching, share a brief duration estimate without confidence labels. Estimates are not guarantees or budgets.
122052
122081
  - Preserve inherited budget limits and approval gates without asking for a budget before each launch. Pass \`budget\` only for limits the user stated; omission inherits and zero disables only its field. Never convert an estimate into a cap.
122053
122082
  - Heartbeat cadence is 15 minutes by default. Keep that interval unless the user explicitly asks for a different cadence. A heartbeat is a periodic alignment check: re-read the objective, judge whether the run is still on goal, and continue a progressing run when no intervention is needed. Use workflow pause, resume, or quit when run control is useful, and ask the user when a decision is needed.
122054
- - Wrap critical parts of the \`inputs\` you pass — objective, prompt, acceptance criteria — in \`<keepContext>\` / \`</keepContext>\`. Tagged text survives compaction verbatim regardless of the compression ratio, and stages inherit it because workflows inject your inputs into their prompts. A long stage is compacted repeatedly, and compaction ranks lines individually: a verbose restated objective outlives the one line that bounds it, so a stage can end up executing a coherent but unbounded version of what you asked for. Decide this per launch rather than tagging everything — tag role constraints, prohibitions, must-hold criteria, and identifiers such as a target branch, worktree path, or issue number; leave background, quoted issue text, and reference material untagged and pass bulk through files and \`reads\`. Protected lines count against the keep target rather than raising it, so an over-tagged input makes the evidence stages need compress harder. \`model: "auto"\` stages also route on an excerpt of about 9 KB (roughly 1,200 words) that keeps only the beginning, the end, and the protected spans, so state the objective in the first or last lines of an input or inside a short tagged span, keep tagged spans to a few lines, and put bulky material in the middle.
122083
+ - Wrap critical parts of the \`inputs\` you pass — objective, prompt, acceptance criteria — in \`<keepContext>\` / \`</keepContext>\`. Tagged text survives compaction verbatim regardless of the compression ratio, and stages inherit it because workflows inject your inputs into their prompts. A long stage is compacted repeatedly, and compaction ranks lines individually: a verbose restated objective outlives the one line that bounds it, so a stage can end up executing a coherent but unbounded version of what you asked for. Decide this per launch rather than tagging everything — tag role constraints, prohibitions, must-hold criteria, and identifiers such as a target branch, worktree path, or issue number; leave background, quoted issue text, and reference material untagged and pass bulk through files and \`reads\`. Protected lines count against the keep target rather than raising it, so an over-tagged input makes the evidence stages need compress harder.
122055
122084
  - Tag steering the same way. An Intercom \`send\` amendment is authoritative and stages must carry it forward, but it arrives late in an already-long session and is exactly one short message competing with the whole transcript; \`<keepContext>\` around the requirement keeps it from being compacted away before the stage acts on it.
122056
122085
  - In interactive chat, named workflow launches run in the background. Run \`/workflow connect <run>\` to see agents working and chat with and steer each stage. Inspection and control calls (\`status\`, \`stages\`, \`stage\`, \`transcript\`, \`answer\`, \`pause\`, \`resume\`, \`quit\`) remain available while work runs.
122057
122086
  - At lifecycle updates, revise the estimate only when new evidence materially changes the remaining path; at completion, report actual elapsed time against the estimate and note the main bottleneck for future scheduling. Do not add confidence labels or scores to duration estimates.
@@ -122089,7 +122118,7 @@ var DEFAULT_PROMPT_GUIDANCE = [
122089
122118
  - Prefer \`ctx.tool(name, args, fn)\` for workflow-owned TypeScript operations with side effects, such as filesystem writes, network mutations, and external API actions. It creates a tracked, non-attachable durable graph node before invoking \`fn\`; it may be used before, between, after, or without model stages. A completed \`ctx.tool\` call is durably checkpointed with its serializable result, so resume replays that result without rerunning \`fn\`. For checks that may fail during a bounded repair loop, opt into \`failureMode: "return"\`, branch on the typed outcome, and pass only the needed error fields to the repair stage or artifact yourself; Atomic does not inject failure evidence into later prompts. Retries do not bound a hung callback, so every \`ctx.tool\` callback that starts a child process or performs network I/O MUST set an explicit positive finite \`timeoutMs\` and forward the supplied \`signal\` to cancellable work. A timeout applies per attempt, aborts that attempt's signal, and gives retries a fresh deadline and signal. Cancellation and storage faults still throw. Keep pure computation and side-effect-free transformations as ordinary TypeScript. Do not wrap agent-stage internals or every function call indiscriminately; this rule applies to side effects orchestrated directly by the workflow definition.
122090
122119
  - Pass large stage context through files/artifacts and \`reads\` with an explicit \`Read the file at <path>...\` prompt rather than large \`previous\` payloads or injected session history.
122091
122120
  - Wrap critical stage-prompt content in \`<keepContext>\` / \`</keepContext>\`. Tagged content survives compression verbatim regardless of the compression ratio, and every line of the span including the tag lines is protected. A long-running stage will be compacted, and compaction ranks lines individually: an objective is verbose and restated while the constraint that narrows it is usually one line, so the constraint is the cheaper deletion and what survives reads as broader permission than intended. Tag role constraints that bound a stage to part of the work, acceptance criteria and immutable contracts, explicit prohibitions, and identifiers a stage must not lose such as a target branch, worktree path, or run ID. Do not tag bulk context: protected lines count against the keep target rather than raising it, so a large protected span makes the surrounding transcript compress harder — tag the constraint, not the material it applies to.
122092
- - Structure \`model: "auto"\` stage prompts for the model router. Routing sees an excerpt of about 9 KB (roughly 1,200 words): the beginning, the end, and every \`<keepContext>\` span, with cuts marked \`[... truncated ...]\`; the stage still receives the full prompt. Put the stage's role and objective in the first or last lines or a short tagged span, place artifact reads, issue text, and prior-stage output in the middle, and keep tagged spans brief — spans that alone exceed the excerpt are cut through the middle.
122121
+ - For \`model: "auto"\` stages, a chat model reads the prompt to answer the routing questions. Set \`taskNeeds\` (work, difficulty, mistakeCost, needsImages, longContext, latencySensitive) with everything you can judge so routing does not have to infer it. To skip whole providers because the user asked, set \`modelConstraints.allowedProviders\` or \`excludedProviders\`, which replace the user's \`modelRouting\` provider settings for that stage. To choose the contenders yourself, list them in \`modelConstraints.allowedModels\`; prefer the user's subscription models (for example ChatGPT/Codex, GitHub Copilot, a Claude subscription, or a coding or token plan) over pay-per-token API models, unless the user asked for API models or has no subscription models.
122093
122122
  - Separate implementation/review acceptance from explicitly authorized final actions such as PR/MR/review creation, release tagging, deployment, or publication. Stop implementation loops once acceptance is proven and carry a remaining final action separately.
122094
122123
  - A model stage sees its local prompt, artifacts, tools, and reads, not the graph name or surrounding implementation. State the concrete action, evidence, and success criteria directly.`
122095
122124
  ];
@@ -51078,7 +51078,9 @@ import { createStructuredOutputCapture, runCallback as runCallback2 } from "@bas
51078
51078
  import {
51079
51079
  AutoRoutingInferenceError,
51080
51080
  convertToLlm,
51081
- parseModelConstraints
51081
+ isModelRoutingDebugEnabled,
51082
+ parseModelConstraints,
51083
+ setsProviders
51082
51084
  } from "@bastani/atomic";
51083
51085
 
51084
51086
  // dist/builtin/workflows/src/runs/shared/model-fallback-candidates.ts
@@ -51819,6 +51821,7 @@ function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendingStage
51819
51821
  fallbackModels: _fallbackModels,
51820
51822
  fallbackThinkingLevels: _fallbackThinkingLevels,
51821
51823
  modelConstraints: _modelConstraints,
51824
+ taskNeeds: _taskNeeds,
51822
51825
  inheritedModelConstraints: _inheritedModelConstraints,
51823
51826
  routerSelection: _routerSelection,
51824
51827
  context,
@@ -52673,7 +52676,9 @@ class StageSessionController {
52673
52676
  stageName: this.opts.stageName,
52674
52677
  constraints,
52675
52678
  signal: this.startupWait.signal,
52676
- selection: options?.routerSelection
52679
+ selection: options?.routerSelection,
52680
+ ...options?.taskNeeds ? { taskNeeds: options.taskNeeds } : {},
52681
+ ...setsProviders(parseModelConstraints(options?.modelConstraints)) ? { overrideProviderSettings: true } : {}
52677
52682
  });
52678
52683
  } catch (error) {
52679
52684
  this.startupWait.signal.throwIfAborted();
@@ -52681,7 +52686,8 @@ class StageSessionController {
52681
52686
  if (!(error instanceof AutoRoutingInferenceError) || error.currentModelRoute === undefined)
52682
52687
  throw error;
52683
52688
  this.modelRoute = error.currentModelRoute;
52684
- this.modelCatalog?.recordWarning?.(`workflows: stage auto routing failed; running "${this.opts.stageName}" on the current chat model ${this.modelRoute.modelOverride}.`);
52689
+ if (isModelRoutingDebugEnabled())
52690
+ this.modelCatalog?.recordWarning?.(`workflows: stage auto routing failed; running "${this.opts.stageName}" on the current chat model ${this.modelRoute.modelOverride}.`);
52685
52691
  }
52686
52692
  this.modelRoute.assertCurrent();
52687
52693
  this.meta.stageOptions = { ...options, model: this.modelRoute.modelOverride };
@@ -1,5 +1,5 @@
1
1
  /** Workflow authoring primitives, stage/session contracts, and task option types. */
2
- import type { ModelConstraints, ModelRoute, ModelRouterOutput } from "@bastani/atomic";
2
+ import type { ModelConstraints, ModelRoute, ModelRouterOutput, TaskNeeds } from "@bastani/atomic";
3
3
  import type { Static, TSchema } from "typebox";
4
4
  export type { Static, TSchema };
5
5
  export type WorkflowSerializablePrimitive = string | number | boolean | null;
@@ -90,6 +90,9 @@ export interface WorkflowModelCatalogPort {
90
90
  constraints: readonly ModelConstraints[];
91
91
  signal?: AbortSignal;
92
92
  selection?: ModelRouterOutput;
93
+ taskNeeds?: TaskNeeds;
94
+ /** The stage's own constraints set a provider list, replacing the user's provider settings. */
95
+ overrideProviderSettings?: boolean;
93
96
  }): Promise<ModelRoute>;
94
97
  readonly currentModel?: WorkflowModelValue;
95
98
  readonly preferredProvider?: string;
@@ -130,6 +133,8 @@ export interface StageOptions<TSchemaDef extends TSchema | undefined = TSchema |
130
133
  readonly model?: WorkflowModelValue;
131
134
  /** Hard restrictions for automatic model selection and its execution fallbacks. */
132
135
  readonly modelConstraints?: ModelConstraints;
136
+ /** What the author already knows about the task, for `model: "auto"`; routing asks only for the rest. */
137
+ readonly taskNeeds?: TaskNeeds;
133
138
  readonly mcp?: StageMcpOptions;
134
139
  readonly tools?: readonly string[];
135
140
  readonly noTools?: "all" | "builtin";
@@ -1,5 +1,10 @@
1
1
  import { APP_NAME } from "../config.js";
2
2
  export class AuthCommandError extends Error {
3
+ // Declared and assigned explicitly rather than as a constructor parameter
4
+ // property: `tsconfig.base.json` sets `erasableSyntaxOnly`, under which a
5
+ // parameter property is TS1294. Root `tsc --noEmit` does not surface it,
6
+ // but the shipped build does.
7
+ exitCode;
3
8
  constructor(message, exitCode = 1) {
4
9
  super(message);
5
10
  this.exitCode = exitCode;
@@ -1 +1 @@
1
- {"version":3,"file":"auth-command.js","sourceRoot":"","sources":["../../src/cli/auth-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAgBxC,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAO1C,YAAY,OAAe,EAAE,QAAQ,GAAG,CAAC;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IAChC,CAAC;CACD;AAED,MAAM,kBAAkB,GAAoC;IAC3D,KAAK,EAAE,GAAG,QAAQ,+FAA+F;IACjH,OAAO,EAAE,GAAG,QAAQ,6DAA6D;IACjF,YAAY,EAAE,GAAG,QAAQ,4FAA4F;CACrH,CAAC;AAEF,MAAM,UAAU,kBAAkB,CAAC,IAAqB;IACvD,OAAO,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,yBAAyB,CAAC;AAChH,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAqB;IACxD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,IAAc;IAC/C,IAAI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AAE,WAAW,EAAE,SAAS,EAAE;QAC3D,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAU;IAC/C,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;IACpD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;IAC9C,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;QAChC,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;QACrD,MAAM,IAAI,gBAAgB,CAAC,oBAAoB,MAAM,oBAAoB,CAAC,CAAC;IAC5E,CAAC;IACD,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvF,MAAM,IAAI,gBAAgB,CAAC,gDAAgD,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,CAAC,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,gBAAgB,CAAC,8DAA8D,CAAC,CAAC;IAC5F,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["import { APP_NAME } from \"../config.js\";\nimport type { Args } from \"./args.ts\";\n\nexport type AuthCommandKind = \"check\" | \"api_key\" | \"bearer_token\";\n\nexport interface AuthCommand {\n\tkind: AuthCommandKind;\n\t/** Remaining argv for the normal parser. */\n\targs: string[];\n\tjson: boolean;\n\t/** `auth check` emits a resolved credential only with this explicit opt-in. */\n\tcredentials: boolean;\n\tnoRefresh: boolean;\n\tminExpiryMs?: number;\n}\n\nexport class AuthCommandError extends Error {\n\t// Declared and assigned explicitly rather than as a constructor parameter\n\t// property: `tsconfig.base.json` sets `erasableSyntaxOnly`, under which a\n\t// parameter property is TS1294. Root `tsc --noEmit` does not surface it,\n\t// but the shipped build does.\n\treadonly exitCode: number;\n\n\tconstructor(message: string, exitCode = 1) {\n\t\tsuper(message);\n\t\tthis.exitCode = exitCode;\n\t\tthis.name = \"AuthCommandError\";\n\t}\n}\n\nconst AUTH_COMMAND_USAGE: Record<AuthCommandKind, string> = {\n\tcheck: `${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]`,\n\tapi_key: `${APP_NAME} auth print-api-key --model <model> [--provider <provider>]`,\n\tbearer_token: `${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]`,\n};\n\nexport function getAuthCommandName(kind: AuthCommandKind): string {\n\treturn kind === \"check\" ? \"auth check\" : kind === \"api_key\" ? \"auth print-api-key\" : \"auth print-bearer-token\";\n}\n\nexport function getAuthCommandUsage(kind: AuthCommandKind): string {\n\treturn AUTH_COMMAND_USAGE[kind];\n}\n\nexport function isAuthCommandHelp(args: string[]): boolean {\n\tif (args[0] !== \"auth\") return false;\n\tif (args[1] === undefined || args[1] === \"help\" || args[1] === \"--help\" || args[1] === \"-h\") return true;\n\tconst terminator = args.indexOf(\"--\", 2);\n\tconst flags = args.slice(2, terminator === -1 ? undefined : terminator);\n\t// Checks accept direct help flags. The print commands reserve every extra\n\t// parser flag, including --help, as a usage error to keep their export stream narrow.\n\treturn args[1] === \"check\" && (flags.includes(\"--help\") || flags.includes(\"-h\"));\n}\n\nexport function printAuthCommandHelp(): void {\n\tconsole.error(`Usage:\n ${APP_NAME} auth print-api-key --model <model> [--provider <provider>]\n ${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]\n ${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]\n\nCredential print commands write one configured credential alone on stdout. Everything else —\nwarnings, provider selection, refresh notices, and help — goes to stderr. --model is\nrequired for these exports, so no ambient model can emit a credential you did not name.\n\nAuth checks require at least one of --provider or --model. They print ready, not_ready,\nor invalid on stdout and refresh expired OAuth credentials by default; --no-refresh\nprevents a refresh and any auth.json mutation. --json includes the resolved provider\nwhen one is found, plus auth type and a reason when it is not ready. --credentials is\nan explicit export that needs --provider or an exact --model target; on a ready check\nit writes the credential, or includes it in JSON. A non-ready raw export leaves stdout\nempty and reports status on stderr.\n\n--min-expiry accepts ms, s, m, or h (for example 30m) and applies only to\nprint-bearer-token, where it defaults to 30m. A token with less than that\nremaining is refreshed first. It remains reserved after --, so print-api-key\nstill rejects it in either spelling.\n\nCredential-export exit codes:\n 0 credential written to stdout\n 1 usage error\n 2 no credential configured\n 3 provider ambiguous\n 4 credential kind unsupported for that provider\n 5 refresh failed (the stored credential is left untouched)\n 6 provider cannot mint a token that lives long enough\n 7 the provider's OAuth credential could not be used\n 8 the credential could not be written (nothing was emitted)\n 9 the credential was written only in part; stdout holds an unusable\n fragment, which the caller must discard rather than use\n\nAuth-check exit codes:\n 0 provider is ready\n 1 provider is not ready\n 2 auth state or command is invalid\n 8 with --credentials, the credential could not be written\n 9 with --credentials, only part of the credential was written`);\n}\n\nfunction parseDuration(value: string | undefined, exitCode: number): number {\n\tconst match = value ? /^(\\d+)(ms|s|m|h)$/iu.exec(value) : undefined;\n\tif (!match) throw new AuthCommandError(\"--min-expiry must use a duration such as 30m or 1h\", exitCode);\n\tconst unit = match[2].toLowerCase();\n\tconst scale = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n\treturn Number(match[1]) * scale;\n}\n\n/** Parse the `atomic auth` command surface before normal startup. */\nexport function parseAuthCommand(args: string[]): AuthCommand | undefined {\n\tif (args[0] !== \"auth\") return undefined;\n\n\tconst kind: AuthCommandKind | undefined =\n\t\targs[1] === \"check\"\n\t\t\t? \"check\"\n\t\t\t: args[1] === \"print-api-key\"\n\t\t\t\t? \"api_key\"\n\t\t\t\t: args[1] === \"print-bearer-token\"\n\t\t\t\t\t? \"bearer_token\"\n\t\t\t\t\t: undefined;\n\tif (!kind) {\n\t\tthrow new AuthCommandError(\n\t\t\t`Unknown auth command \"${args[1] ?? \"\"}\". Use \"${APP_NAME} auth print-api-key\", \"${APP_NAME} auth print-bearer-token\", or \"${APP_NAME} auth check\".`,\n\t\t);\n\t}\n\n\tconst exitCode = kind === \"check\" ? 2 : 1;\n\tconst commandArgs: string[] = [];\n\tlet json = false;\n\tlet credentials = false;\n\tlet noRefresh = false;\n\tlet minExpiryMs: number | undefined;\n\tlet optionsEnded = false;\n\tfor (let index = 2; index < args.length; index++) {\n\t\tconst arg = args[index];\n\t\tif (arg === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcommandArgs.push(arg);\n\t\t\tcontinue;\n\t\t}\n\t\tconst inlineMinExpiry = arg.startsWith(\"--min-expiry=\") ? arg.slice(\"--min-expiry=\".length) : undefined;\n\t\tif (arg === \"--min-expiry\" || inlineMinExpiry !== undefined) {\n\t\t\tif (kind !== \"bearer_token\") {\n\t\t\t\tthrow new AuthCommandError(\"--min-expiry is only supported by print-bearer-token\", exitCode);\n\t\t\t}\n\t\t\tminExpiryMs = parseDuration(inlineMinExpiry ?? args[++index], exitCode);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && (arg === \"--json\" || arg === \"--credentials\" || arg === \"--no-refresh\")) {\n\t\t\tif (kind !== \"check\") throw new AuthCommandError(`${arg} is only supported by auth check`, exitCode);\n\t\t\tif (arg === \"--json\") json = true;\n\t\t\telse if (arg === \"--credentials\") credentials = true;\n\t\t\telse noRefresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tcommandArgs.push(arg);\n\t}\n\n\treturn minExpiryMs === undefined\n\t\t? { kind, args: commandArgs, json, credentials, noRefresh }\n\t\t: { kind, args: commandArgs, json, credentials, noRefresh, minExpiryMs };\n}\n\nexport function validateAuthCheckArgs(args: Args): { provider?: string; model?: string } {\n\tconst provider = args.provider?.trim() || undefined;\n\tconst model = args.model?.trim() || undefined;\n\tif (args.unknownFlags.size > 0) {\n\t\tconst option = args.unknownFlags.keys().next().value;\n\t\tthrow new AuthCommandError(`Unknown option --${option} for \"auth check\".`);\n\t}\n\tif (args.apiKey !== undefined || args.messages.length > 0 || args.fileArgs.length > 0) {\n\t\tthrow new AuthCommandError(\"Auth checks only accept --provider and --model\");\n\t}\n\tif (!provider && !model) {\n\t\tthrow new AuthCommandError(\"Auth checks require --provider <provider> or --model <model>\");\n\t}\n\treturn { provider, model };\n}\n"]}
1
+ {"version":3,"file":"auth-command.js","sourceRoot":"","sources":["../../src/cli/auth-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAgBxC,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAC1C,0EAA0E;IAC1E,0EAA0E;IAC1E,yEAAyE;IACzE,8BAA8B;IACrB,QAAQ,CAAS;IAE1B,YAAY,OAAe,EAAE,QAAQ,GAAG,CAAC;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IAChC,CAAC;CACD;AAED,MAAM,kBAAkB,GAAoC;IAC3D,KAAK,EAAE,GAAG,QAAQ,+FAA+F;IACjH,OAAO,EAAE,GAAG,QAAQ,6DAA6D;IACjF,YAAY,EAAE,GAAG,QAAQ,4FAA4F;CACrH,CAAC;AAEF,MAAM,UAAU,kBAAkB,CAAC,IAAqB;IACvD,OAAO,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,yBAAyB,CAAC;AAChH,CAAC;AAED,MAAM,U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\n\nexport interface AuthCommand {\n\tkind: AuthCommandKind;\n\t/** Remaining argv for the normal parser. */\n\targs: string[];\n\tjson: boolean;\n\t/** `auth check` emits a resolved credential only with this explicit opt-in. */\n\tcredentials: boolean;\n\tnoRefresh: boolean;\n\tminExpiryMs?: number;\n}\n\nexport class AuthCommandError extends Error {\n\t// Declared and assigned explicitly rather than as a constructor parameter\n\t// property: `tsconfig.base.json` sets `erasableSyntaxOnly`, under which a\n\t// parameter property is TS1294. Root `tsc --noEmit` does not surface it,\n\t// but the shipped build does.\n\treadonly exitCode: number;\n\n\tconstructor(message: string, exitCode = 1) {\n\t\tsuper(message);\n\t\tthis.exitCode = exitCode;\n\t\tthis.name = \"AuthCommandError\";\n\t}\n}\n\nconst AUTH_COMMAND_USAGE: Record<AuthCommandKind, string> = {\n\tcheck: `${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]`,\n\tapi_key: `${APP_NAME} auth print-api-key --model <model> [--provider <provider>]`,\n\tbearer_token: `${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]`,\n};\n\nexport function getAuthCommandName(kind: AuthCommandKind): string {\n\treturn kind === \"check\" ? \"auth check\" : kind === \"api_key\" ? \"auth print-api-key\" : \"auth print-bearer-token\";\n}\n\nexport function getAuthCommandUsage(kind: AuthCommandKind): string {\n\treturn AUTH_COMMAND_USAGE[kind];\n}\n\nexport function isAuthCommandHelp(args: string[]): boolean {\n\tif (args[0] !== \"auth\") return false;\n\tif (args[1] === undefined || args[1] === \"help\" || args[1] === \"--help\" || args[1] === \"-h\") return true;\n\tconst terminator = args.indexOf(\"--\", 2);\n\tconst flags = args.slice(2, terminator === -1 ? undefined : terminator);\n\t// Checks accept direct help flags. The print commands reserve every extra\n\t// parser flag, including --help, as a usage error to keep their export stream narrow.\n\treturn args[1] === \"check\" && (flags.includes(\"--help\") || flags.includes(\"-h\"));\n}\n\nexport function printAuthCommandHelp(): void {\n\tconsole.error(`Usage:\n ${APP_NAME} auth print-api-key --model <model> [--provider <provider>]\n ${APP_NAME} auth print-bearer-token --model <model> [--provider <provider>] [--min-expiry <duration>]\n ${APP_NAME} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]\n\nCredential print commands write one configured credential alone on stdout. Everything else —\nwarnings, provider selection, refresh notices, and help — goes to stderr. --model is\nrequired for these exports, so no ambient model can emit a credential you did not name.\n\nAuth checks require at least one of --provider or --model. They print ready, not_ready,\nor invalid on stdout and refresh expired OAuth credentials by default; --no-refresh\nprevents a refresh and any auth.json mutation. --json includes the resolved provider\nwhen one is found, plus auth type and a reason when it is not ready. --credentials is\nan explicit export that needs --provider or an exact --model target; on a ready check\nit writes the credential, or includes it in JSON. A non-ready raw export leaves stdout\nempty and reports status on stderr.\n\n--min-expiry accepts ms, s, m, or h (for example 30m) and applies only to\nprint-bearer-token, where it defaults to 30m. A token with less than that\nremaining is refreshed first. It remains reserved after --, so print-api-key\nstill rejects it in either spelling.\n\nCredential-export exit codes:\n 0 credential written to stdout\n 1 usage error\n 2 no credential configured\n 3 provider ambiguous\n 4 credential kind unsupported for that provider\n 5 refresh failed (the stored credential is left untouched)\n 6 provider cannot mint a token that lives long enough\n 7 the provider's OAuth credential could not be used\n 8 the credential could not be written (nothing was emitted)\n 9 the credential was written only in part; stdout holds an unusable\n fragment, which the caller must discard rather than use\n\nAuth-check exit codes:\n 0 provider is ready\n 1 provider is not ready\n 2 auth state or command is invalid\n 8 with --credentials, the credential could not be written\n 9 with --credentials, only part of the credential was written`);\n}\n\nfunction parseDuration(value: string | undefined, exitCode: number): number {\n\tconst match = value ? /^(\\d+)(ms|s|m|h)$/iu.exec(value) : undefined;\n\tif (!match) throw new AuthCommandError(\"--min-expiry must use a duration such as 30m or 1h\", exitCode);\n\tconst unit = match[2].toLowerCase();\n\tconst scale = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n\treturn Number(match[1]) * scale;\n}\n\n/** Parse the `atomic auth` command surface before normal startup. */\nexport function parseAuthCommand(args: string[]): AuthCommand | undefined {\n\tif (args[0] !== \"auth\") return undefined;\n\n\tconst kind: AuthCommandKind | undefined =\n\t\targs[1] === \"check\"\n\t\t\t? \"check\"\n\t\t\t: args[1] === \"print-api-key\"\n\t\t\t\t? \"api_key\"\n\t\t\t\t: args[1] === \"print-bearer-token\"\n\t\t\t\t\t? \"bearer_token\"\n\t\t\t\t\t: undefined;\n\tif (!kind) {\n\t\tthrow new AuthCommandError(\n\t\t\t`Unknown auth command \"${args[1] ?? \"\"}\". Use \"${APP_NAME} auth print-api-key\", \"${APP_NAME} auth print-bearer-token\", or \"${APP_NAME} auth check\".`,\n\t\t);\n\t}\n\n\tconst exitCode = kind === \"check\" ? 2 : 1;\n\tconst commandArgs: string[] = [];\n\tlet json = false;\n\tlet credentials = false;\n\tlet noRefresh = false;\n\tlet minExpiryMs: number | undefined;\n\tlet optionsEnded = false;\n\tfor (let index = 2; index < args.length; index++) {\n\t\tconst arg = args[index];\n\t\tif (arg === \"--\") {\n\t\t\toptionsEnded = true;\n\t\t\tcommandArgs.push(arg);\n\t\t\tcontinue;\n\t\t}\n\t\tconst inlineMinExpiry = arg.startsWith(\"--min-expiry=\") ? arg.slice(\"--min-expiry=\".length) : undefined;\n\t\tif (arg === \"--min-expiry\" || inlineMinExpiry !== undefined) {\n\t\t\tif (kind !== \"bearer_token\") {\n\t\t\t\tthrow new AuthCommandError(\"--min-expiry is only supported by print-bearer-token\", exitCode);\n\t\t\t}\n\t\t\tminExpiryMs = parseDuration(inlineMinExpiry ?? args[++index], exitCode);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!optionsEnded && (arg === \"--json\" || arg === \"--credentials\" || arg === \"--no-refresh\")) {\n\t\t\tif (kind !== \"check\") throw new AuthCommandError(`${arg} is only supported by auth check`, exitCode);\n\t\t\tif (arg === \"--json\") json = true;\n\t\t\telse if (arg === \"--credentials\") credentials = true;\n\t\t\telse noRefresh = true;\n\t\t\tcontinue;\n\t\t}\n\t\tcommandArgs.push(arg);\n\t}\n\n\treturn minExpiryMs === undefined\n\t\t? { kind, args: commandArgs, json, credentials, noRefresh }\n\t\t: { kind, args: commandArgs, json, credentials, noRefresh, minExpiryMs };\n}\n\nexport function validateAuthCheckArgs(args: Args): { provider?: string; model?: string } {\n\tconst provider = args.provider?.trim() || undefined;\n\tconst model = args.model?.trim() || undefined;\n\tif (args.unknownFlags.size > 0) {\n\t\tconst option = args.unknownFlags.keys().next().value;\n\t\tthrow new AuthCommandError(`Unknown option --${option} for \"auth check\".`);\n\t}\n\tif (args.apiKey !== undefined || args.messages.length > 0 || args.fileArgs.length > 0) {\n\t\tthrow new AuthCommandError(\"Auth checks only accept --provider and --model\");\n\t}\n\tif (!provider && !model) {\n\t\tthrow new AuthCommandError(\"Auth checks require --provider <provider> or --model <model>\");\n\t}\n\treturn { provider, model };\n}\n"]}
@@ -51,6 +51,8 @@ export const EXIT_CODES = {
51
51
  /** The codes whose contract is an empty stdout. See `EXIT_CODES`. */
52
52
  export const STDOUT_EMPTY_ON_EXIT = new Set(Object.keys(EXIT_CODES).filter((code) => code !== "CredentialTruncated"));
53
53
  export class CredentialPrintError extends Error {
54
+ code;
55
+ exitCode;
54
56
  constructor(code, message, options) {
55
57
  super(message, options);
56
58
  this.name = "CredentialPrintError";
@@ -1 +1 @@
1
- {"version":3,"file":"credential-print.js","sourceRoot":"","sources":["../../src/cli/credential-print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAKlG,8EAA8E;AAC9E,MAAM,CAAC,MAAM,kCAAkC,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AAI,oBAAoB,CAC7B,wBAAwB,EACxB,aAAa,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,oBAAoB,gBAAgB,CAClF,CAAC;IACH,CAAC;IAED,MAAM,IAAI,oBAAoB,CAC7B,mBAAmB,EACnB,UAAU,IAAI,CAAC,KAAK,wCAAwC,WAAW;SACrE,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC;SACnC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CACpC,CAAC;AACH,CAAC","sourcesContent":["/**\n * `atomic auth print-api-key` / `atomic auth print-bearer-token` and the\n * explicit `atomic auth check --credentials` export path.\n *\n * The only door in Atomic whose purpose is emitting a secret. Everything here\n * exists to keep that egress narrow:\n * - the secret leaves as a `Secret`, which cannot be interpolated, serialized,\n * or inspected, and is consumed exactly once by the stdout writer;\n * - every export has an explicit target: the print commands require `--model`,\n * and auth checks require `--provider` or an exact `--model` plus\n * `--credentials`;\n * - there is no `--output <file>` and no clipboard path — stdout only;\n * - every failure is a distinct exit code, and stdout stays empty on all of\n * them but one — `CredentialTruncated` (exit 9) exists to report the case\n * where it cannot be, because bytes already left and cannot be recalled;\n * - a failed OAuth refresh never mutates the stored credential.\n *\n * One residual, and it is upstream: when a model infers several eligible\n * providers, each is asked for its credential before the ambiguity is known, so\n * a *successful* refresh can rotate and persist a credential this command then\n * declines to emit (exit 3). See the note on the `getAuth()` call in the\n * candidate loop.\n */\n\nimport { inspect } from \"node:util\";\nimport type { Api, AuthType, Model } from \"@bastani/pi-ai\";\nimport { ModelsError } from \"@bastani/pi-ai\";\nimport { resolveCliModel } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport type { Args } from \"./args.ts\";\n\nexport type CredentialPrintKind = \"api_key\" | \"bearer_token\";\n\n/** Bearer tokens are refreshed unless they still have this much life left. */\nexport const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;\n\n/**\n * Failure taxonomy. Each member owns one exit code, so a caller can branch on\n * the status without parsing stderr.\n */\nexport type CredentialPrintErrorCode =\n\t| \"Usage\"\n\t| \"NoCredentialConfigured\"\n\t| \"ProviderAmbiguous\"\n\t| \"KindUnsupportedForProvider\"\n\t| \"RefreshFailed\"\n\t| \"MinValidityUnreachable\"\n\t| \"OAuthUnavailable\"\n\t| \"CredentialNotEmitted\"\n\t| \"CredentialTruncated\";\n\n/**\n * Exported so a test can walk the whole taxonomy: every declared code has to\n * name an exercised path, and the record type makes a new member without an\n * exit code a compile error rather than a review miss.\n *\n * Every one of these leaves stdout empty except `CredentialTruncated`, which\n * exists to report the one case where it cannot be: bytes already went out and\n * cannot be recalled. `STDOUT_EMPTY_ON_EXIT` names that split so the taxonomy\n * test asserts it rather than assuming it.\n */\nexport const EXIT_CODES: Record<CredentialPrintErrorCode, number> = {\n\tUsage: 1,\n\tNoCredentialConfigured: 2,\n\tProviderAmbiguous: 3,\n\tKindUnsupportedForProvider: 4,\n\tRefreshFailed: 5,\n\tMinValidityUnreachable: 6,\n\tOAuthUnavailable: 7,\n\tCredentialNotEmitted: 8,\n\tCredentialTruncated: 9,\n};\n\n/** The codes whose contract is an empty stdout. See `EXIT_CODES`. */\nexport const STDOUT_EMPTY_ON_EXIT: ReadonlySet<CredentialPrintErrorCode> = new Set(\n\t(Object.keys(EXIT_CODES) as CredentialPrintErrorCode[]).filter((code) => code !== \"CredentialTruncated\"),\n);\n\nexport class CredentialPrintError extends Error {\n\treadonly code: CredentialPrintErrorCode;\n\treadonly exitCode: number;\n\n\tconstructor(code: CredentialPrintErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CredentialPrintError\";\n\t\tthis.code = code;\n\t\tthis.exitCode = EXIT_CODES[code];\n\t}\n}\n\n/**\n * A credential in transit.\n *\n * Every path that would copy the value into a string is closed: `toString`,\n * `toJSON`, and `Symbol.toPrimitive` throw rather than return, so a template\n * literal, `JSON.stringify`, or string concatenation fails loudly instead of\n * leaking into a log line, a transcript, or an error message. `inspect` — which\n * `console.log` and Node's error formatting use — renders a placeholder.\n *\n * `take()` is the single exit, and it works once.\n */\nexport class Secret {\n\t#value: string | undefined;\n\n\tconstructor(value: string) {\n\t\tthis.#value = value;\n\t}\n\n\t/** Consume the secret. A second call is a bug, not a second read. */\n\ttake(): string {\n\t\tconst value = this.#value;\n\t\tif (value === undefined) {\n\t\t\tthrow new Error(\"Secret has already been consumed\");\n\t\t}\n\t\tthis.#value = undefined;\n\t\treturn value;\n\t}\n\n\ttoString(): never {\n\t\tthrow new Error(\"A Secret cannot be converted to a string; use take()\");\n\t}\n\n\ttoJSON(): never {\n\t\tthrow new Error(\"A Secret cannot be serialized; use take()\");\n\t}\n\n\t[Symbol.toPrimitive](): never {\n\t\tthrow new Error(\"A Secret cannot be interpolated; use take()\");\n\t}\n\n\t[inspect.custom](): string {\n\t\treturn \"[Secret]\";\n\t}\n}\n\n/** Public readiness fields emitted with a credential under `auth check --json --credentials`. */\nexport interface CredentialJsonFields {\n\tstatus: string;\n\tprovider: string;\n\tauthType?: string;\n}\n\n/**\n * The only function in `src` that opens a `Secret`.\n *\n * Its two `Secret.take()` calls are the only call sites in `src`, and the\n * source-wide credential-egress test pins that list. This function builds one\n * payload and returns it only to `emitCredential`; no caller receives a plain\n * credential string.\n */\nfunction credentialPayload(secret: Secret, jsonFields: CredentialJsonFields | undefined): string {\n\tif (jsonFields === undefined) return `${secret.take()}\\n`;\n\n\tconst { status, provider, authType } = jsonFields;\n\tif (\n\t\ttypeof status !== \"string\" ||\n\t\ttypeof provider !== \"string\" ||\n\t\t(authType !== undefined && typeof authType !== \"string\")\n\t) {\n\t\tthrow new Error(\"Invalid credential JSON fields\");\n\t}\n\n\t// Allowlist the non-secret envelope before opening the Secret. That leaves no\n\t// formatter, logger, or error path between take() and the guarded stdout write.\n\tconst fields = JSON.stringify({\n\t\tstatus,\n\t\tprovider,\n\t\t...(authType === undefined ? {} : { authType }),\n\t});\n\tif (fields === undefined || !fields.startsWith(\"{\") || !fields.endsWith(\"}\")) {\n\t\tthrow new Error(\"Invalid credential JSON envelope\");\n\t}\n\treturn `${fields.slice(0, -1)},\"credentials\":${JSON.stringify(secret.take())}}\\n`;\n}\n\n/**\n * The single credential egress in `src`.\n *\n * `credentialPayload` opens the secret only while building this one payload,\n * and this guarded write is the only path that hands it to real stdout. A\n * caller — `main.ts` included — receives a `Secret` it cannot read, print, or\n * serialize, so it cannot add a second export path without crossing this door.\n * `test/credential-print.test.ts` pins both the `take()` sites and every\n * data-bearing real-stdout write in `packages/coding-agent/src`.\n *\n * A failed payload write is answered from the stream rather than from the shape\n * of the error, because `bytesWritten` says how much of the credential actually\n * left and the right report differs for each amount.\n *\n * Nothing left — the write call threw, or the callback failed with the counter\n * unmoved — is `CredentialNotEmitted` (exit 8) with stdout provably empty,\n * which is what that exit promises. It must not fall through to the caller's\n * credential-resolution catch, which would report exit 2.\n *\n * All of it left and the failure came after: the caller holds the credential it\n * asked for, so this is reported on stderr with the exit code left at 0, for\n * the same reason the trailing drain is. A non-zero exit over a stream carrying\n * a whole credential is the thing this door never produces.\n *\n * Part of it left is neither. Those bytes cannot be recalled, so stdout is not\n * empty and cannot be made empty; but they are a fragment, not a credential,\n * and reporting success over them would hand a caller a truncated secret it\n * cannot tell from a whole one. That case gets `CredentialTruncated` (exit 9),\n * the one code in this taxonomy whose contract is *not* an empty stdout —\n * stated as such in `EXIT_CODES` and asserted through `STDOUT_EMPTY_ON_EXIT`,\n * rather than left for a caller to discover.\n */\nexport async function emitCredential(secret: Secret, jsonFields: CredentialJsonFields | undefined): Promise<void> {\n\tconst payload = credentialPayload(secret, jsonFields);\n\ttry {\n\t\tawait writeRawStdoutOnce(payload);\n\t} catch (error) {\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"all\") {\n\t\t\t// The caller holds the whole credential. Exiting non-zero here would be\n\t\t\t// a non-zero exit over a stream carrying it, which this door never does.\n\t\t\tconsole.error(\n\t\t\t\t`Warning: the credential reached stdout but the write did not complete cleanly: ${error.message}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"partial\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"CredentialTruncated\",\n\t\t\t\t\"Only part of the credential reached stdout; discard the output, it is not a usable credential\",\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"CredentialNotEmitted\",\n\t\t\t\"Failed to write the credential to stdout; nothing was emitted\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\ttry {\n\t\tawait flushRawStdout();\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Warning: the credential was written to stdout but the stream did not drain cleanly: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n}\n\n/**\n * The single place a thrown value becomes an exit code for this door.\n *\n * `main.ts` routes every failure through here. Every code it can produce leaves\n * stdout empty, so an exit code from this door never contradicts the stream.\n */\nexport function toCredentialPrintError(error: unknown): CredentialPrintError {\n\tif (error instanceof CredentialPrintError) return error;\n\treturn new CredentialPrintError(\n\t\t\"NoCredentialConfigured\",\n\t\terror instanceof Error ? error.message : \"Failed to resolve credential\",\n\t\t{ cause: error },\n\t);\n}\n\n/**\n * The only two fields of `Args` this door accepts.\n *\n * Validation is an allowlist rather than a list of refusals, because the\n * refusal list only held while the dispatcher happened to ignore every other\n * flag. `--export <path>`, `--session-dir <path>`, `--print`, and `--help` are\n * all parsed by `parseArgs`; under an exclusion check they passed silently and\n * the door's \"no file sink\" guarantee rested on a downstream accident.\n */\nconst ACCEPTED_ARG_FIELDS: ReadonlySet<string> = new Set([\"model\", \"provider\"]);\n\n/** Names every field of a parsed `Args` that the caller actually set. */\nfunction populatedArgFields(args: Args): string[] {\n\tconst populated: string[] = [];\n\tfor (const [field, value] of Object.entries(args)) {\n\t\tif (ACCEPTED_ARG_FIELDS.has(field) || value === undefined) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length > 0) populated.push(field);\n\t\t} else if (value instanceof Map) {\n\t\t\tif (value.size > 0) populated.push(field);\n\t\t} else {\n\t\t\tpopulated.push(field);\n\t\t}\n\t}\n\treturn populated;\n}\n\nexport function validateCredentialPrintArgs(args: Args): void {\n\tif (!args.model?.trim()) {\n\t\tthrow new CredentialPrintError(\"Usage\", \"Credential printing requires --model <model>\");\n\t}\n\tif (args.apiKey !== undefined) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t\"Credential printing reads configured credentials; --api-key is not supported\",\n\t\t);\n\t}\n\tconst refused = populatedArgFields(args);\n\tif (refused.length > 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t`Credential printing only accepts --provider and --model (refused: ${refused.join(\", \")})`,\n\t\t);\n\t}\n}\n\n/**\n * Provider-supplied text with anything credential-bearing masked.\n *\n * A failed refresh is reported on stderr, and the provider composes that\n * message. Most describe the failure; some quote the request they sent or the\n * body they got back, either of which can carry the very value this door exists\n * to keep off every stream except stdout. Masking keeps the diagnosis — which\n * is what makes the exit code actionable — without putting the secret in a log,\n * a terminal scrollback, or a CI transcript.\n *\n * Two passes, because either alone leaves a gap. Shape catches a value wherever\n * it appears, but only for the formats that announce themselves. Context\n * catches an opaque value — an `x-api-key`, which is just bytes — by the name it\n * is filed under, in the header, JSON, and query spellings a quoted request or\n * response body uses.\n */\nconst CREDENTIAL_SHAPES: readonly RegExp[] = [\n\t// `Authorization: Bearer <token>`, the form an echoed request header takes.\n\t/\\bBearer\\s+[\\w.~+/-]+=*/giu,\n\t// JWTs, which several providers return verbatim in an error body.\n\t/\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]+/gu,\n\t// Prefixed API keys: sk-…, sk_live_…, api-key-…, and the same shapes again.\n\t/\\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\\w-]{12,}/giu,\n];\n\n/**\n * Field names whose value is the credential, however opaque that value looks.\n * `x-api-key` is the case shape-matching cannot reach: the value is just bytes.\n */\nconst CREDENTIAL_FIELD_NAME =\n\t\"(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)\";\n\n/**\n * Auth schemes that stand between the field name and the value it introduces.\n *\n * Without them the header matcher stops at the space after `Bearer`: it redacts\n * the scheme and leaves the token, and having consumed the `Bearer` the shape\n * pass depends on, that pass can no longer reach the token either. An opaque\n * `Authorization: Bearer <token>` then survives both passes.\n */\nconst CREDENTIAL_AUTH_SCHEME = \"(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)\";\n\nconst CREDENTIAL_CONTEXTS: readonly RegExp[] = [\n\t// Header or YAML-ish: `x-api-key: abc123`, to end of line, and the scheme\n\t// form `Authorization: Bearer abc123` with it.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*:\\s*(?:${CREDENTIAL_AUTH_SCHEME}\\s+)?[^\\s,;}\"']+`, \"giu\"),\n\t// JSON: `\"api_key\": \"abc123\"` / `'token':'abc123'`, quoted value.\n\tnew RegExp(String.raw`([\"']?)${CREDENTIAL_FIELD_NAME}\\1\\s*:\\s*([\"'])(?:(?!\\2).)*\\2`, \"giu\"),\n\t// Query string or form body: `?api_key=abc123&…`.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*=\\s*[^\\s&,;}\"']+`, \"giu\"),\n];\n\nexport function redactCredentialShapes(text: string): string {\n\tconst byContext = CREDENTIAL_CONTEXTS.reduce(\n\t\t(masked, context) =>\n\t\t\tmasked.replace(context, (match) => {\n\t\t\t\t// Keep the field name so the diagnosis still says which one failed;\n\t\t\t\t// replace only what follows the separator.\n\t\t\t\tconst separator = /[:=]/u.exec(match);\n\t\t\t\treturn separator ? `${match.slice(0, separator.index + 1)} [redacted]` : \"[redacted]\";\n\t\t\t}),\n\t\ttext,\n\t);\n\treturn CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, \"[redacted]\"), byContext);\n}\n\n/**\n * The literal phrase pi-ai throws when a refresh itself failed, from inside\n * `credentials.modify` and therefore before anything is persisted. This is the\n * only oauth-coded error that can claim the stored credential was left alone.\n */\nexport const OAUTH_REFRESH_FAILED_PHRASE = \"OAuth refresh failed for\";\n\n/**\n * The literal phrase pi-ai throws when a refresh succeeded but the rotated\n * token still expires inside the requested window. It is the only signal that\n * separates exit 6 from exit 5.\n */\nexport const OAUTH_EXPIRES_TOO_SOON_PHRASE = \"expires too soon\";\n\n/**\n * pi-ai raises three different `oauth`-coded failures from\n * `dist/auth/resolve.js`, and only one of them is a failed refresh.\n *\n * `OAuth auth derivation failed for <provider>` is thrown after\n * `credentials.modify` has already persisted a rotated credential, and also on\n * the branch where no refresh was attempted at all — so it gets its own code\n * and a message that makes no claim about the stored credential. Treating it as\n * `RefreshFailed` asserted a rollback the command never verified.\n *\n * Classification reads the raw message, because redaction could rewrite the\n * phrase it matches on; only the text that becomes a user-facing message is\n * redacted. The unredacted error stays reachable as `cause`, which this door\n * never logs.\n *\n * `test/credential-print.test.ts` pins both phrases against the installed\n * pi-ai build, so an upstream rewording fails the suite rather than silently\n * collapsing exit 6 into exit 5.\n */\nexport function classifyOAuthFailure(error: ModelsError): CredentialPrintError {\n\tconst detail = redactCredentialShapes(error.message);\n\tif (error.message.includes(OAUTH_EXPIRES_TOO_SOON_PHRASE)) {\n\t\treturn new CredentialPrintError(\n\t\t\t\"MinValidityUnreachable\",\n\t\t\t`The provider refreshed the token but it still expires sooner than requested: ${detail}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\tif (error.message.startsWith(OAUTH_REFRESH_FAILED_PHRASE)) {\n\t\treturn new CredentialPrintError(\"RefreshFailed\", `${detail} (the stored credential was left untouched)`, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn new CredentialPrintError(\"OAuthUnavailable\", detail, { cause: error });\n}\n\n/**\n * Providers whose credential the caller could have meant.\n *\n * With `--provider` the caller named one, so failing to resolve it is an error.\n * Without it, eligibility is *not* narrowed to providers holding a persisted\n * credential: a provider authenticated by an environment variable or a custom\n * resolver has nothing in `auth.json`, and filtering on that list dropped it\n * before `getAuth()` could produce its working key. Candidacy is therefore\n * \"offers the named model\", and `getAuth()` — the same call a real request\n * makes — decides which candidate actually authenticates.\n */\nfunction candidateModels(args: Args, modelRuntime: ModelRuntime): Model<Api>[] {\n\tif (args.provider) {\n\t\tconst resolved = resolveCliModel({ cliProvider: args.provider, cliModel: args.model, modelRuntime });\n\t\tif (resolved.error || !resolved.model) {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tresolved.error ?? \"Unable to resolve the requested provider/model\",\n\t\t\t);\n\t\t}\n\t\treturn [resolved.model];\n\t}\n\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveCliModel({ cliProvider: provider.id, cliModel: args.model, modelRuntime });\n\t\tif (resolved.model && !resolved.error && !resolved.warning?.includes(\"Using custom model id\")) {\n\t\t\tmodels.push(resolved.model);\n\t\t}\n\t}\n\tif (models.length === 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`Model \"${args.model}\" not found among the available providers. Use --list-models to see available models.`,\n\t\t);\n\t}\n\treturn models;\n}\n\nfunction bearerFromHeaders(headers: Record<string, unknown> | undefined): string | undefined {\n\tconst authorization = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === \"authorization\")?.[1];\n\treturn typeof authorization === \"string\" ? /^Bearer\\s+(.+)$/iu.exec(authorization)?.[1] : undefined;\n}\n\n/**\n * Resolve exactly one credential for a named provider/model pair.\n *\n * Goes through `ModelRuntime.getAuth()`, the same request-auth path a real\n * model call uses, so an OAuth credential is refreshed and persisted by the one\n * implementation that already handles concurrent refresh under a lock.\n */\nexport async function resolveCredentialForPrint(\n\targs: Args,\n\tmodelRuntime: ModelRuntime,\n\tkind: CredentialPrintKind,\n\tminExpiryMs?: number,\n): Promise<Secret> {\n\tvalidateCredentialPrintArgs(args);\n\n\t// The effective auth type per candidate provider, taken from the runtime\n\t// rather than from auth.json.\n\t//\n\t// `checkAuth` reports what a provider would actually authenticate with,\n\t// including a credential supplied by an environment variable or a custom\n\t// resolver that persists nothing, and it answers without refreshing OAuth.\n\t// `listCredentials()` sees only what was stored, which both hid working\n\t// credentials and — for a provider offering an API key *and* OAuth — could not\n\t// say which of the two a request would use. Provider capability cannot say\n\t// either: several providers send an API key as `Authorization: Bearer`, so\n\t// neither that header nor `apiKey` identifies the credential's kind on its own.\n\tconst wantedAuthType: AuthType = kind === \"api_key\" ? \"api_key\" : \"oauth\";\n\tconst resolvedAuthTypes = new Map<string, AuthType | undefined>();\n\tconst models = candidateModels(args, modelRuntime);\n\tfor (const { provider } of models) {\n\t\tif (resolvedAuthTypes.has(provider)) continue;\n\t\tresolvedAuthTypes.set(provider, (await modelRuntime.checkAuth(provider))?.type);\n\t}\n\t// A named provider, or a single candidate, is the one the caller meant, so its\n\t// authentication failure is reported with its own exit code. Among several\n\t// inferred candidates a failure only means \"not this one\" — reporting it would\n\t// let an unrelated provider that happens to offer the model decide the exit\n\t// code for a request another candidate can satisfy.\n\tconst authFailureIsFatal = args.provider !== undefined || models.length === 1;\n\n\tconst credentials: Array<{ providerId: string; value: string }> = [];\n\t// The classified diagnosis from a candidate that could not authenticate.\n\t// Skipping a candidate must not discard why it failed: a refresh that failed,\n\t// or a token that cannot reach the requested validity, is the real answer if\n\t// nothing else produces a credential, and keeping it is what leaves exits 5\n\t// and 6 reachable instead of collapsing every inferred failure into exit 2.\n\t// It holds a `CredentialPrintError`, never a credential — the provider's text\n\t// is redacted on the way in.\n\tlet deferredDiagnosis: CredentialPrintError | undefined;\n\tfor (const model of models) {\n\t\tconst type = resolvedAuthTypes.get(model.provider);\n\t\tif (type !== wantedAuthType) continue;\n\n\t\t// Every eligible candidate is asked here, before `ProviderAmbiguous` is\n\t\t// known, so an ambiguous export can refresh and persist credentials it\n\t\t// emits nothing for. Deciding eligibility earlier is not available:\n\t\t// `checkAuth()` is the only non-mutating probe and cannot tell a candidate\n\t\t// that will authenticate from one that will fail, which is what keeps\n\t\t// exits 5 and 6 reachable. Nor does resolving without refreshing exist —\n\t\t// `resolveStoredOAuth` in `@bastani/pi-ai` refreshes whenever the\n\t\t// token falls inside `max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,\n\t\t// minOAuthValidityMs ?? 0)`, so omitting `minOAuthValidityMs` only lowers\n\t\t// that window to five minutes and drops the post-refresh check exit 6 is\n\t\t// decided by. Bounded: the refresh rotates a valid credential, it does not\n\t\t// invalidate one. Closing it needs a non-mutating probe upstream.\n\t\tlet auth: Awaited<ReturnType<ModelRuntime[\"getAuth\"]>>;\n\t\ttry {\n\t\t\tauth = await modelRuntime.getAuth(\n\t\t\t\tmodel,\n\t\t\t\tkind === \"bearer_token\" ? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS } : {},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst diagnosis =\n\t\t\t\terror instanceof ModelsError && error.code === \"oauth\" ? classifyOAuthFailure(error) : undefined;\n\t\t\tif (!authFailureIsFatal) {\n\t\t\t\tdeferredDiagnosis ??= diagnosis;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (diagnosis) throw diagnosis;\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tredactCredentialShapes(error instanceof Error ? error.message : String(error)),\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tconst value =\n\t\t\tkind === \"bearer_token\" ? (auth?.auth.apiKey ?? bearerFromHeaders(auth?.auth.headers)) : auth?.auth.apiKey;\n\t\tif (value) credentials.push({ providerId: model.provider, value });\n\t}\n\n\tif (credentials.length === 1) return new Secret(credentials[0].value);\n\n\tif (credentials.length === 0) {\n\t\tif (deferredDiagnosis) throw deferredDiagnosis;\n\t\tconst providerId = models[0]?.provider;\n\t\tconst type = providerId ? resolvedAuthTypes.get(providerId) : undefined;\n\t\tif (args.provider && kind === \"api_key\" && type === \"oauth\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is configured with OAuth, not an API key`,\n\t\t\t);\n\t\t}\n\t\tif (args.provider && kind === \"bearer_token\" && type === \"api_key\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is not configured with an OAuth bearer token`,\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`No usable ${kind === \"api_key\" ? \"API key\" : \"OAuth bearer token\"} is configured`,\n\t\t);\n\t}\n\n\tthrow new CredentialPrintError(\n\t\t\"ProviderAmbiguous\",\n\t\t`Model \"${args.model}\" has multiple configured providers (${credentials\n\t\t\t.map(({ providerId }) => providerId)\n\t\t\t.join(\", \")}). Specify --provider.`,\n\t);\n}\n"]}
1
+ {"version":3,"file":"credential-print.js","sourceRoot":"","sources":["../../src/cli/credential-print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAKlG,8EAA8E;AAC9E,MAAM,CAAC,MAAM,kCAAk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DAAgD,CACvE,CAAC;QACH,CAAC;QACD,MAAM,IAAI,oBAAoB,CAC7B,wBAAwB,EACxB,aAAa,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,oBAAoB,gBAAgB,CAClF,CAAC;IACH,CAAC;IAED,MAAM,IAAI,oBAAoB,CAC7B,mBAAmB,EACnB,UAAU,IAAI,CAAC,KAAK,wCAAwC,WAAW;SACrE,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC;SACnC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CACpC,CAAC;AACH,CAAC","sourcesContent":["/**\n * `atomic auth print-api-key` / `atomic auth print-bearer-token` and the\n * explicit `atomic auth check --credentials` export path.\n *\n * The only door in Atomic whose purpose is emitting a secret. Everything here\n * exists to keep that egress narrow:\n * - the secret leaves as a `Secret`, which cannot be interpolated, serialized,\n * or inspected, and is consumed exactly once by the stdout writer;\n * - every export has an explicit target: the print commands require `--model`,\n * and auth checks require `--provider` or an exact `--model` plus\n * `--credentials`;\n * - there is no `--output <file>` and no clipboard path — stdout only;\n * - every failure is a distinct exit code, and stdout stays empty on all of\n * them but one — `CredentialTruncated` (exit 9) exists to report the case\n * where it cannot be, because bytes already left and cannot be recalled;\n * - a failed OAuth refresh never mutates the stored credential.\n *\n * One residual, and it is upstream: when a model infers several eligible\n * providers, each is asked for its credential before the ambiguity is known, so\n * a *successful* refresh can rotate and persist a credential this command then\n * declines to emit (exit 3). See the note on the `getAuth()` call in the\n * candidate loop.\n */\n\nimport { inspect } from \"node:util\";\nimport type { Api, AuthType, Model } from \"@bastani/pi-ai\";\nimport { ModelsError } from \"@bastani/pi-ai\";\nimport { resolveCliModel } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport type { Args } from \"./args.ts\";\n\nexport type CredentialPrintKind = \"api_key\" | \"bearer_token\";\n\n/** Bearer tokens are refreshed unless they still have this much life left. */\nexport const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;\n\n/**\n * Failure taxonomy. Each member owns one exit code, so a caller can branch on\n * the status without parsing stderr.\n */\nexport type CredentialPrintErrorCode =\n\t| \"Usage\"\n\t| \"NoCredentialConfigured\"\n\t| \"ProviderAmbiguous\"\n\t| \"KindUnsupportedForProvider\"\n\t| \"RefreshFailed\"\n\t| \"MinValidityUnreachable\"\n\t| \"OAuthUnavailable\"\n\t| \"CredentialNotEmitted\"\n\t| \"CredentialTruncated\";\n\n/**\n * Exported so a test can walk the whole taxonomy: every declared code has to\n * name an exercised path, and the record type makes a new member without an\n * exit code a compile error rather than a review miss.\n *\n * Every one of these leaves stdout empty except `CredentialTruncated`, which\n * exists to report the one case where it cannot be: bytes already went out and\n * cannot be recalled. `STDOUT_EMPTY_ON_EXIT` names that split so the taxonomy\n * test asserts it rather than assuming it.\n */\nexport const EXIT_CODES: Record<CredentialPrintErrorCode, number> = {\n\tUsage: 1,\n\tNoCredentialConfigured: 2,\n\tProviderAmbiguous: 3,\n\tKindUnsupportedForProvider: 4,\n\tRefreshFailed: 5,\n\tMinValidityUnreachable: 6,\n\tOAuthUnavailable: 7,\n\tCredentialNotEmitted: 8,\n\tCredentialTruncated: 9,\n};\n\n/** The codes whose contract is an empty stdout. See `EXIT_CODES`. */\nexport const STDOUT_EMPTY_ON_EXIT: ReadonlySet<CredentialPrintErrorCode> = new Set(\n\t(Object.keys(EXIT_CODES) as CredentialPrintErrorCode[]).filter((code) => code !== \"CredentialTruncated\"),\n);\n\nexport class CredentialPrintError extends Error {\n\treadonly code: CredentialPrintErrorCode;\n\treadonly exitCode: number;\n\n\tconstructor(code: CredentialPrintErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CredentialPrintError\";\n\t\tthis.code = code;\n\t\tthis.exitCode = EXIT_CODES[code];\n\t}\n}\n\n/**\n * A credential in transit.\n *\n * Every path that would copy the value into a string is closed: `toString`,\n * `toJSON`, and `Symbol.toPrimitive` throw rather than return, so a template\n * literal, `JSON.stringify`, or string concatenation fails loudly instead of\n * leaking into a log line, a transcript, or an error message. `inspect` — which\n * `console.log` and Node's error formatting use — renders a placeholder.\n *\n * `take()` is the single exit, and it works once.\n */\nexport class Secret {\n\t#value: string | undefined;\n\n\tconstructor(value: string) {\n\t\tthis.#value = value;\n\t}\n\n\t/** Consume the secret. A second call is a bug, not a second read. */\n\ttake(): string {\n\t\tconst value = this.#value;\n\t\tif (value === undefined) {\n\t\t\tthrow new Error(\"Secret has already been consumed\");\n\t\t}\n\t\tthis.#value = undefined;\n\t\treturn value;\n\t}\n\n\ttoString(): never {\n\t\tthrow new Error(\"A Secret cannot be converted to a string; use take()\");\n\t}\n\n\ttoJSON(): never {\n\t\tthrow new Error(\"A Secret cannot be serialized; use take()\");\n\t}\n\n\t[Symbol.toPrimitive](): never {\n\t\tthrow new Error(\"A Secret cannot be interpolated; use take()\");\n\t}\n\n\t[inspect.custom](): string {\n\t\treturn \"[Secret]\";\n\t}\n}\n\n/** Public readiness fields emitted with a credential under `auth check --json --credentials`. */\nexport interface CredentialJsonFields {\n\tstatus: string;\n\tprovider: string;\n\tauthType?: string;\n}\n\n/**\n * The only function in `src` that opens a `Secret`.\n *\n * Its two `Secret.take()` calls are the only call sites in `src`, and the\n * source-wide credential-egress test pins that list. This function builds one\n * payload and returns it only to `emitCredential`; no caller receives a plain\n * credential string.\n */\nfunction credentialPayload(secret: Secret, jsonFields: CredentialJsonFields | undefined): string {\n\tif (jsonFields === undefined) return `${secret.take()}\\n`;\n\n\tconst { status, provider, authType } = jsonFields;\n\tif (\n\t\ttypeof status !== \"string\" ||\n\t\ttypeof provider !== \"string\" ||\n\t\t(authType !== undefined && typeof authType !== \"string\")\n\t) {\n\t\tthrow new Error(\"Invalid credential JSON fields\");\n\t}\n\n\t// Allowlist the non-secret envelope before opening the Secret. That leaves no\n\t// formatter, logger, or error path between take() and the guarded stdout write.\n\tconst fields = JSON.stringify({\n\t\tstatus,\n\t\tprovider,\n\t\t...(authType === undefined ? {} : { authType }),\n\t});\n\tif (fields === undefined || !fields.startsWith(\"{\") || !fields.endsWith(\"}\")) {\n\t\tthrow new Error(\"Invalid credential JSON envelope\");\n\t}\n\treturn `${fields.slice(0, -1)},\"credentials\":${JSON.stringify(secret.take())}}\\n`;\n}\n\n/**\n * The single credential egress in `src`.\n *\n * `credentialPayload` opens the secret only while building this one payload,\n * and this guarded write is the only path that hands it to real stdout. A\n * caller — `main.ts` included — receives a `Secret` it cannot read, print, or\n * serialize, so it cannot add a second export path without crossing this door.\n * `test/credential-print.test.ts` pins both the `take()` sites and every\n * data-bearing real-stdout write in `packages/coding-agent/src`.\n *\n * A failed payload write is answered from the stream rather than from the shape\n * of the error, because `bytesWritten` says how much of the credential actually\n * left and the right report differs for each amount.\n *\n * Nothing left — the write call threw, or the callback failed with the counter\n * unmoved — is `CredentialNotEmitted` (exit 8) with stdout provably empty,\n * which is what that exit promises. It must not fall through to the caller's\n * credential-resolution catch, which would report exit 2.\n *\n * All of it left and the failure came after: the caller holds the credential it\n * asked for, so this is reported on stderr with the exit code left at 0, for\n * the same reason the trailing drain is. A non-zero exit over a stream carrying\n * a whole credential is the thing this door never produces.\n *\n * Part of it left is neither. Those bytes cannot be recalled, so stdout is not\n * empty and cannot be made empty; but they are a fragment, not a credential,\n * and reporting success over them would hand a caller a truncated secret it\n * cannot tell from a whole one. That case gets `CredentialTruncated` (exit 9),\n * the one code in this taxonomy whose contract is *not* an empty stdout —\n * stated as such in `EXIT_CODES` and asserted through `STDOUT_EMPTY_ON_EXIT`,\n * rather than left for a caller to discover.\n */\nexport async function emitCredential(secret: Secret, jsonFields: CredentialJsonFields | undefined): Promise<void> {\n\tconst payload = credentialPayload(secret, jsonFields);\n\ttry {\n\t\tawait writeRawStdoutOnce(payload);\n\t} catch (error) {\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"all\") {\n\t\t\t// The caller holds the whole credential. Exiting non-zero here would be\n\t\t\t// a non-zero exit over a stream carrying it, which this door never does.\n\t\t\tconsole.error(\n\t\t\t\t`Warning: the credential reached stdout but the write did not complete cleanly: ${error.message}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"partial\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"CredentialTruncated\",\n\t\t\t\t\"Only part of the credential reached stdout; discard the output, it is not a usable credential\",\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"CredentialNotEmitted\",\n\t\t\t\"Failed to write the credential to stdout; nothing was emitted\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\ttry {\n\t\tawait flushRawStdout();\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Warning: the credential was written to stdout but the stream did not drain cleanly: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n}\n\n/**\n * The single place a thrown value becomes an exit code for this door.\n *\n * `main.ts` routes every failure through here. Every code it can produce leaves\n * stdout empty, so an exit code from this door never contradicts the stream.\n */\nexport function toCredentialPrintError(error: unknown): CredentialPrintError {\n\tif (error instanceof CredentialPrintError) return error;\n\treturn new CredentialPrintError(\n\t\t\"NoCredentialConfigured\",\n\t\terror instanceof Error ? error.message : \"Failed to resolve credential\",\n\t\t{ cause: error },\n\t);\n}\n\n/**\n * The only two fields of `Args` this door accepts.\n *\n * Validation is an allowlist rather than a list of refusals, because the\n * refusal list only held while the dispatcher happened to ignore every other\n * flag. `--export <path>`, `--session-dir <path>`, `--print`, and `--help` are\n * all parsed by `parseArgs`; under an exclusion check they passed silently and\n * the door's \"no file sink\" guarantee rested on a downstream accident.\n */\nconst ACCEPTED_ARG_FIELDS: ReadonlySet<string> = new Set([\"model\", \"provider\"]);\n\n/** Names every field of a parsed `Args` that the caller actually set. */\nfunction populatedArgFields(args: Args): string[] {\n\tconst populated: string[] = [];\n\tfor (const [field, value] of Object.entries(args)) {\n\t\tif (ACCEPTED_ARG_FIELDS.has(field) || value === undefined) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length > 0) populated.push(field);\n\t\t} else if (value instanceof Map) {\n\t\t\tif (value.size > 0) populated.push(field);\n\t\t} else {\n\t\t\tpopulated.push(field);\n\t\t}\n\t}\n\treturn populated;\n}\n\nexport function validateCredentialPrintArgs(args: Args): void {\n\tif (!args.model?.trim()) {\n\t\tthrow new CredentialPrintError(\"Usage\", \"Credential printing requires --model <model>\");\n\t}\n\tif (args.apiKey !== undefined) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t\"Credential printing reads configured credentials; --api-key is not supported\",\n\t\t);\n\t}\n\tconst refused = populatedArgFields(args);\n\tif (refused.length > 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t`Credential printing only accepts --provider and --model (refused: ${refused.join(\", \")})`,\n\t\t);\n\t}\n}\n\n/**\n * Provider-supplied text with anything credential-bearing masked.\n *\n * A failed refresh is reported on stderr, and the provider composes that\n * message. Most describe the failure; some quote the request they sent or the\n * body they got back, either of which can carry the very value this door exists\n * to keep off every stream except stdout. Masking keeps the diagnosis — which\n * is what makes the exit code actionable — without putting the secret in a log,\n * a terminal scrollback, or a CI transcript.\n *\n * Two passes, because either alone leaves a gap. Shape catches a value wherever\n * it appears, but only for the formats that announce themselves. Context\n * catches an opaque value — an `x-api-key`, which is just bytes — by the name it\n * is filed under, in the header, JSON, and query spellings a quoted request or\n * response body uses.\n */\nconst CREDENTIAL_SHAPES: readonly RegExp[] = [\n\t// `Authorization: Bearer <token>`, the form an echoed request header takes.\n\t/\\bBearer\\s+[\\w.~+/-]+=*/giu,\n\t// JWTs, which several providers return verbatim in an error body.\n\t/\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]+/gu,\n\t// Prefixed API keys: sk-…, sk_live_…, api-key-…, and the same shapes again.\n\t/\\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\\w-]{12,}/giu,\n];\n\n/**\n * Field names whose value is the credential, however opaque that value looks.\n * `x-api-key` is the case shape-matching cannot reach: the value is just bytes.\n */\nconst CREDENTIAL_FIELD_NAME =\n\t\"(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)\";\n\n/**\n * Auth schemes that stand between the field name and the value it introduces.\n *\n * Without them the header matcher stops at the space after `Bearer`: it redacts\n * the scheme and leaves the token, and having consumed the `Bearer` the shape\n * pass depends on, that pass can no longer reach the token either. An opaque\n * `Authorization: Bearer <token>` then survives both passes.\n */\nconst CREDENTIAL_AUTH_SCHEME = \"(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)\";\n\nconst CREDENTIAL_CONTEXTS: readonly RegExp[] = [\n\t// Header or YAML-ish: `x-api-key: abc123`, to end of line, and the scheme\n\t// form `Authorization: Bearer abc123` with it.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*:\\s*(?:${CREDENTIAL_AUTH_SCHEME}\\s+)?[^\\s,;}\"']+`, \"giu\"),\n\t// JSON: `\"api_key\": \"abc123\"` / `'token':'abc123'`, quoted value.\n\tnew RegExp(String.raw`([\"']?)${CREDENTIAL_FIELD_NAME}\\1\\s*:\\s*([\"'])(?:(?!\\2).)*\\2`, \"giu\"),\n\t// Query string or form body: `?api_key=abc123&…`.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*=\\s*[^\\s&,;}\"']+`, \"giu\"),\n];\n\nexport function redactCredentialShapes(text: string): string {\n\tconst byContext = CREDENTIAL_CONTEXTS.reduce(\n\t\t(masked, context) =>\n\t\t\tmasked.replace(context, (match) => {\n\t\t\t\t// Keep the field name so the diagnosis still says which one failed;\n\t\t\t\t// replace only what follows the separator.\n\t\t\t\tconst separator = /[:=]/u.exec(match);\n\t\t\t\treturn separator ? `${match.slice(0, separator.index + 1)} [redacted]` : \"[redacted]\";\n\t\t\t}),\n\t\ttext,\n\t);\n\treturn CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, \"[redacted]\"), byContext);\n}\n\n/**\n * The literal phrase pi-ai throws when a refresh itself failed, from inside\n * `credentials.modify` and therefore before anything is persisted. This is the\n * only oauth-coded error that can claim the stored credential was left alone.\n */\nexport const OAUTH_REFRESH_FAILED_PHRASE = \"OAuth refresh failed for\";\n\n/**\n * The literal phrase pi-ai throws when a refresh succeeded but the rotated\n * token still expires inside the requested window. It is the only signal that\n * separates exit 6 from exit 5.\n */\nexport const OAUTH_EXPIRES_TOO_SOON_PHRASE = \"expires too soon\";\n\n/**\n * pi-ai raises three different `oauth`-coded failures from\n * `dist/auth/resolve.js`, and only one of them is a failed refresh.\n *\n * `OAuth auth derivation failed for <provider>` is thrown after\n * `credentials.modify` has already persisted a rotated credential, and also on\n * the branch where no refresh was attempted at all — so it gets its own code\n * and a message that makes no claim about the stored credential. Treating it as\n * `RefreshFailed` asserted a rollback the command never verified.\n *\n * Classification reads the raw message, because redaction could rewrite the\n * phrase it matches on; only the text that becomes a user-facing message is\n * redacted. The unredacted error stays reachable as `cause`, which this door\n * never logs.\n *\n * `test/credential-print.test.ts` pins both phrases against the installed\n * pi-ai build, so an upstream rewording fails the suite rather than silently\n * collapsing exit 6 into exit 5.\n */\nexport function classifyOAuthFailure(error: ModelsError): CredentialPrintError {\n\tconst detail = redactCredentialShapes(error.message);\n\tif (error.message.includes(OAUTH_EXPIRES_TOO_SOON_PHRASE)) {\n\t\treturn new CredentialPrintError(\n\t\t\t\"MinValidityUnreachable\",\n\t\t\t`The provider refreshed the token but it still expires sooner than requested: ${detail}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\tif (error.message.startsWith(OAUTH_REFRESH_FAILED_PHRASE)) {\n\t\treturn new CredentialPrintError(\"RefreshFailed\", `${detail} (the stored credential was left untouched)`, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn new CredentialPrintError(\"OAuthUnavailable\", detail, { cause: error });\n}\n\n/**\n * Providers whose credential the caller could have meant.\n *\n * With `--provider` the caller named one, so failing to resolve it is an error.\n * Without it, eligibility is *not* narrowed to providers holding a persisted\n * credential: a provider authenticated by an environment variable or a custom\n * resolver has nothing in `auth.json`, and filtering on that list dropped it\n * before `getAuth()` could produce its working key. Candidacy is therefore\n * \"offers the named model\", and `getAuth()` — the same call a real request\n * makes — decides which candidate actually authenticates.\n */\nfunction candidateModels(args: Args, modelRuntime: ModelRuntime): Model<Api>[] {\n\tif (args.provider) {\n\t\tconst resolved = resolveCliModel({ cliProvider: args.provider, cliModel: args.model, modelRuntime });\n\t\tif (resolved.error || !resolved.model) {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tresolved.error ?? \"Unable to resolve the requested provider/model\",\n\t\t\t);\n\t\t}\n\t\treturn [resolved.model];\n\t}\n\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveCliModel({ cliProvider: provider.id, cliModel: args.model, modelRuntime });\n\t\tif (resolved.model && !resolved.error && !resolved.warning?.includes(\"Using custom model id\")) {\n\t\t\tmodels.push(resolved.model);\n\t\t}\n\t}\n\tif (models.length === 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`Model \"${args.model}\" not found among the available providers. Use --list-models to see available models.`,\n\t\t);\n\t}\n\treturn models;\n}\n\nfunction bearerFromHeaders(headers: Record<string, unknown> | undefined): string | undefined {\n\tconst authorization = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === \"authorization\")?.[1];\n\treturn typeof authorization === \"string\" ? /^Bearer\\s+(.+)$/iu.exec(authorization)?.[1] : undefined;\n}\n\n/**\n * Resolve exactly one credential for a named provider/model pair.\n *\n * Goes through `ModelRuntime.getAuth()`, the same request-auth path a real\n * model call uses, so an OAuth credential is refreshed and persisted by the one\n * implementation that already handles concurrent refresh under a lock.\n */\nexport async function resolveCredentialForPrint(\n\targs: Args,\n\tmodelRuntime: ModelRuntime,\n\tkind: CredentialPrintKind,\n\tminExpiryMs?: number,\n): Promise<Secret> {\n\tvalidateCredentialPrintArgs(args);\n\n\t// The effective auth type per candidate provider, taken from the runtime\n\t// rather than from auth.json.\n\t//\n\t// `checkAuth` reports what a provider would actually authenticate with,\n\t// including a credential supplied by an environment variable or a custom\n\t// resolver that persists nothing, and it answers without refreshing OAuth.\n\t// `listCredentials()` sees only what was stored, which both hid working\n\t// credentials and — for a provider offering an API key *and* OAuth — could not\n\t// say which of the two a request would use. Provider capability cannot say\n\t// either: several providers send an API key as `Authorization: Bearer`, so\n\t// neither that header nor `apiKey` identifies the credential's kind on its own.\n\tconst wantedAuthType: AuthType = kind === \"api_key\" ? \"api_key\" : \"oauth\";\n\tconst resolvedAuthTypes = new Map<string, AuthType | undefined>();\n\tconst models = candidateModels(args, modelRuntime);\n\tfor (const { provider } of models) {\n\t\tif (resolvedAuthTypes.has(provider)) continue;\n\t\tresolvedAuthTypes.set(provider, (await modelRuntime.checkAuth(provider))?.type);\n\t}\n\t// A named provider, or a single candidate, is the one the caller meant, so its\n\t// authentication failure is reported with its own exit code. Among several\n\t// inferred candidates a failure only means \"not this one\" — reporting it would\n\t// let an unrelated provider that happens to offer the model decide the exit\n\t// code for a request another candidate can satisfy.\n\tconst authFailureIsFatal = args.provider !== undefined || models.length === 1;\n\n\tconst credentials: Array<{ providerId: string; value: string }> = [];\n\t// The classified diagnosis from a candidate that could not authenticate.\n\t// Skipping a candidate must not discard why it failed: a refresh that failed,\n\t// or a token that cannot reach the requested validity, is the real answer if\n\t// nothing else produces a credential, and keeping it is what leaves exits 5\n\t// and 6 reachable instead of collapsing every inferred failure into exit 2.\n\t// It holds a `CredentialPrintError`, never a credential — the provider's text\n\t// is redacted on the way in.\n\tlet deferredDiagnosis: CredentialPrintError | undefined;\n\tfor (const model of models) {\n\t\tconst type = resolvedAuthTypes.get(model.provider);\n\t\tif (type !== wantedAuthType) continue;\n\n\t\t// Every eligible candidate is asked here, before `ProviderAmbiguous` is\n\t\t// known, so an ambiguous export can refresh and persist credentials it\n\t\t// emits nothing for. Deciding eligibility earlier is not available:\n\t\t// `checkAuth()` is the only non-mutating probe and cannot tell a candidate\n\t\t// that will authenticate from one that will fail, which is what keeps\n\t\t// exits 5 and 6 reachable. Nor does resolving without refreshing exist —\n\t\t// `resolveStoredOAuth` in `@bastani/pi-ai` refreshes whenever the\n\t\t// token falls inside `max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,\n\t\t// minOAuthValidityMs ?? 0)`, so omitting `minOAuthValidityMs` only lowers\n\t\t// that window to five minutes and drops the post-refresh check exit 6 is\n\t\t// decided by. Bounded: the refresh rotates a valid credential, it does not\n\t\t// invalidate one. Closing it needs a non-mutating probe upstream.\n\t\tlet auth: Awaited<ReturnType<ModelRuntime[\"getAuth\"]>>;\n\t\ttry {\n\t\t\tauth = await modelRuntime.getAuth(\n\t\t\t\tmodel,\n\t\t\t\tkind === \"bearer_token\" ? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS } : {},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst diagnosis =\n\t\t\t\terror instanceof ModelsError && error.code === \"oauth\" ? classifyOAuthFailure(error) : undefined;\n\t\t\tif (!authFailureIsFatal) {\n\t\t\t\tdeferredDiagnosis ??= diagnosis;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (diagnosis) throw diagnosis;\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tredactCredentialShapes(error instanceof Error ? error.message : String(error)),\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tconst value =\n\t\t\tkind === \"bearer_token\" ? (auth?.auth.apiKey ?? bearerFromHeaders(auth?.auth.headers)) : auth?.auth.apiKey;\n\t\tif (value) credentials.push({ providerId: model.provider, value });\n\t}\n\n\tif (credentials.length === 1) return new Secret(credentials[0].value);\n\n\tif (credentials.length === 0) {\n\t\tif (deferredDiagnosis) throw deferredDiagnosis;\n\t\tconst providerId = models[0]?.provider;\n\t\tconst type = providerId ? resolvedAuthTypes.get(providerId) : undefined;\n\t\tif (args.provider && kind === \"api_key\" && type === \"oauth\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is configured with OAuth, not an API key`,\n\t\t\t);\n\t\t}\n\t\tif (args.provider && kind === \"bearer_token\" && type === \"api_key\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is not configured with an OAuth bearer token`,\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`No usable ${kind === \"api_key\" ? \"API key\" : \"OAuth bearer token\"} is configured`,\n\t\t);\n\t}\n\n\tthrow new CredentialPrintError(\n\t\t\"ProviderAmbiguous\",\n\t\t`Model \"${args.model}\" has multiple configured providers (${credentials\n\t\t\t.map(({ providerId }) => providerId)\n\t\t\t.join(\", \")}). Specify --provider.`,\n\t);\n}\n"]}
@@ -5,9 +5,12 @@ export function stringOption(name) {
5
5
  return valueOption(name, (value) => ({ ok: true, value }));
6
6
  }
7
7
  export class Command {
8
+ name;
9
+ options = new Map();
10
+ subcommands = new Map();
11
+ builder;
12
+ commandAction;
8
13
  constructor(name) {
9
- this.options = new Map();
10
- this.subcommands = new Map();
11
14
  this.name = name;
12
15
  }
13
16
  option(option) {
@@ -1 +1 @@
1
- {"version":3,"file":"command.js","sourceRoot":"","sources":["../../../src/cli/experimental/command.ts"],"names":[],"mappings":"AAqBA,MAAM,UAAU,WAAW,CAC1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AC;YACnE,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACzB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;gBAC7B,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;oBACjD,KAAK,GAAG,IAAI,CAAC;oBACb,KAAK,EAAE,CAAC;gBACT,CAAC;YACF,CAAC;YACD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,EAAE,CAAC;gBACzC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,mBAAmB,CAAC,CAAC;gBAC/C,SAAS;YACV,CAAC;YAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YAC7C,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,6BAA6B,CAAC,CAAC;gBACzD,SAAS;YACV,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;gBAChB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACjC,SAAS;YACV,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC1B,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACjC,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["export interface NamedCommandInvocation {\n\treadonly command: string;\n}\n\nexport type CommandParseResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandExecutionResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandOptionParseResult<TValue> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| { readonly ok: false; readonly error: string };\n\nexport interface CommandOption<TValue> {\n\treadonly name: `--${string}`;\n\tparse(value: string): CommandOptionParseResult<TValue>;\n}\n\nexport function valueOption<TValue>(\n\tname: `--${string}`,\n\tparse: (value: string) => CommandOptionParseResult<TValue>,\n): CommandOption<TValue> {\n\treturn { name, parse };\n}\n\nexport function stringOption(name: `--${string}`): CommandOption<string> {\n\treturn valueOption(name, (value) => ({ ok: true, value }));\n}\n\nexport interface ParsedCommandInput {\n\treadonly remainingArgs: readonly string[];\n\tvalue<TValue>(option: CommandOption<TValue>): TValue | undefined;\n\tvalues<TValue>(option: CommandOption<TValue>): readonly TValue[];\n}\n\nexport type CommandBuildResult<TInvocation extends NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\ninterface MutableParsedCommandInput {\n\treadonly values: Map<string, unknown[]>;\n\treadonly remainingArgs: string[];\n\treadonly errors: string[];\n}\n\ntype CommandBuilder<TInvocation extends NamedCommandInvocation> = (\n\tinput: ParsedCommandInput,\n) => CommandBuildResult<TInvocation>;\n\ntype CommandAction<TInvocation extends NamedCommandInvocation, TContext> = (\n\tcommand: TInvocation,\n\tcontext: TContext,\n) => void | Promise<void>;\n\ninterface RegisteredCommand {\n\tparse(argv: readonly string[]): CommandParseResult;\n\texecute(argv: readonly string[], context: unknown): Promise<CommandExecutionResult>;\n}\n\nexport class Command<\n\tTOwnInvocation extends NamedCommandInvocation,\n\tTContext,\n\tTInvocation extends NamedCommandInvocation = TOwnInvocation,\n> {\n\treadonly name: string;\n\tprivate readonly options = new Map<string, CommandOption<unknown>>();\n\tprivate readonly subcommands = new Map<string, RegisteredCommand>();\n\tprivate builder?: CommandBuilder<TOwnInvocation>;\n\tprivate commandAction?: CommandAction<TOwnInvocation, TContext>;\n\n\tconstructor(name: string) {\n\t\tthis.name = name;\n\t}\n\n\toption<TValue>(option: CommandOption<TValue>): this {\n\t\tif (this.options.has(option.name)) {\n\t\t\tthrow new Error(`Option ${option.name} is already registered for ${this.name}`);\n\t\t}\n\t\tthis.options.set(option.name, option);\n\t\treturn this;\n\t}\n\n\tbuild(builder: CommandBuilder<TOwnInvocation>): this {\n\t\tthis.builder = builder;\n\t\treturn this;\n\t}\n\n\taction(action: CommandAction<TOwnInvocation, TContext>): this {\n\t\tthis.commandAction = action;\n\t\treturn this;\n\t}\n\n\tcommand<\n\t\tTSubcommandOwnInvocation extends NamedCommandInvocation,\n\t\tTSubcommandContext,\n\t\tTSubcommandInvocation extends NamedCommandInvocation,\n\t>(\n\t\tcommand: Command<TSubcommandOwnInvocation, TSubcommandContext, TSubcommandInvocation>,\n\t): Command<TOwnInvocation, TContext & TSubcommandContext, TInvocation | TSubcommandInvocation> {\n\t\tif (this.subcommands.has(command.name)) throw new Error(`Command ${command.name} is already registered`);\n\t\tthis.subcommands.set(command.name, {\n\t\t\tparse: (argv) => command.parse(argv),\n\t\t\texecute: (argv, context) => command.execute(argv, context as TSubcommandContext),\n\t\t});\n\t\treturn this as unknown as Command<\n\t\t\tTOwnInvocation,\n\t\t\tTContext & TSubcommandContext,\n\t\t\tTInvocation | TSubcommandInvocation\n\t\t>;\n\t}\n\n\tparse(argv: readonly string[]): CommandParseResult<TInvocation> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) return selected.command.parse(selected.argv) as CommandParseResult<TInvocation>;\n\t\treturn this.parseOwn(argv) as CommandParseResult<TInvocation>;\n\t}\n\n\tasync execute(argv: readonly string[], context: TContext): Promise<CommandExecutionResult<TInvocation>> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) {\n\t\t\treturn selected.command.execute(selected.argv, context) as Promise<CommandExecutionResult<TInvocation>>;\n\t\t}\n\n\t\tconst parsed = this.parseOwn(argv);\n\t\tif (!parsed.ok) return parsed;\n\t\tif (!this.commandAction) throw new Error(`Command ${this.name} does not define an action`);\n\t\tawait this.commandAction(parsed.command, context);\n\t\treturn { ok: true, command: parsed.command as unknown as TInvocation };\n\t}\n\n\tprivate select(argv: readonly string[]): { command: RegisteredCommand; argv: readonly string[] } | undefined {\n\t\tconst candidate = argv[0];\n\t\tif (candidate === undefined) return undefined;\n\t\tconst command = this.subcommands.get(candidate);\n\t\treturn command ? { command, argv: argv.slice(1) } : undefined;\n\t}\n\n\tprivate parseOwn(argv: readonly string[]): CommandParseResult<TOwnInvocation> {\n\t\tif (!this.builder) throw new Error(`Command ${this.name} does not define a builder`);\n\t\tconst parsed = this.parseOptions(argv);\n\t\tconst input: ParsedCommandInput = {\n\t\t\tremainingArgs: parsed.remainingArgs,\n\t\t\tvalue: <TValue>(option: CommandOption<TValue>) => parsed.values.get(option.name)?.[0] as TValue | undefined,\n\t\t\tvalues: <TValue>(option: CommandOption<TValue>) => (parsed.values.get(option.name) ?? []) as readonly TValue[],\n\t\t};\n\t\tconst built = this.builder(input);\n\t\tconst errors = [...parsed.errors, ...(built.ok ? [] : built.errors)];\n\t\tif (errors.length > 0) return { ok: false, errors };\n\t\tif (!built.ok) throw new Error(`Command ${this.name} failed without an error`);\n\t\treturn { ok: true, command: built.command };\n\t}\n\n\tprivate parseOptions(argv: readonly string[]): MutableParsedCommandInput {\n\t\tconst parsed: MutableParsedCommandInput = {\n\t\t\tvalues: new Map(),\n\t\t\tremainingArgs: [],\n\t\t\terrors: [],\n\t\t};\n\t\tfor (let index = 0; index < argv.length; index++) {\n\t\t\tconst argument = argv[index]!;\n\t\t\tif (argument === \"--\") {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst equals = argument.indexOf(\"=\");\n\t\t\tconst name = equals === -1 ? argument : argument.slice(0, equals);\n\t\t\tconst option = this.options.get(name);\n\t\t\tif (!option) {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet value = equals === -1 ? undefined : argument.slice(equals + 1);\n\t\t\tif (value === undefined) {\n\t\t\t\tconst next = argv[index + 1];\n\t\t\t\tif (next !== undefined && !next.startsWith(\"-\")) {\n\t\t\t\t\tvalue = next;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (value === undefined || value === \"\") {\n\t\t\t\tparsed.errors.push(`${name} requires a value`);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst values = parsed.values.get(name) ?? [];\n\t\t\tif (values.length > 0) {\n\t\t\t\tparsed.errors.push(`${name} may only be specified once`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = option.parse(value);\n\t\t\tif (!result.ok) {\n\t\t\t\tparsed.errors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalues.push(result.value);\n\t\t\tparsed.values.set(name, values);\n\t\t}\n\t\treturn parsed;\n\t}\n}\n"]}
1
+ {"version":3,"file":"command.js","sourceRoot":"","sources":["../../../src/cli/experimental/command.ts"],"names":[],"mappings":"AAqBA,MAAM,UAAU,WAAW,CAC1B,IAAmB,EACnB,KAA0D;IAE1D,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AACxB,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,IAAmB;IAC/C,OAAO,WAAW,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;AAC5D,CAAC;AAgCD,MAAM,OAAO,OAAO;IAKV,IAAI,CAAS;IACL,OAAO,GAAG,IAAI,GAAG,EAAkC,CAAC;IACpD,WAAW,GAAG,IAAI,GAAG,EAA6B,CAAC;IAC5D,OAAO,CAAkC;IACzC,aAAa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M,CAAC,IAAI,CAAC,GAAG,IAAI,mBAAmB,CAAC,CAAC;gBAC/C,SAAS;YACV,CAAC;YAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YAC7C,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,6BAA6B,CAAC,CAAC;gBACzD,SAAS;YACV,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACnC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;gBAChB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACjC,SAAS;YACV,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC1B,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACjC,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC;CACD","sourcesContent":["export interface NamedCommandInvocation {\n\treadonly command: string;\n}\n\nexport type CommandParseResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandExecutionResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\nexport type CommandOptionParseResult<TValue> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| { readonly ok: false; readonly error: string };\n\nexport interface CommandOption<TValue> {\n\treadonly name: `--${string}`;\n\tparse(value: string): CommandOptionParseResult<TValue>;\n}\n\nexport function valueOption<TValue>(\n\tname: `--${string}`,\n\tparse: (value: string) => CommandOptionParseResult<TValue>,\n): CommandOption<TValue> {\n\treturn { name, parse };\n}\n\nexport function stringOption(name: `--${string}`): CommandOption<string> {\n\treturn valueOption(name, (value) => ({ ok: true, value }));\n}\n\nexport interface ParsedCommandInput {\n\treadonly remainingArgs: readonly string[];\n\tvalue<TValue>(option: CommandOption<TValue>): TValue | undefined;\n\tvalues<TValue>(option: CommandOption<TValue>): readonly TValue[];\n}\n\nexport type CommandBuildResult<TInvocation extends NamedCommandInvocation> =\n\t| { readonly ok: true; readonly command: TInvocation }\n\t| { readonly ok: false; readonly errors: readonly string[] };\n\ninterface MutableParsedCommandInput {\n\treadonly values: Map<string, unknown[]>;\n\treadonly remainingArgs: string[];\n\treadonly errors: string[];\n}\n\ntype CommandBuilder<TInvocation extends NamedCommandInvocation> = (\n\tinput: ParsedCommandInput,\n) => CommandBuildResult<TInvocation>;\n\ntype CommandAction<TInvocation extends NamedCommandInvocation, TContext> = (\n\tcommand: TInvocation,\n\tcontext: TContext,\n) => void | Promise<void>;\n\ninterface RegisteredCommand {\n\tparse(argv: readonly string[]): CommandParseResult;\n\texecute(argv: readonly string[], context: unknown): Promise<CommandExecutionResult>;\n}\n\nexport class Command<\n\tTOwnInvocation extends NamedCommandInvocation,\n\tTContext,\n\tTInvocation extends NamedCommandInvocation = TOwnInvocation,\n> {\n\treadonly name: string;\n\tprivate readonly options = new Map<string, CommandOption<unknown>>();\n\tprivate readonly subcommands = new Map<string, RegisteredCommand>();\n\tprivate builder?: CommandBuilder<TOwnInvocation>;\n\tprivate commandAction?: CommandAction<TOwnInvocation, TContext>;\n\n\tconstructor(name: string) {\n\t\tthis.name = name;\n\t}\n\n\toption<TValue>(option: CommandOption<TValue>): this {\n\t\tif (this.options.has(option.name)) {\n\t\t\tthrow new Error(`Option ${option.name} is already registered for ${this.name}`);\n\t\t}\n\t\tthis.options.set(option.name, option);\n\t\treturn this;\n\t}\n\n\tbuild(builder: CommandBuilder<TOwnInvocation>): this {\n\t\tthis.builder = builder;\n\t\treturn this;\n\t}\n\n\taction(action: CommandAction<TOwnInvocation, TContext>): this {\n\t\tthis.commandAction = action;\n\t\treturn this;\n\t}\n\n\tcommand<\n\t\tTSubcommandOwnInvocation extends NamedCommandInvocation,\n\t\tTSubcommandContext,\n\t\tTSubcommandInvocation extends NamedCommandInvocation,\n\t>(\n\t\tcommand: Command<TSubcommandOwnInvocation, TSubcommandContext, TSubcommandInvocation>,\n\t): Command<TOwnInvocation, TContext & TSubcommandContext, TInvocation | TSubcommandInvocation> {\n\t\tif (this.subcommands.has(command.name)) throw new Error(`Command ${command.name} is already registered`);\n\t\tthis.subcommands.set(command.name, {\n\t\t\tparse: (argv) => command.parse(argv),\n\t\t\texecute: (argv, context) => command.execute(argv, context as TSubcommandContext),\n\t\t});\n\t\treturn this as unknown as Command<\n\t\t\tTOwnInvocation,\n\t\t\tTContext & TSubcommandContext,\n\t\t\tTInvocation | TSubcommandInvocation\n\t\t>;\n\t}\n\n\tparse(argv: readonly string[]): CommandParseResult<TInvocation> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) return selected.command.parse(selected.argv) as CommandParseResult<TInvocation>;\n\t\treturn this.parseOwn(argv) as CommandParseResult<TInvocation>;\n\t}\n\n\tasync execute(argv: readonly string[], context: TContext): Promise<CommandExecutionResult<TInvocation>> {\n\t\tconst selected = this.select(argv);\n\t\tif (selected) {\n\t\t\treturn selected.command.execute(selected.argv, context) as Promise<CommandExecutionResult<TInvocation>>;\n\t\t}\n\n\t\tconst parsed = this.parseOwn(argv);\n\t\tif (!parsed.ok) return parsed;\n\t\tif (!this.commandAction) throw new Error(`Command ${this.name} does not define an action`);\n\t\tawait this.commandAction(parsed.command, context);\n\t\treturn { ok: true, command: parsed.command as unknown as TInvocation };\n\t}\n\n\tprivate select(argv: readonly string[]): { command: RegisteredCommand; argv: readonly string[] } | undefined {\n\t\tconst candidate = argv[0];\n\t\tif (candidate === undefined) return undefined;\n\t\tconst command = this.subcommands.get(candidate);\n\t\treturn command ? { command, argv: argv.slice(1) } : undefined;\n\t}\n\n\tprivate parseOwn(argv: readonly string[]): CommandParseResult<TOwnInvocation> {\n\t\tif (!this.builder) throw new Error(`Command ${this.name} does not define a builder`);\n\t\tconst parsed = this.parseOptions(argv);\n\t\tconst input: ParsedCommandInput = {\n\t\t\tremainingArgs: parsed.remainingArgs,\n\t\t\tvalue: <TValue>(option: CommandOption<TValue>) => parsed.values.get(option.name)?.[0] as TValue | undefined,\n\t\t\tvalues: <TValue>(option: CommandOption<TValue>) => (parsed.values.get(option.name) ?? []) as readonly TValue[],\n\t\t};\n\t\tconst built = this.builder(input);\n\t\tconst errors = [...parsed.errors, ...(built.ok ? [] : built.errors)];\n\t\tif (errors.length > 0) return { ok: false, errors };\n\t\tif (!built.ok) throw new Error(`Command ${this.name} failed without an error`);\n\t\treturn { ok: true, command: built.command };\n\t}\n\n\tprivate parseOptions(argv: readonly string[]): MutableParsedCommandInput {\n\t\tconst parsed: MutableParsedCommandInput = {\n\t\t\tvalues: new Map(),\n\t\t\tremainingArgs: [],\n\t\t\terrors: [],\n\t\t};\n\t\tfor (let index = 0; index < argv.length; index++) {\n\t\t\tconst argument = argv[index]!;\n\t\t\tif (argument === \"--\") {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst equals = argument.indexOf(\"=\");\n\t\t\tconst name = equals === -1 ? argument : argument.slice(0, equals);\n\t\t\tconst option = this.options.get(name);\n\t\t\tif (!option) {\n\t\t\t\tparsed.remainingArgs.push(...argv.slice(index));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlet value = equals === -1 ? undefined : argument.slice(equals + 1);\n\t\t\tif (value === undefined) {\n\t\t\t\tconst next = argv[index + 1];\n\t\t\t\tif (next !== undefined && !next.startsWith(\"-\")) {\n\t\t\t\t\tvalue = next;\n\t\t\t\t\tindex++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (value === undefined || value === \"\") {\n\t\t\t\tparsed.errors.push(`${name} requires a value`);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst values = parsed.values.get(name) ?? [];\n\t\t\tif (values.length > 0) {\n\t\t\t\tparsed.errors.push(`${name} may only be specified once`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = option.parse(value);\n\t\t\tif (!result.ok) {\n\t\t\t\tparsed.errors.push(result.error);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvalues.push(result.value);\n\t\t\tparsed.values.set(name, values);\n\t\t}\n\t\treturn parsed;\n\t}\n}\n"]}
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * CLI entry point for the refactored coding agent.
4
4
  * Uses main.ts with AgentSession and new mode modules.
5
5
  *
6
- * Test with: npx tsx src/cli-new.ts [args...]
6
+ * Test with: bun src/cli.ts [args...]
7
7
  *
8
8
  * Deliberately keeps the static entry graph to config, compile-cache support,
9
9
  * attribution, and the disabled-by-default lifecycle seam. The full CLI graph