@bastani/atomic 0.9.40-alpha.2 → 0.9.41-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +1 -1
  3. package/dist/builtin/intercom/CHANGELOG.md +26 -0
  4. package/dist/builtin/intercom/README.md +1 -1
  5. package/dist/builtin/intercom/broker/broker.ts +24 -21
  6. package/dist/builtin/intercom/broker/client.ts +97 -6
  7. package/dist/builtin/intercom/broker/list-reply.ts +53 -0
  8. package/dist/builtin/intercom/index.bundle.mjs +278 -46
  9. package/dist/builtin/intercom/package.json +1 -1
  10. package/dist/builtin/intercom/recoverable-disconnect.ts +27 -1
  11. package/dist/builtin/intercom/types.ts +8 -1
  12. package/dist/builtin/mcp/package.json +1 -1
  13. package/dist/builtin/subagents/CHANGELOG.md +45 -0
  14. package/dist/builtin/subagents/README.md +14 -0
  15. package/dist/builtin/subagents/package.json +1 -1
  16. package/dist/builtin/subagents/src/extension/index.bundle.mjs +99 -19
  17. package/dist/builtin/web-access/CHANGELOG.md +6 -0
  18. package/dist/builtin/web-access/package.json +1 -1
  19. package/dist/builtin/workflows/CHANGELOG.md +44 -0
  20. package/dist/builtin/workflows/README.md +2 -0
  21. package/dist/builtin/workflows/package.json +1 -1
  22. package/dist/builtin/workflows/src/authoring.d.ts +1 -1
  23. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +16 -0
  24. package/dist/builtin/workflows/src/durable/journal/legacy-journal-tables.d.ts +9 -0
  25. package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +6 -0
  26. package/dist/builtin/workflows/src/extension/index.bundle.mjs +441 -90
  27. package/dist/builtin/workflows/src/index.js +226 -34
  28. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +17 -1
  29. package/dist/cli/credential-print.d.ts.map +1 -1
  30. package/dist/cli/credential-print.js +1 -1
  31. package/dist/cli/credential-print.js.map +1 -1
  32. package/dist/config.d.ts +1 -0
  33. package/dist/config.d.ts.map +1 -1
  34. package/dist/config.js +1 -0
  35. package/dist/config.js.map +1 -1
  36. package/dist/core/agent-session-extension-bindings.d.ts +2 -1
  37. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  38. package/dist/core/agent-session-extension-bindings.js +33 -18
  39. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  40. package/dist/core/agent-session-methods.d.ts +2 -1
  41. package/dist/core/agent-session-methods.d.ts.map +1 -1
  42. package/dist/core/agent-session-methods.js.map +1 -1
  43. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  44. package/dist/core/agent-session-prompt.js +114 -21
  45. package/dist/core/agent-session-prompt.js.map +1 -1
  46. package/dist/core/agent-session-runtime.d.ts +1 -1
  47. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  48. package/dist/core/agent-session-runtime.js +6 -0
  49. package/dist/core/agent-session-runtime.js.map +1 -1
  50. package/dist/core/agent-session-state.d.ts +19 -1
  51. package/dist/core/agent-session-state.d.ts.map +1 -1
  52. package/dist/core/agent-session-state.js +41 -6
  53. package/dist/core/agent-session-state.js.map +1 -1
  54. package/dist/core/auth-storage-backends.d.ts +3 -1
  55. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  56. package/dist/core/auth-storage-backends.js +79 -12
  57. package/dist/core/auth-storage-backends.js.map +1 -1
  58. package/dist/core/client-identity.d.ts +8 -0
  59. package/dist/core/client-identity.d.ts.map +1 -0
  60. package/dist/core/client-identity.js +16 -0
  61. package/dist/core/client-identity.js.map +1 -0
  62. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  63. package/dist/core/compaction/planner-outcome.js +2 -1
  64. package/dist/core/compaction/planner-outcome.js.map +1 -1
  65. package/dist/core/execution-model-router.d.ts +18 -0
  66. package/dist/core/execution-model-router.d.ts.map +1 -1
  67. package/dist/core/execution-model-router.js +14 -8
  68. package/dist/core/execution-model-router.js.map +1 -1
  69. package/dist/core/extension-oauth-refresh-rejection.d.ts +12 -0
  70. package/dist/core/extension-oauth-refresh-rejection.d.ts.map +1 -0
  71. package/dist/core/extension-oauth-refresh-rejection.js +70 -0
  72. package/dist/core/extension-oauth-refresh-rejection.js.map +1 -0
  73. package/dist/core/extension-startup-failure.d.ts +30 -0
  74. package/dist/core/extension-startup-failure.d.ts.map +1 -0
  75. package/dist/core/extension-startup-failure.js +62 -0
  76. package/dist/core/extension-startup-failure.js.map +1 -0
  77. package/dist/core/extensions/context-types.d.ts +2 -0
  78. package/dist/core/extensions/context-types.d.ts.map +1 -1
  79. package/dist/core/extensions/context-types.js.map +1 -1
  80. package/dist/core/extensions/provider-types.d.ts +2 -0
  81. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  82. package/dist/core/extensions/provider-types.js.map +1 -1
  83. package/dist/core/extensions/runner-context.d.ts +1 -0
  84. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  85. package/dist/core/extensions/runner-context.js +8 -0
  86. package/dist/core/extensions/runner-context.js.map +1 -1
  87. package/dist/core/extensions/runner.d.ts +1 -0
  88. package/dist/core/extensions/runner.d.ts.map +1 -1
  89. package/dist/core/extensions/runner.js +3 -0
  90. package/dist/core/extensions/runner.js.map +1 -1
  91. package/dist/core/extensions/runtime-types.d.ts +1 -0
  92. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  93. package/dist/core/extensions/runtime-types.js.map +1 -1
  94. package/dist/core/extensions/workflow-run-control-hub.d.ts +1 -0
  95. package/dist/core/extensions/workflow-run-control-hub.d.ts.map +1 -1
  96. package/dist/core/extensions/workflow-run-control-hub.js +3 -0
  97. package/dist/core/extensions/workflow-run-control-hub.js.map +1 -1
  98. package/dist/core/extensions/workflow-run-control.d.ts +8 -0
  99. package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
  100. package/dist/core/extensions/workflow-run-control.js.map +1 -1
  101. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  102. package/dist/core/model-fallback-failures.js +12 -0
  103. package/dist/core/model-fallback-failures.js.map +1 -1
  104. package/dist/core/model-resolver-defaults.js +1 -1
  105. package/dist/core/model-resolver-defaults.js.map +1 -1
  106. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  107. package/dist/core/model-runtime-streaming.js +9 -3
  108. package/dist/core/model-runtime-streaming.js.map +1 -1
  109. package/dist/core/model-runtime.d.ts +5 -0
  110. package/dist/core/model-runtime.d.ts.map +1 -1
  111. package/dist/core/model-runtime.js +6 -0
  112. package/dist/core/model-runtime.js.map +1 -1
  113. package/dist/core/provider-composer-internal.d.ts +6 -5
  114. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  115. package/dist/core/provider-composer-internal.js +13 -2
  116. package/dist/core/provider-composer-internal.js.map +1 -1
  117. package/dist/core/sdk.d.ts.map +1 -1
  118. package/dist/core/sdk.js +12 -4
  119. package/dist/core/sdk.js.map +1 -1
  120. package/dist/core/storage/session/sql-session-store.d.ts +35 -0
  121. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  122. package/dist/core/storage/session/sql-session-store.js +158 -42
  123. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  124. package/dist/core/structured-output/deadline.d.ts +40 -0
  125. package/dist/core/structured-output/deadline.d.ts.map +1 -0
  126. package/dist/core/structured-output/deadline.js +110 -0
  127. package/dist/core/structured-output/deadline.js.map +1 -0
  128. package/dist/core/structured-output/index.d.ts.map +1 -1
  129. package/dist/core/structured-output/index.js +103 -47
  130. package/dist/core/structured-output/index.js.map +1 -1
  131. package/dist/core/structured-output/rejection-detail.d.ts +9 -0
  132. package/dist/core/structured-output/rejection-detail.d.ts.map +1 -0
  133. package/dist/core/structured-output/rejection-detail.js +129 -0
  134. package/dist/core/structured-output/rejection-detail.js.map +1 -0
  135. package/dist/core/structured-output/types.d.ts +8 -1
  136. package/dist/core/structured-output/types.d.ts.map +1 -1
  137. package/dist/core/structured-output/types.js.map +1 -1
  138. package/dist/core/tasks/completion.d.ts +7 -1
  139. package/dist/core/tasks/completion.d.ts.map +1 -1
  140. package/dist/core/tasks/completion.js +28 -6
  141. package/dist/core/tasks/completion.js.map +1 -1
  142. package/dist/core/tasks/contracts.d.ts +6 -1
  143. package/dist/core/tasks/contracts.d.ts.map +1 -1
  144. package/dist/core/tasks/contracts.js.map +1 -1
  145. package/dist/core/tasks/pause.d.ts +2 -1
  146. package/dist/core/tasks/pause.d.ts.map +1 -1
  147. package/dist/core/tasks/pause.js +3 -2
  148. package/dist/core/tasks/pause.js.map +1 -1
  149. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  150. package/dist/core/tools/bash-pty-native.js +10 -5
  151. package/dist/core/tools/bash-pty-native.js.map +1 -1
  152. package/dist/core/tools/bash.d.ts.map +1 -1
  153. package/dist/core/tools/bash.js +16 -32
  154. package/dist/core/tools/bash.js.map +1 -1
  155. package/dist/core/tools/kill.d.ts.map +1 -1
  156. package/dist/core/tools/kill.js +17 -3
  157. package/dist/core/tools/kill.js.map +1 -1
  158. package/dist/core/tools/shell-task-render.d.ts +55 -0
  159. package/dist/core/tools/shell-task-render.d.ts.map +1 -0
  160. package/dist/core/tools/shell-task-render.js +123 -0
  161. package/dist/core/tools/shell-task-render.js.map +1 -0
  162. package/dist/core/tools/shell-task-status.d.ts +52 -0
  163. package/dist/core/tools/shell-task-status.d.ts.map +1 -0
  164. package/dist/core/tools/shell-task-status.js +184 -0
  165. package/dist/core/tools/shell-task-status.js.map +1 -0
  166. package/dist/core/tools/structured-output.d.ts +5 -0
  167. package/dist/core/tools/structured-output.d.ts.map +1 -1
  168. package/dist/core/tools/structured-output.js +3 -0
  169. package/dist/core/tools/structured-output.js.map +1 -1
  170. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  171. package/dist/extensions/codemode/execute.js +134 -57
  172. package/dist/extensions/codemode/execute.js.map +1 -1
  173. package/dist/extensions/mcp/config.d.ts.map +1 -1
  174. package/dist/extensions/mcp/config.js +3 -2
  175. package/dist/extensions/mcp/config.js.map +1 -1
  176. package/dist/index-extensions.d.ts +1 -0
  177. package/dist/index-extensions.d.ts.map +1 -1
  178. package/dist/index-extensions.js +3 -0
  179. package/dist/index-extensions.js.map +1 -1
  180. package/dist/index.d.ts +3 -1
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +3 -1
  183. package/dist/index.js.map +1 -1
  184. package/dist/main.d.ts.map +1 -1
  185. package/dist/main.js +19 -6
  186. package/dist/main.js.map +1 -1
  187. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  188. package/dist/modes/interactive/components/task-row.js +11 -1
  189. package/dist/modes/interactive/components/task-row.js.map +1 -1
  190. package/dist/modes/interactive/interactive-auth-routing.js +12 -10
  191. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  192. package/dist/modes/interactive/interactive-extension-custom-ui.js +20 -30
  193. package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
  194. package/dist/modes/interactive/interactive-extension-dialogs.js +23 -96
  195. package/dist/modes/interactive/interactive-extension-dialogs.js.map +1 -1
  196. package/dist/modes/interactive/interactive-extension-runtime.js +7 -8
  197. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  198. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  199. package/dist/modes/interactive/interactive-input-handling.js +27 -4
  200. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  201. package/dist/modes/interactive/interactive-mode-base.d.ts +20 -10
  202. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  203. package/dist/modes/interactive/interactive-mode-base.js +40 -5
  204. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  205. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  206. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  207. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  208. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  209. package/dist/modes/interactive/interactive-mode-surface.d.ts +2 -4
  210. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  211. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  212. package/dist/modes/interactive/interactive-mode-types.d.ts +4 -1
  213. package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
  214. package/dist/modes/interactive/interactive-mode-types.js.map +1 -1
  215. package/dist/modes/interactive/interactive-prompt-restore.d.ts +3 -0
  216. package/dist/modes/interactive/interactive-prompt-restore.d.ts.map +1 -1
  217. package/dist/modes/interactive/interactive-prompt-restore.js +9 -1
  218. package/dist/modes/interactive/interactive-prompt-restore.js.map +1 -1
  219. package/dist/modes/interactive/interactive-prompt-turn.js +30 -2
  220. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  221. package/dist/modes/interactive/interactive-queueing.js +43 -8
  222. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  223. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  224. package/dist/modes/interactive/interactive-startup.js +12 -3
  225. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  226. package/dist/modes/interactive/theme/color-utils.d.ts +6 -1
  227. package/dist/modes/interactive/theme/color-utils.d.ts.map +1 -1
  228. package/dist/modes/interactive/theme/color-utils.js +39 -17
  229. package/dist/modes/interactive/theme/color-utils.js.map +1 -1
  230. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  231. package/dist/modes/interactive/theme/theme-class.js +2 -2
  232. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  233. package/dist/modes/interactive/theme/theme-tokens.d.ts +6 -0
  234. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -1
  235. package/dist/modes/interactive/theme/theme-tokens.js +7 -3
  236. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -1
  237. package/dist/modes/interactive-engine/isolated-auth.d.ts +3 -0
  238. package/dist/modes/interactive-engine/isolated-auth.d.ts.map +1 -1
  239. package/dist/modes/interactive-engine/isolated-auth.js +13 -1
  240. package/dist/modes/interactive-engine/isolated-auth.js.map +1 -1
  241. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  242. package/dist/modes/interactive-engine/isolated-runtime.js +11 -2
  243. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  244. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +8 -0
  245. package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -1
  246. package/dist/modes/interactive-engine/remote-model-catalog.js +54 -0
  247. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
  248. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  249. package/dist/modes/rpc/rpc-command-handler.js +4 -13
  250. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  251. package/dist/modes/rpc/rpc-model-catalog.d.ts +9 -0
  252. package/dist/modes/rpc/rpc-model-catalog.d.ts.map +1 -0
  253. package/dist/modes/rpc/rpc-model-catalog.js +19 -0
  254. package/dist/modes/rpc/rpc-model-catalog.js.map +1 -0
  255. package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -1
  256. package/dist/modes/rpc/rpc-provider-auth.js +2 -6
  257. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  258. package/dist/modes/rpc/rpc-types.d.ts +6 -0
  259. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  260. package/dist/modes/rpc/rpc-types.js.map +1 -1
  261. package/dist/utils/changelog.d.ts +6 -0
  262. package/dist/utils/changelog.d.ts.map +1 -1
  263. package/dist/utils/changelog.js +11 -0
  264. package/dist/utils/changelog.js.map +1 -1
  265. package/dist/utils/clipboard.d.ts.map +1 -1
  266. package/dist/utils/clipboard.js +4 -0
  267. package/dist/utils/clipboard.js.map +1 -1
  268. package/dist/utils/tools-manager.d.ts.map +1 -1
  269. package/dist/utils/tools-manager.js +3 -2
  270. package/dist/utils/tools-manager.js.map +1 -1
  271. package/docs/background-tasks.md +5 -3
  272. package/docs/codemode.md +2 -2
  273. package/docs/custom-provider/oauth.md +42 -1
  274. package/docs/custom-provider/registration.md +2 -0
  275. package/docs/environment-variables.md +1 -0
  276. package/docs/extensions/api-reference.md +3 -4
  277. package/docs/extensions/authoring.md +1 -1
  278. package/docs/extensions/events.md +1 -1
  279. package/docs/providers.md +3 -3
  280. package/docs/rpc/protocol.md +4 -2
  281. package/docs/sdk/reference.md +2 -0
  282. package/docs/sdk/structured-decisions.md +7 -5
  283. package/docs/sdk.md +5 -2
  284. package/docs/settings.md +4 -2
  285. package/docs/subagents/reference.md +1 -1
  286. package/docs/subagents.md +15 -1
  287. package/docs/themes/reference.md +3 -1
  288. package/docs/usage.md +3 -1
  289. package/docs/workflows/api-reference.md +28 -0
  290. package/docs/workflows/operations.md +2 -2
  291. package/npm-shrinkwrap.json +32 -32
  292. package/package.json +3 -3
  293. package/dist/core/provider-attribution.d.ts +0 -4
  294. package/dist/core/provider-attribution.d.ts.map +0 -1
  295. package/dist/core/provider-attribution.js +0 -87
  296. package/dist/core/provider-attribution.js.map +0 -1
@@ -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,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAEnF,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClG,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAK1E,8EAA8E;AAC9E,MAAM,CAAC,MAAM,kCAAkC,GAAG,EAAE,GAAG,MAAM,CAAC;AAiB9D;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAA6C;IACnE,KAAK,EAAE,CAAC;IACR,sBAAsB,EAAE,CAAC;IACzB,iBAAiB,EAAE,CAAC;IACpB,0BAA0B,EAAE,CAAC;IAC7B,aA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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, resolveModelReference } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport { redactCredentialShapes } from \"../utils/credential-redaction.js\";\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\nexport { redactCredentialShapes } from \"../utils/credential-redaction.js\";\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 catalog = modelRuntime.getModels();\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveModelReference(\n\t\t\t{ text: args.model ?? \"\", provider: provider.id, thinkingSuffix: \"strict\", fuzzy: true },\n\t\t\tcatalog,\n\t\t\t() => true,\n\t\t);\n\t\tif (resolved.status === \"resolved\") models.push(resolved.model);\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,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAEnF,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClG,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAK1E,8EAA8E;AAC9E,MAAM,CAAC,MAAM,kCAAkC,GAAG,EAAE,GAAG,MAAM,CAAC;AAiB9D;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,UAAU,GAA6C;IACnE,KAAK,EAAE,CAAC;IACR,sBAAsB,EAAE,CAAC;IACzB,iBAAiB,EAAE,CAAC;IACpB,0BAA0B,EAAE,CAAC;IAC7B,aAAa,EAAE,CAAC;IAChB,sBAAsB,EAAE,CAAC;IACzB,gBAAgB,EAAE,CAAC;IACnB,oBAAoB,EAAE,CAAC;IACvB,mBAAmB,EAAE,CAAC;CACtB,CAAC;AAEF,qEAAqE;AACrE,MAAM,CAAC,MAAM,oBAAoB,GAA0C,IAAI,GAAG,CAChF,MAAM,CAAC,IAAI,CAAC,UAAU,CAAgC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,qBAAqB,CAAC,CACxG,CAAC;AAEF,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACrC,IAAI,CAA2B;IAC/B,QAAQ,CAAS;IAE1B,YAAY,IAA8B,EAAE,OAAe,EAAE,OAA6B;QACzF,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CA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;QAC/C,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC;QACvC,MAAM,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACxE,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YAC7D,MAAM,IAAI,oBAAoB,CAC7B,4BAA4B,EAC5B,aAAa,UAAU,4CAA4C,CACnE,CAAC;QACH,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,KAAK,cAAc,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACpE,MAAM,IAAI,oBAAoB,CAC7B,4BAA4B,EAC5B,aAAa,UAAU,gDAAgD,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, resolveModelReference } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport { redactCredentialShapes } from \"../utils/credential-redaction.js\";\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\nexport { redactCredentialShapes } from \"../utils/credential-redaction.js\";\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(\n\t\t\t\"RefreshFailed\",\n\t\t\t`${detail} (the stored credential changes only if the provider completes this refresh later)`,\n\t\t\t{\n\t\t\t\tcause: error,\n\t\t\t},\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 catalog = modelRuntime.getModels();\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveModelReference(\n\t\t\t{ text: args.model ?? \"\", provider: provider.id, thinkingSuffix: \"strict\", fuzzy: true },\n\t\t\tcatalog,\n\t\t\t() => true,\n\t\t);\n\t\tif (resolved.status === \"resolved\") models.push(resolved.model);\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"]}
package/dist/config.d.ts CHANGED
@@ -83,6 +83,7 @@ export declare const ENV_HARDWARE_CURSOR: string;
83
83
  export declare const ENV_CLIPBOARD_OSC52: string;
84
84
  export declare const ENV_TIMING: string;
85
85
  export declare const ENV_HEAP_MB: string;
86
+ export declare const ENV_CODEMODE_MAX_WORKERS: string;
86
87
  export declare const WORKFLOW_STAGE_SUBAGENT_GUARD_ENV: string;
87
88
  export declare function getEnvNames(name: string): string[];
88
89
  export declare function getEnvValue(name: string): string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAwBA,eAAO,MAAM,WAAW,S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AgB,cAAc,IAAI,MAAM,CAEvC;AAED,iCAAiC;AACjC,wBAAgB,eAAe,IAAI,MAAM,CAExC"}
package/dist/config.js CHANGED
@@ -242,6 +242,7 @@ export const ENV_HARDWARE_CURSOR = `${ENV_PREFIX}_HARDWARE_CURSOR`;
242
242
  export const ENV_CLIPBOARD_OSC52 = `${ENV_PREFIX}_CLIPBOARD_OSC52`;
243
243
  export const ENV_TIMING = `${ENV_PREFIX}_TIMING`;
244
244
  export const ENV_HEAP_MB = `${ENV_PREFIX}_HEAP_MB`;
245
+ export const ENV_CODEMODE_MAX_WORKERS = `${ENV_PREFIX}_CODEMODE_MAX_WORKERS`;
245
246
  export const WORKFLOW_STAGE_SUBAGENT_GUARD_ENV = `${ENV_PREFIX}_WORKFLOW_STAGE_SUBAGENT_GUARD`;
246
247
  export function getEnvNames(name) {
247
248
  if (ENV_PREFIX === LEGACY_ENV_PREFIX || !name.startsWith(`${ENV_PREFIX}_`))
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAC1F,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,gFAAgF;AAChF,oBAAoB;AACpB,gFAAgF;AAEhF,MAAM,UAAU,GAAG,qBAAqB,CAAC,OAAO,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;AACpE,MAAM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IAC5B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,CAAC,CAAC;AACvC,CAAC;AAED,qCAAqC;AACrC,MAAM,UAAU,cAAc;IAC7B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,UAAU,CAAC,CAAC;AACxC,CAAC;AAED,iCAAiC;AACjC,MAAM,UAAU,eAAe;IAC9B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,GAAG,QAAQ,YAAY,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import { createRequire } from \"node:module\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { resolvePackageDirFrom } from \"./config-package-identity.ts\";\nimport { getHomeDir, normalizePath } from \"./utils/paths.ts\";\nimport { isSplitLauncherRuntime, moduleFileFromMetaUrl } from \"./utils/split-launcher.ts\";\nimport { stripBom } from \"./utils/text.ts\";\n\n// =============================================================================\n// Package Detection\n// =============================================================================\n\nconst __filename = moduleFileFromMetaUrl(import.meta.url, \"app.js\");\nconst __dirname = dirname(__filename);\n\n/**\n * Detect if we're running as a Bun compiled binary.\n * Bun binaries have import.meta.url containing \"$bunfs\", \"~BUN\", or \"%7EBUN\" (Bun's virtual filesystem path).\n * Split Windows/macOS/Linux release launchers also set ATOMIC_CODING_AGENT before importing the sidecar app bundle.\n */\nconst bunFsMarkers = [\"$bunfs\", \"~BUN\", \"%7EBUN\"];\n// Check process.argv[1] as well as import.meta.url: in a CJS (bytecode) bundle\n// import.meta.url is rewritten to the original source path, but argv[1] still\n// points into Bun's virtual filesystem.\nexport const isBunBinary =\n\tisSplitLauncherRuntime() ||\n\t[import.meta.url, process.argv[1] ?? \"\"].some((candidate) =>\n\t\tbunFsMarkers.some((marker) => candidate.includes(marker)),\n\t);\n\n/**\n * Detect if we're running from a single-file bundle produced by `bun run bundle:dev`.\n * The bundle build inlines this env var via `--define`, so it is a compile-time\n * constant there and undefined everywhere else.\n */\nexport const isBundledBuild = process.env.ATOMIC_BUNDLED_BUILD === \"1\";\n\n/** Detect if Bun is the runtime (compiled binary or bun run) */\nexport const isBunRuntime = !!process.versions.bun;\n\n// =============================================================================\n// Install Method Detection\n// =============================================================================\n\nimport {\n\tdetectInstallMethodForRuntime,\n\tgetSelfUpdateCommandForRuntime,\n\tgetSelfUpdateUnavailableInstructionForRuntime,\n\tgetUpdateInstructionForRuntime,\n\ttype SelfUpdateRuntime,\n} from \"./config-self-update.ts\";\n\nexport type { InstallMethod, SelfUpdateCommand, SelfUpdateTarget } from \"./config-self-update.ts\";\n\nfunction selfUpdateRuntime(): SelfUpdateRuntime {\n\treturn {\n\t\tisBunBinary,\n\t\tisBunRuntime,\n\t\tmoduleDir: __dirname,\n\t\tgetPackageDir,\n\t};\n}\n\nexport function detectInstallMethod(): import(\"./config-self-update.ts\").InstallMethod {\n\treturn detectInstallMethodForRuntime(selfUpdateRuntime());\n}\n\nexport function getSelfUpdateCommand(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdateTarget: import(\"./config-self-update.ts\").SelfUpdateTarget = { packageName, installSpec: packageName },\n): import(\"./config-self-update.ts\").SelfUpdateCommand | undefined {\n\treturn getSelfUpdateCommandForRuntime(selfUpdateRuntime(), packageName, npmCommand, updateTarget);\n}\n\nexport function getSelfUpdateUnavailableInstruction(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdateTarget: import(\"./config-self-update.ts\").SelfUpdateTarget = { packageName, installSpec: packageName },\n): string {\n\treturn getSelfUpdateUnavailableInstructionForRuntime(selfUpdateRuntime(), packageName, npmCommand, updateTarget);\n}\n\nexport function getUpdateInstruction(packageName: string): string {\n\treturn getUpdateInstructionForRuntime(selfUpdateRuntime(), packageName);\n}\n\n// =============================================================================\n// Package Asset Paths (shipped with executable)\n// =============================================================================\n\n/**\n * Get the base directory for resolving package assets (themes, package.json, README.md, CHANGELOG.md).\n * - For Bun binary: returns the directory containing the executable\n * - For Node.js (dist/): returns __dirname (the dist/ directory)\n * - For source (src/): returns parent directory (the package root)\n */\nexport function getPackageDir(): string {\n\t// Allow override via environment variable (useful for Nix/Guix where store paths tokenize poorly).\n\t// This runs before package.json app config is read, so the env var name is hardcoded.\n\tconst envDir = process.env.ATOMIC_PACKAGE_DIR ?? process.env.PI_PACKAGE_DIR;\n\tif (envDir) {\n\t\treturn normalizePath(envDir);\n\t}\n\n\tif (isBunBinary) {\n\t\t// Bun binary: process.execPath points to the compiled executable\n\t\treturn dirname(process.execPath);\n\t}\n\t// Node.js: walk up from __dirname to the Atomic app package. Prebundled\n\t// companion extensions ship under dist/builtin/<name>/ with their own\n\t// package.json; stopping at the first one made APP_NAME \"workflows\".\n\treturn resolvePackageDirFrom(__dirname);\n}\n\n/**\n * Resolve the root that contains source-layout assets for non-binary runtimes.\n * Ordinary source and compiled modules already live in src/ or dist/, so use\n * their module directory directly. Bundled development builds and explicit\n * package-directory overrides instead need to select a package-root layout.\n */\nfunction getModuleAssetRoot(): string {\n\tconst hasPackageDirOverride = !!(process.env.ATOMIC_PACKAGE_DIR || process.env.PI_PACKAGE_DIR);\n\tif (!isBundledBuild && !hasPackageDirOverride) {\n\t\treturn __dirname;\n\t}\n\tconst packageDir = getPackageDir();\n\treturn join(packageDir, existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\");\n}\n\n/** Codemode workers and wasm live beside Atomic's split/development bundle. */\nlet codemodeWorkerDataUrl: URL | undefined;\nlet quickJSWasmPath: string | undefined;\n\nexport function getCodemodeWorkerUrl(): URL | undefined {\n\tif (codemodeWorkerDataUrl) return codemodeWorkerDataUrl;\n\tconst worker = isBunBinary\n\t\t? join(getPackageDir(), \"codemode-worker.js\")\n\t\t: isBundledBuild\n\t\t\t? join(dirname(resolve(process.argv[1])), \"codemode-worker.js\")\n\t\t\t: join(getModuleAssetRoot(), \"codemode-worker.js\");\n\tif (!isBunBinary && !isBundledBuild && !existsSync(worker)) return undefined;\n\t// A self-contained worker survives replacement or removal of the running install.\n\tcodemodeWorkerDataUrl ??= new URL(`data:text/javascript;base64,${readFileSync(worker).toString(\"base64\")}`);\n\treturn codemodeWorkerDataUrl;\n}\n\nexport function getQuickJSWasmPath(): string {\n\tquickJSWasmPath ??= isBunBinary\n\t\t? join(getPackageDir(), \"quickjs.wasm\")\n\t\t: isBundledBuild\n\t\t\t? join(dirname(resolve(process.argv[1])), \"quickjs.wasm\")\n\t\t\t: createRequire(__filename).resolve(\"quickjs-wasi/quickjs.wasm\");\n\treturn quickJSWasmPath;\n}\n\nexport type InstallChange = { kind: \"updated\"; version: string } | { kind: \"removed\" };\n\nexport function detectInstallChange(packageJsonPath = startupPackageJsonPath): InstallChange | undefined {\n\tif (isBunBinary || !packageJsonPath) return undefined;\n\tlet installed: PackageJson;\n\ttry {\n\t\tinstalled = JSON.parse(stripBom(readFileSync(packageJsonPath, \"utf-8\"))) as PackageJson;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\" ? { kind: \"removed\" } : undefined;\n\t}\n\treturn installed.version && installed.version !== VERSION\n\t\t? { kind: \"updated\", version: installed.version }\n\t\t: undefined;\n}\n/**\n * Get path to built-in themes directory (shipped with package)\n * - For Bun binary: theme/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/theme/\n * - For source (src/): src/modes/interactive/theme/\n */\nexport function getThemesDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"theme\");\n\t}\n\treturn join(getModuleAssetRoot(), \"modes\", \"interactive\", \"theme\");\n}\n\n/**\n * Get path to HTML export template directory (shipped with package)\n * - For Bun binary: export-html/ next to executable\n * - For Node.js (dist/): dist/core/export-html/\n * - For source (src/): src/core/export-html/\n */\nexport function getExportTemplateDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"export-html\");\n\t}\n\treturn join(getModuleAssetRoot(), \"core\", \"export-html\");\n}\n\n/** Get path to package.json */\nexport function getPackageJsonPath(): string {\n\treturn join(getPackageDir(), \"package.json\");\n}\n\n/** Get path to README.md */\nexport function getReadmePath(): string {\n\treturn resolve(join(getPackageDir(), \"README.md\"));\n}\n\n/** Get path to docs directory */\nexport function getDocsPath(): string {\n\treturn resolve(join(getPackageDir(), \"docs\"));\n}\n\n/** Get path to examples directory */\nexport function getExamplesPath(): string {\n\treturn resolve(join(getPackageDir(), \"examples\"));\n}\n\n/** Get path to CHANGELOG.md */\nexport function getChangelogPath(): string {\n\treturn resolve(join(getPackageDir(), \"CHANGELOG.md\"));\n}\n\n/**\n * Get path to built-in interactive assets directory.\n * - For Bun binary: assets/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/assets/\n * - For source (src/): src/modes/interactive/assets/\n */\nexport function getInteractiveAssetsDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"assets\");\n\t}\n\treturn join(getModuleAssetRoot(), \"modes\", \"interactive\", \"assets\");\n}\n\n/** Get path to a bundled interactive asset */\nexport function getBundledInteractiveAssetPath(name: string): string {\n\treturn join(getInteractiveAssetsDir(), name);\n}\n\n// =============================================================================\n// App Config (from package.json <appName>Config, with piConfig as a legacy shim)\n// =============================================================================\n\ninterface AppConfig {\n\tname?: string;\n\tconfigDir?: string;\n\tchangelogUrl?: string;\n}\n\ninterface PackageJson extends Record<string, unknown> {\n\tname?: string;\n\tversion?: string;\n\tpiConfig?: AppConfig;\n}\n\nlet pkg: PackageJson = {};\nlet startupPackageJsonPath: string | undefined;\ntry {\n\tconst packageJsonPath = getPackageJsonPath();\n\tpkg = JSON.parse(stripBom(readFileSync(packageJsonPath, \"utf-8\"))) as PackageJson;\n\tstartupPackageJsonPath = packageJsonPath;\n} catch (e: unknown) {\n\tconst err = e as NodeJS.ErrnoException;\n\tif (err.code !== \"ENOENT\") throw e;\n}\n\nfunction appNameFromPackageName(packageName: string | undefined): string | undefined {\n\tconst localName = packageName?.split(\"/\").pop()?.trim();\n\treturn localName && localName.length > 0 ? localName : undefined;\n}\n\nfunction readAppConfig(packageJson: PackageJson, appName: string | undefined): AppConfig | undefined {\n\tif (appName) {\n\t\tconst appConfig = packageJson[`${appName}Config`];\n\t\tif (appConfig && typeof appConfig === \"object\" && !Array.isArray(appConfig)) {\n\t\t\treturn appConfig as AppConfig;\n\t\t}\n\t}\n\treturn packageJson.piConfig;\n}\n\nexport const PACKAGE_NAME: string = pkg.name || \"@bastani/atomic\";\nconst packageAppName = appNameFromPackageName(PACKAGE_NAME);\nconst appConfig = readAppConfig(pkg, packageAppName);\nexport const APP_NAME: string = appConfig?.name || packageAppName || \"pi\";\nexport const APP_TITLE: string = appConfig?.name !== undefined || APP_NAME !== \"pi\" ? APP_NAME : \"π\";\nexport const CONFIG_DIR_NAME: string = appConfig?.configDir || (APP_NAME === \"pi\" ? \".pi\" : `.${APP_NAME}`);\nexport const LEGACY_CONFIG_DIR_NAME = \".pi\";\nexport const CONFIG_DIR_NAMES: readonly string[] =\n\tCONFIG_DIR_NAME === LEGACY_CONFIG_DIR_NAME ? [CONFIG_DIR_NAME] : [CONFIG_DIR_NAME, LEGACY_CONFIG_DIR_NAME];\nexport const VERSION: string = pkg.version || \"0.0.0\";\nexport const CHANGELOG_URL: string | undefined = appConfig?.changelogUrl?.trim() || undefined;\n\nconst ENV_PREFIX = APP_NAME.toUpperCase();\nexport const LEGACY_ENV_PREFIX = \"PI\";\n\n// e.g., ATOMIC_CODING_AGENT_DIR (with PI_CODING_AGENT_DIR as a compatibility alias)\nexport const ENV_AGENT_DIR = `${ENV_PREFIX}_CODING_AGENT_DIR`;\nexport const ENV_SESSION_DIR = `${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`;\nexport const ENV_PACKAGE_DIR = `${ENV_PREFIX}_PACKAGE_DIR`;\nexport const ENV_OFFLINE = `${ENV_PREFIX}_OFFLINE`;\nexport const ENV_SKIP_VERSION_CHECK = `${ENV_PREFIX}_SKIP_VERSION_CHECK`;\nexport const ENV_STARTUP_BENCHMARK = `${ENV_PREFIX}_STARTUP_BENCHMARK`;\nexport const ENV_TELEMETRY = `${ENV_PREFIX}_TELEMETRY`;\nexport const ENV_SHARE_VIEWER_URL = `${ENV_PREFIX}_SHARE_VIEWER_URL`;\nexport const ENV_CLEAR_ON_SHRINK = `${ENV_PREFIX}_CLEAR_ON_SHRINK`;\nexport const ENV_HARDWARE_CURSOR = `${ENV_PREFIX}_HARDWARE_CURSOR`;\nexport const ENV_CLIPBOARD_OSC52 = `${ENV_PREFIX}_CLIPBOARD_OSC52`;\nexport const ENV_TIMING = `${ENV_PREFIX}_TIMING`;\nexport const ENV_HEAP_MB = `${ENV_PREFIX}_HEAP_MB`;\nexport const WORKFLOW_STAGE_SUBAGENT_GUARD_ENV = `${ENV_PREFIX}_WORKFLOW_STAGE_SUBAGENT_GUARD`;\nexport function getEnvNames(name: string): string[] {\n\tif (ENV_PREFIX === LEGACY_ENV_PREFIX || !name.startsWith(`${ENV_PREFIX}_`)) return [name];\n\treturn [name, `${LEGACY_ENV_PREFIX}_${name.slice(ENV_PREFIX.length + 1)}`];\n}\n\nexport function getEnvValue(name: string): string | undefined {\n\tfor (const candidate of getEnvNames(name)) {\n\t\tconst value = process.env[candidate];\n\t\tif (value !== undefined) return value;\n\t}\n\treturn undefined;\n}\n\nexport function hasEnvValue(name: string): boolean {\n\treturn getEnvValue(name) !== undefined;\n}\n\nexport function setEnvValue(name: string, value: string): void {\n\tprocess.env[name] = value;\n}\n\nexport function expandTildePath(path: string): string {\n\treturn normalizePath(path);\n}\n\nconst DEFAULT_SHARE_VIEWER_URL = \"https://pi.dev/session/\";\n\nexport const VERSION_ADOPTION_ENDPOINT =\n\t\"https://atomic-version-adoption.bastani-atomic.workers.dev/v1/version-adoption\";\n\n/** Get the share viewer URL for a gist ID */\nexport function getShareViewerUrl(gistId: string): string {\n\tconst baseUrl = getEnvValue(ENV_SHARE_VIEWER_URL) || DEFAULT_SHARE_VIEWER_URL;\n\treturn `${baseUrl}#${gistId}`;\n}\n\n// =============================================================================\n// User Config Paths (~/.atomic/agent/*)\n// =============================================================================\n\n/** Get the agent config directory (e.g., ~/.atomic/agent/) */\nexport function getAgentDir(): string {\n\tconst envDir = getEnvValue(ENV_AGENT_DIR);\n\tif (envDir) {\n\t\treturn expandTildePath(envDir);\n\t}\n\treturn join(getHomeDir(), CONFIG_DIR_NAME, \"agent\");\n}\n\n/** Get the legacy pi agent config directory (e.g., ~/.pi/agent/) */\nexport function getLegacyAgentDir(): string {\n\treturn join(getHomeDir(), LEGACY_CONFIG_DIR_NAME, \"agent\");\n}\n\n/** Get agent config directories in precedence order (primary first, then legacy). */\nexport function getAgentDirs(): string[] {\n\tconst primary = getAgentDir();\n\tif (hasEnvValue(ENV_AGENT_DIR) || CONFIG_DIR_NAME === LEGACY_CONFIG_DIR_NAME) {\n\t\treturn [primary];\n\t}\n\tconst legacy = getLegacyAgentDir();\n\treturn legacy === primary ? [primary] : [primary, legacy];\n}\n\n/** Get user config root directories in precedence order (primary first, then legacy). */\nexport function getUserConfigDirs(): string[] {\n\treturn CONFIG_DIR_NAMES.map((name) => join(getHomeDir(), name));\n}\n\n/** Get project config directories in precedence order (primary first, then legacy). */\nexport function getProjectConfigDirs(cwd: string): string[] {\n\treturn CONFIG_DIR_NAMES.map((name) => join(cwd, name));\n}\n\n/** Get a path inside every user config root directory. */\nexport function getUserConfigPaths(...segments: string[]): string[] {\n\treturn getUserConfigDirs().map((dir) => join(dir, ...segments));\n}\n\n/** Get a path inside every agent config directory. */\nexport function getAgentConfigPaths(...segments: string[]): string[] {\n\treturn getAgentDirs().map((dir) => join(dir, ...segments));\n}\n\n/** Get a path inside every project config directory. */\nexport function getProjectConfigPaths(cwd: string, ...segments: string[]): string[] {\n\treturn getProjectConfigDirs(cwd).map((dir) => join(dir, ...segments));\n}\n\n/** Model config paths from highest to lowest precedence: Atomic project/global, then Pi project/global. */\nexport function getModelsConfigPaths(cwd: string, agentDir: string = getAgentDir(), includeProject = true): string[] {\n\tconst globalPaths =\n\t\tagentDir === getAgentDir() ? getAgentConfigPaths(\"models.json\") : [join(agentDir, \"models.json\")];\n\tif (!includeProject) return globalPaths;\n\tconst projectPaths = getProjectConfigPaths(cwd, \"models.json\");\n\tconst paths: string[] = [];\n\tfor (let index = 0; index < Math.max(projectPaths.length, globalPaths.length); index++) {\n\t\tif (projectPaths[index]) paths.push(projectPaths[index]);\n\t\tif (globalPaths[index]) paths.push(globalPaths[index]);\n\t}\n\treturn [...new Set(paths)];\n}\n\n/** Get path to user's custom themes directory */\nexport function getCustomThemesDir(): string {\n\treturn join(getAgentDir(), \"themes\");\n}\n\n/** Get path to models.json */\nexport function getModelsPath(): string {\n\treturn join(getAgentDir(), \"models.json\");\n}\n\n/** Get path to auth.json */\nexport function getAuthPath(): string {\n\treturn join(getAgentDir(), \"auth.json\");\n}\n\n/** Get path to settings.json */\nexport function getSettingsPath(): string {\n\treturn join(getAgentDir(), \"settings.json\");\n}\n\n/** Get path to tools directory */\nexport function getToolsDir(): string {\n\treturn join(getAgentDir(), \"tools\");\n}\n\n/** Get path to managed binaries directory (fd, rg) */\nexport function getBinDir(): string {\n\treturn join(getAgentDir(), \"bin\");\n}\n\nconst EXTENSION_TRANSPILE_CACHE_FORMAT = \"ts-source-specifiers\";\n\n/**\n * Get path to the extension transpile cache directory (jiti fsCache).\n * Scoped by version and transform format so neither a release upgrade nor a\n * loader transform change reads stale transpiled output.\n */\nexport function getExtensionTranspileCacheDir(): string {\n\treturn join(getAgentDir(), \"cache\", \"jiti\", `${VERSION}+${EXTENSION_TRANSPILE_CACHE_FORMAT}`);\n}\n\n/** Get path to prompt templates directory */\nexport function getPromptsDir(): string {\n\treturn join(getAgentDir(), \"prompts\");\n}\n\n/** Get path to sessions directory */\nexport function getSessionsDir(): string {\n\treturn join(getAgentDir(), \"sessions\");\n}\n\n/** Get path to debug log file */\nexport function getDebugLogPath(): string {\n\treturn join(getAgentDir(), `${APP_NAME}-debug.log`);\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE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;AAChC,MAAM,UAAU,eAAe;IAC9B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,eAAe,CAAC,CAAC;AAC7C,CAAC;AAED,kCAAkC;AAClC,MAAM,UAAU,WAAW;IAC1B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,CAAC;AACrC,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,SAAS;IACxB,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,KAAK,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,gCAAgC,GAAG,sBAAsB,CAAC;AAEhE;;;;GAIG;AACH,MAAM,UAAU,6BAA6B;IAC5C,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,IAAI,gCAAgC,EAAE,CAAC,CAAC;AAC/F,CAAC;AAED,6CAA6C;AAC7C,MAAM,UAAU,aAAa;IAC5B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,CAAC,CAAC;AACvC,CAAC;AAED,qCAAqC;AACrC,MAAM,UAAU,cAAc;IAC7B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,UAAU,CAAC,CAAC;AACxC,CAAC;AAED,iCAAiC;AACjC,MAAM,UAAU,eAAe;IAC9B,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,GAAG,QAAQ,YAAY,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import { createRequire } from \"node:module\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { resolvePackageDirFrom } from \"./config-package-identity.ts\";\nimport { getHomeDir, normalizePath } from \"./utils/paths.ts\";\nimport { isSplitLauncherRuntime, moduleFileFromMetaUrl } from \"./utils/split-launcher.ts\";\nimport { stripBom } from \"./utils/text.ts\";\n\n// =============================================================================\n// Package Detection\n// =============================================================================\n\nconst __filename = moduleFileFromMetaUrl(import.meta.url, \"app.js\");\nconst __dirname = dirname(__filename);\n\n/**\n * Detect if we're running as a Bun compiled binary.\n * Bun binaries have import.meta.url containing \"$bunfs\", \"~BUN\", or \"%7EBUN\" (Bun's virtual filesystem path).\n * Split Windows/macOS/Linux release launchers also set ATOMIC_CODING_AGENT before importing the sidecar app bundle.\n */\nconst bunFsMarkers = [\"$bunfs\", \"~BUN\", \"%7EBUN\"];\n// Check process.argv[1] as well as import.meta.url: in a CJS (bytecode) bundle\n// import.meta.url is rewritten to the original source path, but argv[1] still\n// points into Bun's virtual filesystem.\nexport const isBunBinary =\n\tisSplitLauncherRuntime() ||\n\t[import.meta.url, process.argv[1] ?? \"\"].some((candidate) =>\n\t\tbunFsMarkers.some((marker) => candidate.includes(marker)),\n\t);\n\n/**\n * Detect if we're running from a single-file bundle produced by `bun run bundle:dev`.\n * The bundle build inlines this env var via `--define`, so it is a compile-time\n * constant there and undefined everywhere else.\n */\nexport const isBundledBuild = process.env.ATOMIC_BUNDLED_BUILD === \"1\";\n\n/** Detect if Bun is the runtime (compiled binary or bun run) */\nexport const isBunRuntime = !!process.versions.bun;\n\n// =============================================================================\n// Install Method Detection\n// =============================================================================\n\nimport {\n\tdetectInstallMethodForRuntime,\n\tgetSelfUpdateCommandForRuntime,\n\tgetSelfUpdateUnavailableInstructionForRuntime,\n\tgetUpdateInstructionForRuntime,\n\ttype SelfUpdateRuntime,\n} from \"./config-self-update.ts\";\n\nexport type { InstallMethod, SelfUpdateCommand, SelfUpdateTarget } from \"./config-self-update.ts\";\n\nfunction selfUpdateRuntime(): SelfUpdateRuntime {\n\treturn {\n\t\tisBunBinary,\n\t\tisBunRuntime,\n\t\tmoduleDir: __dirname,\n\t\tgetPackageDir,\n\t};\n}\n\nexport function detectInstallMethod(): import(\"./config-self-update.ts\").InstallMethod {\n\treturn detectInstallMethodForRuntime(selfUpdateRuntime());\n}\n\nexport function getSelfUpdateCommand(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdateTarget: import(\"./config-self-update.ts\").SelfUpdateTarget = { packageName, installSpec: packageName },\n): import(\"./config-self-update.ts\").SelfUpdateCommand | undefined {\n\treturn getSelfUpdateCommandForRuntime(selfUpdateRuntime(), packageName, npmCommand, updateTarget);\n}\n\nexport function getSelfUpdateUnavailableInstruction(\n\tpackageName: string,\n\tnpmCommand?: string[],\n\tupdateTarget: import(\"./config-self-update.ts\").SelfUpdateTarget = { packageName, installSpec: packageName },\n): string {\n\treturn getSelfUpdateUnavailableInstructionForRuntime(selfUpdateRuntime(), packageName, npmCommand, updateTarget);\n}\n\nexport function getUpdateInstruction(packageName: string): string {\n\treturn getUpdateInstructionForRuntime(selfUpdateRuntime(), packageName);\n}\n\n// =============================================================================\n// Package Asset Paths (shipped with executable)\n// =============================================================================\n\n/**\n * Get the base directory for resolving package assets (themes, package.json, README.md, CHANGELOG.md).\n * - For Bun binary: returns the directory containing the executable\n * - For Node.js (dist/): returns __dirname (the dist/ directory)\n * - For source (src/): returns parent directory (the package root)\n */\nexport function getPackageDir(): string {\n\t// Allow override via environment variable (useful for Nix/Guix where store paths tokenize poorly).\n\t// This runs before package.json app config is read, so the env var name is hardcoded.\n\tconst envDir = process.env.ATOMIC_PACKAGE_DIR ?? process.env.PI_PACKAGE_DIR;\n\tif (envDir) {\n\t\treturn normalizePath(envDir);\n\t}\n\n\tif (isBunBinary) {\n\t\t// Bun binary: process.execPath points to the compiled executable\n\t\treturn dirname(process.execPath);\n\t}\n\t// Node.js: walk up from __dirname to the Atomic app package. Prebundled\n\t// companion extensions ship under dist/builtin/<name>/ with their own\n\t// package.json; stopping at the first one made APP_NAME \"workflows\".\n\treturn resolvePackageDirFrom(__dirname);\n}\n\n/**\n * Resolve the root that contains source-layout assets for non-binary runtimes.\n * Ordinary source and compiled modules already live in src/ or dist/, so use\n * their module directory directly. Bundled development builds and explicit\n * package-directory overrides instead need to select a package-root layout.\n */\nfunction getModuleAssetRoot(): string {\n\tconst hasPackageDirOverride = !!(process.env.ATOMIC_PACKAGE_DIR || process.env.PI_PACKAGE_DIR);\n\tif (!isBundledBuild && !hasPackageDirOverride) {\n\t\treturn __dirname;\n\t}\n\tconst packageDir = getPackageDir();\n\treturn join(packageDir, existsSync(join(packageDir, \"src\")) ? \"src\" : \"dist\");\n}\n\n/** Codemode workers and wasm live beside Atomic's split/development bundle. */\nlet codemodeWorkerDataUrl: URL | undefined;\nlet quickJSWasmPath: string | undefined;\n\nexport function getCodemodeWorkerUrl(): URL | undefined {\n\tif (codemodeWorkerDataUrl) return codemodeWorkerDataUrl;\n\tconst worker = isBunBinary\n\t\t? join(getPackageDir(), \"codemode-worker.js\")\n\t\t: isBundledBuild\n\t\t\t? join(dirname(resolve(process.argv[1])), \"codemode-worker.js\")\n\t\t\t: join(getModuleAssetRoot(), \"codemode-worker.js\");\n\tif (!isBunBinary && !isBundledBuild && !existsSync(worker)) return undefined;\n\t// A self-contained worker survives replacement or removal of the running install.\n\tcodemodeWorkerDataUrl ??= new URL(`data:text/javascript;base64,${readFileSync(worker).toString(\"base64\")}`);\n\treturn codemodeWorkerDataUrl;\n}\n\nexport function getQuickJSWasmPath(): string {\n\tquickJSWasmPath ??= isBunBinary\n\t\t? join(getPackageDir(), \"quickjs.wasm\")\n\t\t: isBundledBuild\n\t\t\t? join(dirname(resolve(process.argv[1])), \"quickjs.wasm\")\n\t\t\t: createRequire(__filename).resolve(\"quickjs-wasi/quickjs.wasm\");\n\treturn quickJSWasmPath;\n}\n\nexport type InstallChange = { kind: \"updated\"; version: string } | { kind: \"removed\" };\n\nexport function detectInstallChange(packageJsonPath = startupPackageJsonPath): InstallChange | undefined {\n\tif (isBunBinary || !packageJsonPath) return undefined;\n\tlet installed: PackageJson;\n\ttry {\n\t\tinstalled = JSON.parse(stripBom(readFileSync(packageJsonPath, \"utf-8\"))) as PackageJson;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"ENOENT\" ? { kind: \"removed\" } : undefined;\n\t}\n\treturn installed.version && installed.version !== VERSION\n\t\t? { kind: \"updated\", version: installed.version }\n\t\t: undefined;\n}\n/**\n * Get path to built-in themes directory (shipped with package)\n * - For Bun binary: theme/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/theme/\n * - For source (src/): src/modes/interactive/theme/\n */\nexport function getThemesDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"theme\");\n\t}\n\treturn join(getModuleAssetRoot(), \"modes\", \"interactive\", \"theme\");\n}\n\n/**\n * Get path to HTML export template directory (shipped with package)\n * - For Bun binary: export-html/ next to executable\n * - For Node.js (dist/): dist/core/export-html/\n * - For source (src/): src/core/export-html/\n */\nexport function getExportTemplateDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"export-html\");\n\t}\n\treturn join(getModuleAssetRoot(), \"core\", \"export-html\");\n}\n\n/** Get path to package.json */\nexport function getPackageJsonPath(): string {\n\treturn join(getPackageDir(), \"package.json\");\n}\n\n/** Get path to README.md */\nexport function getReadmePath(): string {\n\treturn resolve(join(getPackageDir(), \"README.md\"));\n}\n\n/** Get path to docs directory */\nexport function getDocsPath(): string {\n\treturn resolve(join(getPackageDir(), \"docs\"));\n}\n\n/** Get path to examples directory */\nexport function getExamplesPath(): string {\n\treturn resolve(join(getPackageDir(), \"examples\"));\n}\n\n/** Get path to CHANGELOG.md */\nexport function getChangelogPath(): string {\n\treturn resolve(join(getPackageDir(), \"CHANGELOG.md\"));\n}\n\n/**\n * Get path to built-in interactive assets directory.\n * - For Bun binary: assets/ next to executable\n * - For Node.js (dist/): dist/modes/interactive/assets/\n * - For source (src/): src/modes/interactive/assets/\n */\nexport function getInteractiveAssetsDir(): string {\n\tif (isBunBinary) {\n\t\treturn join(getPackageDir(), \"assets\");\n\t}\n\treturn join(getModuleAssetRoot(), \"modes\", \"interactive\", \"assets\");\n}\n\n/** Get path to a bundled interactive asset */\nexport function getBundledInteractiveAssetPath(name: string): string {\n\treturn join(getInteractiveAssetsDir(), name);\n}\n\n// =============================================================================\n// App Config (from package.json <appName>Config, with piConfig as a legacy shim)\n// =============================================================================\n\ninterface AppConfig {\n\tname?: string;\n\tconfigDir?: string;\n\tchangelogUrl?: string;\n}\n\ninterface PackageJson extends Record<string, unknown> {\n\tname?: string;\n\tversion?: string;\n\tpiConfig?: AppConfig;\n}\n\nlet pkg: PackageJson = {};\nlet startupPackageJsonPath: string | undefined;\ntry {\n\tconst packageJsonPath = getPackageJsonPath();\n\tpkg = JSON.parse(stripBom(readFileSync(packageJsonPath, \"utf-8\"))) as PackageJson;\n\tstartupPackageJsonPath = packageJsonPath;\n} catch (e: unknown) {\n\tconst err = e as NodeJS.ErrnoException;\n\tif (err.code !== \"ENOENT\") throw e;\n}\n\nfunction appNameFromPackageName(packageName: string | undefined): string | undefined {\n\tconst localName = packageName?.split(\"/\").pop()?.trim();\n\treturn localName && localName.length > 0 ? localName : undefined;\n}\n\nfunction readAppConfig(packageJson: PackageJson, appName: string | undefined): AppConfig | undefined {\n\tif (appName) {\n\t\tconst appConfig = packageJson[`${appName}Config`];\n\t\tif (appConfig && typeof appConfig === \"object\" && !Array.isArray(appConfig)) {\n\t\t\treturn appConfig as AppConfig;\n\t\t}\n\t}\n\treturn packageJson.piConfig;\n}\n\nexport const PACKAGE_NAME: string = pkg.name || \"@bastani/atomic\";\nconst packageAppName = appNameFromPackageName(PACKAGE_NAME);\nconst appConfig = readAppConfig(pkg, packageAppName);\nexport const APP_NAME: string = appConfig?.name || packageAppName || \"pi\";\nexport const APP_TITLE: string = appConfig?.name !== undefined || APP_NAME !== \"pi\" ? APP_NAME : \"π\";\nexport const CONFIG_DIR_NAME: string = appConfig?.configDir || (APP_NAME === \"pi\" ? \".pi\" : `.${APP_NAME}`);\nexport const LEGACY_CONFIG_DIR_NAME = \".pi\";\nexport const CONFIG_DIR_NAMES: readonly string[] =\n\tCONFIG_DIR_NAME === LEGACY_CONFIG_DIR_NAME ? [CONFIG_DIR_NAME] : [CONFIG_DIR_NAME, LEGACY_CONFIG_DIR_NAME];\nexport const VERSION: string = pkg.version || \"0.0.0\";\nexport const CHANGELOG_URL: string | undefined = appConfig?.changelogUrl?.trim() || undefined;\n\nconst ENV_PREFIX = APP_NAME.toUpperCase();\nexport const LEGACY_ENV_PREFIX = \"PI\";\n\n// e.g., ATOMIC_CODING_AGENT_DIR (with PI_CODING_AGENT_DIR as a compatibility alias)\nexport const ENV_AGENT_DIR = `${ENV_PREFIX}_CODING_AGENT_DIR`;\nexport const ENV_SESSION_DIR = `${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`;\nexport const ENV_PACKAGE_DIR = `${ENV_PREFIX}_PACKAGE_DIR`;\nexport const ENV_OFFLINE = `${ENV_PREFIX}_OFFLINE`;\nexport const ENV_SKIP_VERSION_CHECK = `${ENV_PREFIX}_SKIP_VERSION_CHECK`;\nexport const ENV_STARTUP_BENCHMARK = `${ENV_PREFIX}_STARTUP_BENCHMARK`;\nexport const ENV_TELEMETRY = `${ENV_PREFIX}_TELEMETRY`;\nexport const ENV_SHARE_VIEWER_URL = `${ENV_PREFIX}_SHARE_VIEWER_URL`;\nexport const ENV_CLEAR_ON_SHRINK = `${ENV_PREFIX}_CLEAR_ON_SHRINK`;\nexport const ENV_HARDWARE_CURSOR = `${ENV_PREFIX}_HARDWARE_CURSOR`;\nexport const ENV_CLIPBOARD_OSC52 = `${ENV_PREFIX}_CLIPBOARD_OSC52`;\nexport const ENV_TIMING = `${ENV_PREFIX}_TIMING`;\nexport const ENV_HEAP_MB = `${ENV_PREFIX}_HEAP_MB`;\nexport const ENV_CODEMODE_MAX_WORKERS = `${ENV_PREFIX}_CODEMODE_MAX_WORKERS`;\nexport const WORKFLOW_STAGE_SUBAGENT_GUARD_ENV = `${ENV_PREFIX}_WORKFLOW_STAGE_SUBAGENT_GUARD`;\nexport function getEnvNames(name: string): string[] {\n\tif (ENV_PREFIX === LEGACY_ENV_PREFIX || !name.startsWith(`${ENV_PREFIX}_`)) return [name];\n\treturn [name, `${LEGACY_ENV_PREFIX}_${name.slice(ENV_PREFIX.length + 1)}`];\n}\n\nexport function getEnvValue(name: string): string | undefined {\n\tfor (const candidate of getEnvNames(name)) {\n\t\tconst value = process.env[candidate];\n\t\tif (value !== undefined) return value;\n\t}\n\treturn undefined;\n}\n\nexport function hasEnvValue(name: string): boolean {\n\treturn getEnvValue(name) !== undefined;\n}\n\nexport function setEnvValue(name: string, value: string): void {\n\tprocess.env[name] = value;\n}\n\nexport function expandTildePath(path: string): string {\n\treturn normalizePath(path);\n}\n\nconst DEFAULT_SHARE_VIEWER_URL = \"https://pi.dev/session/\";\n\nexport const VERSION_ADOPTION_ENDPOINT =\n\t\"https://atomic-version-adoption.bastani-atomic.workers.dev/v1/version-adoption\";\n\n/** Get the share viewer URL for a gist ID */\nexport function getShareViewerUrl(gistId: string): string {\n\tconst baseUrl = getEnvValue(ENV_SHARE_VIEWER_URL) || DEFAULT_SHARE_VIEWER_URL;\n\treturn `${baseUrl}#${gistId}`;\n}\n\n// =============================================================================\n// User Config Paths (~/.atomic/agent/*)\n// =============================================================================\n\n/** Get the agent config directory (e.g., ~/.atomic/agent/) */\nexport function getAgentDir(): string {\n\tconst envDir = getEnvValue(ENV_AGENT_DIR);\n\tif (envDir) {\n\t\treturn expandTildePath(envDir);\n\t}\n\treturn join(getHomeDir(), CONFIG_DIR_NAME, \"agent\");\n}\n\n/** Get the legacy pi agent config directory (e.g., ~/.pi/agent/) */\nexport function getLegacyAgentDir(): string {\n\treturn join(getHomeDir(), LEGACY_CONFIG_DIR_NAME, \"agent\");\n}\n\n/** Get agent config directories in precedence order (primary first, then legacy). */\nexport function getAgentDirs(): string[] {\n\tconst primary = getAgentDir();\n\tif (hasEnvValue(ENV_AGENT_DIR) || CONFIG_DIR_NAME === LEGACY_CONFIG_DIR_NAME) {\n\t\treturn [primary];\n\t}\n\tconst legacy = getLegacyAgentDir();\n\treturn legacy === primary ? [primary] : [primary, legacy];\n}\n\n/** Get user config root directories in precedence order (primary first, then legacy). */\nexport function getUserConfigDirs(): string[] {\n\treturn CONFIG_DIR_NAMES.map((name) => join(getHomeDir(), name));\n}\n\n/** Get project config directories in precedence order (primary first, then legacy). */\nexport function getProjectConfigDirs(cwd: string): string[] {\n\treturn CONFIG_DIR_NAMES.map((name) => join(cwd, name));\n}\n\n/** Get a path inside every user config root directory. */\nexport function getUserConfigPaths(...segments: string[]): string[] {\n\treturn getUserConfigDirs().map((dir) => join(dir, ...segments));\n}\n\n/** Get a path inside every agent config directory. */\nexport function getAgentConfigPaths(...segments: string[]): string[] {\n\treturn getAgentDirs().map((dir) => join(dir, ...segments));\n}\n\n/** Get a path inside every project config directory. */\nexport function getProjectConfigPaths(cwd: string, ...segments: string[]): string[] {\n\treturn getProjectConfigDirs(cwd).map((dir) => join(dir, ...segments));\n}\n\n/** Model config paths from highest to lowest precedence: Atomic project/global, then Pi project/global. */\nexport function getModelsConfigPaths(cwd: string, agentDir: string = getAgentDir(), includeProject = true): string[] {\n\tconst globalPaths =\n\t\tagentDir === getAgentDir() ? getAgentConfigPaths(\"models.json\") : [join(agentDir, \"models.json\")];\n\tif (!includeProject) return globalPaths;\n\tconst projectPaths = getProjectConfigPaths(cwd, \"models.json\");\n\tconst paths: string[] = [];\n\tfor (let index = 0; index < Math.max(projectPaths.length, globalPaths.length); index++) {\n\t\tif (projectPaths[index]) paths.push(projectPaths[index]);\n\t\tif (globalPaths[index]) paths.push(globalPaths[index]);\n\t}\n\treturn [...new Set(paths)];\n}\n\n/** Get path to user's custom themes directory */\nexport function getCustomThemesDir(): string {\n\treturn join(getAgentDir(), \"themes\");\n}\n\n/** Get path to models.json */\nexport function getModelsPath(): string {\n\treturn join(getAgentDir(), \"models.json\");\n}\n\n/** Get path to auth.json */\nexport function getAuthPath(): string {\n\treturn join(getAgentDir(), \"auth.json\");\n}\n\n/** Get path to settings.json */\nexport function getSettingsPath(): string {\n\treturn join(getAgentDir(), \"settings.json\");\n}\n\n/** Get path to tools directory */\nexport function getToolsDir(): string {\n\treturn join(getAgentDir(), \"tools\");\n}\n\n/** Get path to managed binaries directory (fd, rg) */\nexport function getBinDir(): string {\n\treturn join(getAgentDir(), \"bin\");\n}\n\nconst EXTENSION_TRANSPILE_CACHE_FORMAT = \"ts-source-specifiers\";\n\n/**\n * Get path to the extension transpile cache directory (jiti fsCache).\n * Scoped by version and transform format so neither a release upgrade nor a\n * loader transform change reads stale transpiled output.\n */\nexport function getExtensionTranspileCacheDir(): string {\n\treturn join(getAgentDir(), \"cache\", \"jiti\", `${VERSION}+${EXTENSION_TRANSPILE_CACHE_FORMAT}`);\n}\n\n/** Get path to prompt templates directory */\nexport function getPromptsDir(): string {\n\treturn join(getAgentDir(), \"prompts\");\n}\n\n/** Get path to sessions directory */\nexport function getSessionsDir(): string {\n\treturn join(getAgentDir(), \"sessions\");\n}\n\n/** Get path to debug log file */\nexport function getDebugLogPath(): string {\n\treturn join(getAgentDir(), `${APP_NAME}-debug.log`);\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { AgentSessionInternalSurface as AgentSession } from "./agent-session-methods.ts";
2
+ import { type RecordedToolLoadout } from "./agent-session-state.ts";
2
3
  import type { AgentSessionReloadOptions, ExtensionBindings } from "./agent-session-types.js";
3
4
  import { ExtensionRunner } from "./extensions/index.js";
4
5
  import type { ExtensionProviderTransaction, ModelRuntime } from "./model-runtime.js";
@@ -43,7 +44,7 @@ export declare function getExtensionSourceLabel(this: AgentSession, extensionPat
43
44
  export declare function _applyExtensionBindings(this: AgentSession, runner: ExtensionRunner): void;
44
45
  export declare function refreshCurrentModelFromRegistry(this: AgentSession): Promise<void>;
45
46
  export declare function _refreshCurrentModelFromRegistry(this: AgentSession): Promise<void>;
46
- export declare function _bindExtensionCore(this: AgentSession, runner: ExtensionRunner, publication?: ExtensionPublicationGate, startupToolNames?: readonly string[]): void;
47
+ export declare function _bindExtensionCore(this: AgentSession, runner: ExtensionRunner, publication?: ExtensionPublicationGate, startupToolNames?: readonly string[], startupLoadout?: RecordedToolLoadout): void;
47
48
  export declare function reload(this: AgentSession, options?: AgentSessionReloadOptions): Promise<void>;
48
49
  /** Publish approved startup resources without replacing the session or restarting safe reporters. */
49
50
  export declare function completeStartupResources(this: AgentSession, resourceLoader: ResourceLoader): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-extension-bindings.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-extension-bindings.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAI9F,OAAO,KAAK,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAG7F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAYxD,OAAO,KAAK,EAAE,4BAA4B,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACrF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EAA0B,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAuBnF,cAAM,wBAAwB;IAC7B,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAyC;IACjE,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAyC;IACtE,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAyB;IACvD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAiB;IAChD,QAAQ,CAAC,mBAAmB,EAAE,4BAA4B,CAAC;IAC3D,OAAO,CAAC,gBAAgB,CAAS;IACjC,QAAQ,CAAC,WAAW,cAAqB;IACzC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgB;IACzC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkB;IACzC,OAAO,CAAC,SAAS,CAAS;IAE1B,YACC,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,eAAe,EACvB,YAAY,EAAE,YAAY,EAC1B,QAAQ,EAAE,MAAM,OAAO,EACvB,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,EAMrC;IAED,KAAK,CAAC,MAAM,EAAE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BzF;AAED,wBAAsB,+BAA+B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAEvF;AAED,wBAAsB,gCAAgC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CA0BxF;AAED,wBAAgB,kBAAkB,CACjC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,eAAe,EACvB,WAAW,CAAC,EAAE,wBAAwB,EACtC,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,GAClC,IAAI,CAwUN;AAED,wBAAsB,MAAM,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CAKnG;AAoUD,qGAAqG;AACrG,wBAAsB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBhH;AAMD;;;GAGG;AAEH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;CAYhD,CAAC"}
1
+ {"version":3,"file":"agent-session-extension-bindings.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-extension-bindings.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,OAAO,EAGN,KAAK,mBAAmB,EAExB,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAQ7F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAYxD,OAAO,KAAK,EAAE,4BAA4B,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACrF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EAA0B,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAuBnF,cAAM,wBAAwB;IAC7B,QAAQ,CAAC,cAAc,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AAMD;;;GAGG;AAEH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;CAYhD,CAAC"}
@@ -1,10 +1,10 @@
1
1
  import { basename, dirname } from "node:path";
2
- import { getCurrentSystemMessage } from "@bastani/pi-ai";
3
2
  import { clampThinkingLevel, resetApiProviders } from "@bastani/pi-ai/compat";
4
3
  import { executeNestedToolCall, getCallableTools } from "./agent-session-nested-tools.js";
5
- import { preservesInitialToolLoadout } from "./agent-session-state.js";
4
+ import { activatesAfterRecordedLoadout, preservesInitialToolLoadout, recordedToolLoadout, } from "./agent-session-state.js";
6
5
  import { replaceSessionTaskOwner } from "./agent-session-tasks.js";
7
6
  import { generateWorkflowSummary } from "./compaction/session-summarization.js";
7
+ import { ExtensionStartupError, startupCleanupFailureMessage, } from "./extension-startup-failure.js";
8
8
  import { hostInputError } from "./extensions/host-input.js";
9
9
  import { ExtensionRunner } from "./extensions/index.js";
10
10
  import { factoryAcquisitions, factoryRollbackError, rollbackFactoryAcquisitions, } from "./extensions/loader-rollback.js";
@@ -165,7 +165,7 @@ function startExtensions(session, runner, loader, event, finalize) {
165
165
  const failures = [];
166
166
  const unsubscribe = runner.onError((error) => {
167
167
  if (error.event === "session_start" || error.event === "resources_discover") {
168
- failures.push(new Error(`${error.extensionPath}: ${error.error}`));
168
+ failures.push({ extensionPath: error.extensionPath, event: error.event, message: error.error });
169
169
  }
170
170
  });
171
171
  try {
@@ -174,7 +174,7 @@ function startExtensions(session, runner, loader, event, finalize) {
174
174
  await runner.emit(event);
175
175
  await extendRunnerResources(session, runner, loader, event.reason === "reload" ? "reload" : "startup");
176
176
  if (failures.length)
177
- throw new AggregateError(failures, "Extension startup failed");
177
+ throw new ExtensionStartupError(failures);
178
178
  await finalize?.();
179
179
  if (runner === session.extensionRunner)
180
180
  runner.reportUnhandledMcpServers();
@@ -191,9 +191,8 @@ function startExtensions(session, runner, loader, event, finalize) {
191
191
  await session.dispose();
192
192
  }
193
193
  catch (cleanupError) {
194
- throw Object.assign(new AggregateError([cause, cleanupError], "Extension startup and cleanup failed"), {
195
- code: "ShutdownFailed",
196
- });
194
+ const errors = [cause, cleanupError];
195
+ throw Object.assign(new AggregateError(errors, startupCleanupFailureMessage("Extension startup and cleanup failed", errors)), { code: "ShutdownFailed" });
197
196
  }
198
197
  throw cause;
199
198
  });
@@ -314,7 +313,7 @@ export async function _refreshCurrentModelFromRegistry() {
314
313
  if (changedThinking)
315
314
  await this._extensionRunner.emit({ type: "thinking_level_select", ...changedThinking });
316
315
  }
317
- export function _bindExtensionCore(runner, publication, startupToolNames) {
316
+ export function _bindExtensionCore(runner, publication, startupToolNames, startupLoadout) {
318
317
  runner.bindWorkOwner(this);
319
318
  if (publication) {
320
319
  bindExtensionContextPublication(runner.createContext(), (effect, phase) => phase === "commit" ? publication.stageCommit(effect) : publication.stageStart(effect));
@@ -355,9 +354,12 @@ export function _bindExtensionCore(runner, publication, startupToolNames) {
355
354
  const refreshCandidateTools = () => {
356
355
  const definitions = candidateDefinitions();
357
356
  for (const [name, { definition }] of definitions) {
358
- if (startupToolNames === undefined &&
359
- !candidateRegistryNames.has(name) &&
360
- activatesOnRegistration(this, name, definition, this._toolRegistry.has(name)))
357
+ if (!candidateRegistryNames.has(name) &&
358
+ (startupLoadout
359
+ ? activatesAfterRecordedLoadout(this, startupLoadout, name, definition) &&
360
+ applyToolModifiers([name], this._defaultToolModifiers).includes(name)
361
+ : startupToolNames === undefined &&
362
+ activatesOnRegistration(this, name, definition, this._toolRegistry.has(name))))
361
363
  candidateActiveTools.push(name);
362
364
  candidateRegistryNames.add(name);
363
365
  }
@@ -641,6 +643,7 @@ export function _bindExtensionCore(runner, publication, startupToolNames) {
641
643
  getSystemPrompt: () => this.systemPrompt,
642
644
  getRouterModel: () => this.settingsManager.getRouterModel(),
643
645
  getModelRouting: () => this.settingsManager.getModelRouting(),
646
+ getHttpIdleTimeoutMs: () => this.settingsManager.getHttpIdleTimeoutMs(),
644
647
  getSkillCatalog: () => getSkillCatalog(publication?.resourceLoader ?? this._resourceLoader),
645
648
  getSystemPromptOptions: () => this._baseSystemPromptOptions,
646
649
  }, {
@@ -845,13 +848,13 @@ async function reloadOwnedGeneration(retainedRuntimes, options) {
845
848
  throw Object.assign(new AggregateError(discoveryFailures, "Reload discovery cleanup failed"), {
846
849
  code: "ShutdownFailed",
847
850
  });
848
- const recordedTools = reason === "startup" && this._usesDefaultTools && !preservesInitialToolLoadout(this)
849
- ? getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages)
851
+ const startupLoadout = reason === "startup" && this._usesDefaultTools && !preservesInitialToolLoadout(this)
852
+ ? recordedToolLoadout(this)
850
853
  : undefined;
851
- const startupToolNames = recordedTools
852
- ? applyToolModifiers((recordedTools.toolsAdded ?? []).map((tool) => tool.name), this._defaultToolModifiers)
854
+ const startupToolNames = startupLoadout
855
+ ? applyToolModifiers([...startupLoadout.current], this._defaultToolModifiers)
853
856
  : undefined;
854
- this._bindExtensionCore(candidateRunner, publication, startupToolNames);
857
+ this._bindExtensionCore(candidateRunner, publication, startupToolNames, startupLoadout);
855
858
  candidateRunner.setHostBindings(this._extensionHumanInput, this._extensionDiagnosticListener, humanInputBindingRevisions.get(this));
856
859
  candidateRunner.setUIContext(this._extensionUIContext, this._extensionMode, presentationOnlyBindings.get(this) ?? false);
857
860
  candidateRunner.bindCommandContext(this._extensionCommandContextActions);
@@ -981,12 +984,24 @@ export async function completeStartupResources(resourceLoader) {
981
984
  return trackSessionWork(this, async () => {
982
985
  this._resourceLoader = resourceLoader;
983
986
  const startNewcomers = this._extensionRunner.attachStartupExtensions(resourceLoader.getExtensions().extensions);
987
+ const recorded = preservesInitialToolLoadout(this) ? undefined : recordedToolLoadout(this);
988
+ const knownToolNames = new Set(this._toolRegistry.keys());
984
989
  this._buildRuntime({
990
+ // Keeps the tools the session activated or deactivated before startup completed.
985
991
  activeToolNames: this.getActiveToolNames(),
986
- includeAllExtensionTools: preservesInitialToolLoadout(this) ||
987
- getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages) === undefined,
992
+ includeAllExtensionTools: !recorded,
988
993
  preserveRunner: true,
989
994
  });
995
+ if (recorded) {
996
+ // Tools this completion registers for the first time were registered after the branch recorded its
997
+ // loadout, like extensions installed after it: they activate unless the branch mentioned them, as in
998
+ // `_restoreToolsFromTranscript`. Tools registered earlier keep the choices already made about them.
999
+ const newTools = [...this._toolRegistry.keys()].filter((name) => !knownToolNames.has(name) &&
1000
+ activatesAfterRecordedLoadout(this, recorded, name, this._toolDefinitions.get(name)?.definition) &&
1001
+ applyToolModifiers([name], this._defaultToolModifiers).includes(name));
1002
+ if (newTools.length > 0)
1003
+ this._setActiveTools([...this.getActiveToolNames(), ...newTools]);
1004
+ }
990
1005
  await this.refreshCurrentModelFromRegistry();
991
1006
  await startNewcomers();
992
1007
  assertSessionOpen(this);