@bastani/atomic 0.9.14 → 0.9.15

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 (525) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +1 -1
  3. package/dist/builtin/intercom/package.json +2 -2
  4. package/dist/builtin/mcp/CHANGELOG.md +14 -0
  5. package/dist/builtin/mcp/package.json +4 -4
  6. package/dist/builtin/mcp/sampling-handler.ts +2 -2
  7. package/dist/builtin/mcp/types.ts +1 -1
  8. package/dist/builtin/subagents/CHANGELOG.md +40 -0
  9. package/dist/builtin/subagents/README.md +5 -22
  10. package/dist/builtin/subagents/agents/code-simplifier.md +2 -2
  11. package/dist/builtin/subagents/agents/codebase-analyzer.md +2 -2
  12. package/dist/builtin/subagents/agents/codebase-locator.md +2 -2
  13. package/dist/builtin/subagents/agents/codebase-online-researcher.md +2 -2
  14. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -2
  15. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +2 -2
  16. package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -2
  17. package/dist/builtin/subagents/agents/worker.md +2 -2
  18. package/dist/builtin/subagents/package.json +4 -4
  19. package/dist/builtin/subagents/skills/subagent/SKILL.md +6 -6
  20. package/dist/builtin/subagents/src/agents/agent-loaders.ts +0 -4
  21. package/dist/builtin/subagents/src/agents/agent-management-helpers.ts +1 -12
  22. package/dist/builtin/subagents/src/agents/agent-management.ts +0 -1
  23. package/dist/builtin/subagents/src/agents/agent-serializer.ts +7 -6
  24. package/dist/builtin/subagents/src/agents/agent-types.ts +0 -1
  25. package/dist/builtin/subagents/src/extension/schemas.ts +2 -2
  26. package/dist/builtin/subagents/src/extension/startup-maintenance.ts +2 -2
  27. package/dist/builtin/subagents/src/intercom/result-intercom.ts +0 -127
  28. package/dist/builtin/subagents/src/runs/foreground/inprocess-run-sync.ts +1 -3
  29. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +15 -106
  30. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +0 -3
  31. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +2 -13
  32. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +2 -12
  33. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +1 -20
  34. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +0 -6
  35. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +10 -21
  36. package/dist/builtin/subagents/src/runs/inprocess/attempt-handles.ts +104 -0
  37. package/dist/builtin/subagents/src/runs/inprocess/index.ts +10 -21
  38. package/dist/builtin/subagents/src/runs/inprocess/prompt-behavior.ts +2 -3
  39. package/dist/builtin/subagents/src/runs/inprocess/runner.ts +11 -32
  40. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/temp-cleanup.ts +69 -0
  41. package/dist/builtin/subagents/src/shared/model-resolution.ts +1 -1
  42. package/dist/builtin/subagents/src/shared/types-config.ts +0 -4
  43. package/dist/builtin/subagents/src/shared/types-depth.ts +15 -103
  44. package/dist/builtin/subagents/src/shared/types-foreground-state.ts +56 -0
  45. package/dist/builtin/subagents/src/shared/types-results.ts +1 -59
  46. package/dist/builtin/subagents/src/shared/types-runtime.ts +0 -2
  47. package/dist/builtin/subagents/src/shared/types.ts +1 -1
  48. package/dist/builtin/subagents/src/shared/utils.ts +1 -1
  49. package/dist/builtin/subagents/src/slash/slash-live-state.ts +1 -1
  50. package/dist/builtin/web-access/package.json +2 -2
  51. package/dist/builtin/web-access/summary-review.ts +2 -2
  52. package/dist/builtin/web-access/web-search-summary.ts +2 -2
  53. package/dist/builtin/workflows/CHANGELOG.md +30 -0
  54. package/dist/builtin/workflows/README.md +2 -2
  55. package/dist/builtin/workflows/package.json +2 -2
  56. package/dist/builtin/workflows/src/extension/index.bundle.mjs +60473 -401
  57. package/dist/builtin/workflows/src/extension/public-types.ts +1 -1
  58. package/dist/builtin/workflows/src/extension/wiring.ts +1 -1
  59. package/dist/builtin/workflows/src/extension/workflow-heartbeat-delivery.ts +48 -4
  60. package/dist/builtin/workflows/src/extension/workflow-tool.ts +1 -1
  61. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +5 -0
  62. package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +35 -2
  63. package/dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts +1 -1
  64. package/dist/builtin/workflows/src/runs/foreground/stage-runner-pause.ts +6 -0
  65. package/dist/builtin/workflows/src/tui/chat-surface-message.ts +15 -13
  66. package/dist/builtin/workflows/src/tui/store-widget-installer.ts +25 -2
  67. package/dist/bun/cli.js +1 -1
  68. package/dist/bun/cli.js.map +1 -1
  69. package/dist/bun/register-bedrock.js +2 -2
  70. package/dist/bun/register-bedrock.js.map +1 -1
  71. package/dist/cli/auth-check.d.ts +1 -1
  72. package/dist/cli/auth-check.d.ts.map +1 -1
  73. package/dist/cli/auth-check.js +1 -1
  74. package/dist/cli/auth-check.js.map +1 -1
  75. package/dist/cli/credential-print.d.ts +1 -1
  76. package/dist/cli/credential-print.d.ts.map +1 -1
  77. package/dist/cli/credential-print.js +2 -2
  78. package/dist/cli/credential-print.js.map +1 -1
  79. package/dist/cli/file-processor.d.ts +1 -1
  80. package/dist/cli/file-processor.d.ts.map +1 -1
  81. package/dist/cli/file-processor.js.map +1 -1
  82. package/dist/cli/initial-message.d.ts +1 -1
  83. package/dist/cli/initial-message.d.ts.map +1 -1
  84. package/dist/cli/initial-message.js.map +1 -1
  85. package/dist/cli/list-models.js.map +1 -1
  86. package/dist/core/agent-session-auto-compaction.d.ts +1 -1
  87. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  88. package/dist/core/agent-session-auto-compaction.js +1 -1
  89. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  90. package/dist/core/agent-session-events.d.ts +1 -1
  91. package/dist/core/agent-session-events.d.ts.map +1 -1
  92. package/dist/core/agent-session-events.js +1 -1
  93. package/dist/core/agent-session-events.js.map +1 -1
  94. package/dist/core/agent-session-export.js.map +1 -1
  95. package/dist/core/agent-session-extension-bindings.js +1 -1
  96. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  97. package/dist/core/agent-session-message-queue.d.ts +1 -1
  98. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  99. package/dist/core/agent-session-message-queue.js.map +1 -1
  100. package/dist/core/agent-session-methods.d.ts +2 -2
  101. package/dist/core/agent-session-methods.d.ts.map +1 -1
  102. package/dist/core/agent-session-methods.js.map +1 -1
  103. package/dist/core/agent-session-models.d.ts +2 -2
  104. package/dist/core/agent-session-models.d.ts.map +1 -1
  105. package/dist/core/agent-session-models.js +2 -2
  106. package/dist/core/agent-session-models.js.map +1 -1
  107. package/dist/core/agent-session-prompt.d.ts +1 -1
  108. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  109. package/dist/core/agent-session-prompt.js.map +1 -1
  110. package/dist/core/agent-session-retry.d.ts +1 -1
  111. package/dist/core/agent-session-retry.d.ts.map +1 -1
  112. package/dist/core/agent-session-retry.js +1 -1
  113. package/dist/core/agent-session-retry.js.map +1 -1
  114. package/dist/core/agent-session-runtime-auth.js +1 -1
  115. package/dist/core/agent-session-runtime-auth.js.map +1 -1
  116. package/dist/core/agent-session-runtime.d.ts +1 -1
  117. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  118. package/dist/core/agent-session-runtime.js +1 -1
  119. package/dist/core/agent-session-runtime.js.map +1 -1
  120. package/dist/core/agent-session-services.d.ts +1 -1
  121. package/dist/core/agent-session-services.d.ts.map +1 -1
  122. package/dist/core/agent-session-services.js.map +1 -1
  123. package/dist/core/agent-session-state.d.ts +1 -1
  124. package/dist/core/agent-session-state.d.ts.map +1 -1
  125. package/dist/core/agent-session-state.js.map +1 -1
  126. package/dist/core/agent-session-tree.js.map +1 -1
  127. package/dist/core/agent-session-types.d.ts +1 -1
  128. package/dist/core/agent-session-types.d.ts.map +1 -1
  129. package/dist/core/agent-session-types.js.map +1 -1
  130. package/dist/core/agent-session.d.ts +1 -1
  131. package/dist/core/agent-session.d.ts.map +1 -1
  132. package/dist/core/agent-session.js.map +1 -1
  133. package/dist/core/anthropic-thinking-guard.d.ts +1 -1
  134. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  135. package/dist/core/anthropic-thinking-guard.js +1 -1
  136. package/dist/core/anthropic-thinking-guard.js.map +1 -1
  137. package/dist/core/auth-storage.d.ts +1 -1
  138. package/dist/core/auth-storage.d.ts.map +1 -1
  139. package/dist/core/auth-storage.js.map +1 -1
  140. package/dist/core/cache-stats.d.ts +1 -1
  141. package/dist/core/cache-stats.d.ts.map +1 -1
  142. package/dist/core/cache-stats.js.map +1 -1
  143. package/dist/core/cloudflare-gateway-binding.d.ts +1 -1
  144. package/dist/core/cloudflare-gateway-binding.d.ts.map +1 -1
  145. package/dist/core/cloudflare-gateway-binding.js +1 -1
  146. package/dist/core/cloudflare-gateway-binding.js.map +1 -1
  147. package/dist/core/codex-fast-mode.d.ts +2 -2
  148. package/dist/core/codex-fast-mode.d.ts.map +1 -1
  149. package/dist/core/codex-fast-mode.js +3 -2
  150. package/dist/core/codex-fast-mode.js.map +1 -1
  151. package/dist/core/compaction/branch-summarization.d.ts +2 -2
  152. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  153. package/dist/core/compaction/branch-summarization.js +2 -2
  154. package/dist/core/compaction/branch-summarization.js.map +1 -1
  155. package/dist/core/compaction/compaction-runner.d.ts +2 -2
  156. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  157. package/dist/core/compaction/compaction-runner.js.map +1 -1
  158. package/dist/core/compaction/compaction-types.d.ts +2 -2
  159. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  160. package/dist/core/compaction/compaction-types.js.map +1 -1
  161. package/dist/core/compaction/compaction.d.ts +1 -1
  162. package/dist/core/compaction/compaction.d.ts.map +1 -1
  163. package/dist/core/compaction/compaction.js.map +1 -1
  164. package/dist/core/compaction/fallback-planner.d.ts +1 -1
  165. package/dist/core/compaction/fallback-planner.d.ts.map +1 -1
  166. package/dist/core/compaction/fallback-planner.js.map +1 -1
  167. package/dist/core/compaction/planner-outcome.d.ts +1 -1
  168. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  169. package/dist/core/compaction/planner-outcome.js +1 -1
  170. package/dist/core/compaction/planner-outcome.js.map +1 -1
  171. package/dist/core/compaction/range-planner-diagnostics.d.ts +1 -1
  172. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  173. package/dist/core/compaction/range-planner-diagnostics.js +1 -1
  174. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  175. package/dist/core/compaction/range-planner.d.ts +2 -2
  176. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  177. package/dist/core/compaction/range-planner.js +2 -2
  178. package/dist/core/compaction/range-planner.js.map +1 -1
  179. package/dist/core/compaction/session-summarization.d.ts +2 -2
  180. package/dist/core/compaction/session-summarization.d.ts.map +1 -1
  181. package/dist/core/compaction/session-summarization.js +2 -2
  182. package/dist/core/compaction/session-summarization.js.map +1 -1
  183. package/dist/core/compaction/transcript-serialization.d.ts +1 -1
  184. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  185. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  186. package/dist/core/compaction/utils.d.ts +1 -1
  187. package/dist/core/compaction/utils.d.ts.map +1 -1
  188. package/dist/core/compaction/utils.js.map +1 -1
  189. package/dist/core/experimental.d.ts +1 -1
  190. package/dist/core/experimental.d.ts.map +1 -1
  191. package/dist/core/experimental.js.map +1 -1
  192. package/dist/core/export-html/tool-renderer.js.map +1 -1
  193. package/dist/core/extensions/agent-events.d.ts +2 -2
  194. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  195. package/dist/core/extensions/agent-events.js.map +1 -1
  196. package/dist/core/extensions/api-types.d.ts +2 -2
  197. package/dist/core/extensions/api-types.d.ts.map +1 -1
  198. package/dist/core/extensions/api-types.js.map +1 -1
  199. package/dist/core/extensions/context-types.d.ts +1 -7
  200. package/dist/core/extensions/context-types.d.ts.map +1 -1
  201. package/dist/core/extensions/context-types.js.map +1 -1
  202. package/dist/core/extensions/event-results.d.ts +1 -1
  203. package/dist/core/extensions/event-results.d.ts.map +1 -1
  204. package/dist/core/extensions/event-results.js.map +1 -1
  205. package/dist/core/extensions/index.d.ts +1 -1
  206. package/dist/core/extensions/index.d.ts.map +1 -1
  207. package/dist/core/extensions/index.js.map +1 -1
  208. package/dist/core/extensions/loader-api.js.map +1 -1
  209. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  210. package/dist/core/extensions/loader-virtual-modules.js +21 -9
  211. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  212. package/dist/core/extensions/provider-types.d.ts +2 -2
  213. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  214. package/dist/core/extensions/provider-types.js.map +1 -1
  215. package/dist/core/extensions/reactive-widget.d.ts +6 -0
  216. package/dist/core/extensions/reactive-widget.d.ts.map +1 -1
  217. package/dist/core/extensions/reactive-widget.js +62 -6
  218. package/dist/core/extensions/reactive-widget.js.map +1 -1
  219. package/dist/core/extensions/runner-context.d.ts +1 -1
  220. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  221. package/dist/core/extensions/runner-context.js.map +1 -1
  222. package/dist/core/extensions/runner-events.d.ts +1 -1
  223. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  224. package/dist/core/extensions/runner-events.js.map +1 -1
  225. package/dist/core/extensions/runner.d.ts +2 -2
  226. package/dist/core/extensions/runner.d.ts.map +1 -1
  227. package/dist/core/extensions/runner.js.map +1 -1
  228. package/dist/core/extensions/runtime-types.d.ts +2 -2
  229. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  230. package/dist/core/extensions/runtime-types.js.map +1 -1
  231. package/dist/core/extensions/tool-events.d.ts +1 -1
  232. package/dist/core/extensions/tool-events.d.ts.map +1 -1
  233. package/dist/core/extensions/tool-events.js.map +1 -1
  234. package/dist/core/extensions/tool-types.d.ts +2 -2
  235. package/dist/core/extensions/tool-types.d.ts.map +1 -1
  236. package/dist/core/extensions/tool-types.js.map +1 -1
  237. package/dist/core/extensions/ui-types.d.ts +2 -0
  238. package/dist/core/extensions/ui-types.d.ts.map +1 -1
  239. package/dist/core/extensions/ui-types.js.map +1 -1
  240. package/dist/core/fallback-models.d.ts +1 -1
  241. package/dist/core/fallback-models.d.ts.map +1 -1
  242. package/dist/core/fallback-models.js.map +1 -1
  243. package/dist/core/http-dispatcher.d.ts.map +1 -1
  244. package/dist/core/http-dispatcher.js +14 -0
  245. package/dist/core/http-dispatcher.js.map +1 -1
  246. package/dist/core/messages.d.ts +1 -1
  247. package/dist/core/messages.d.ts.map +1 -1
  248. package/dist/core/messages.js.map +1 -1
  249. package/dist/core/model-capabilities.d.ts +1 -1
  250. package/dist/core/model-capabilities.d.ts.map +1 -1
  251. package/dist/core/model-capabilities.js.map +1 -1
  252. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  253. package/dist/core/model-fallback-failures.js +18 -1
  254. package/dist/core/model-fallback-failures.js.map +1 -1
  255. package/dist/core/model-registry.d.ts +1 -1
  256. package/dist/core/model-registry.d.ts.map +1 -1
  257. package/dist/core/model-registry.js.map +1 -1
  258. package/dist/core/model-resolver-cli.js.map +1 -1
  259. package/dist/core/model-resolver-defaults.d.ts +1 -1
  260. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  261. package/dist/core/model-resolver-defaults.js +1 -1
  262. package/dist/core/model-resolver-defaults.js.map +1 -1
  263. package/dist/core/model-resolver-initial.d.ts +1 -1
  264. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  265. package/dist/core/model-resolver-initial.js.map +1 -1
  266. package/dist/core/model-resolver-patterns.d.ts +1 -1
  267. package/dist/core/model-resolver-patterns.d.ts.map +1 -1
  268. package/dist/core/model-resolver-patterns.js.map +1 -1
  269. package/dist/core/model-resolver-scope.d.ts +1 -1
  270. package/dist/core/model-resolver-scope.d.ts.map +1 -1
  271. package/dist/core/model-resolver-scope.js +1 -1
  272. package/dist/core/model-resolver-scope.js.map +1 -1
  273. package/dist/core/model-resolver-types.d.ts +1 -1
  274. package/dist/core/model-resolver-types.d.ts.map +1 -1
  275. package/dist/core/model-resolver-types.js.map +1 -1
  276. package/dist/core/model-runtime-auth.d.ts +1 -1
  277. package/dist/core/model-runtime-auth.d.ts.map +1 -1
  278. package/dist/core/model-runtime-auth.js.map +1 -1
  279. package/dist/core/model-runtime-providers.d.ts +2 -2
  280. package/dist/core/model-runtime-providers.d.ts.map +1 -1
  281. package/dist/core/model-runtime-providers.js +2 -2
  282. package/dist/core/model-runtime-providers.js.map +1 -1
  283. package/dist/core/model-runtime-restoration.d.ts +1 -1
  284. package/dist/core/model-runtime-restoration.d.ts.map +1 -1
  285. package/dist/core/model-runtime-restoration.js.map +1 -1
  286. package/dist/core/model-runtime-snapshot.d.ts +1 -1
  287. package/dist/core/model-runtime-snapshot.d.ts.map +1 -1
  288. package/dist/core/model-runtime-snapshot.js.map +1 -1
  289. package/dist/core/model-runtime-streaming.d.ts +1 -1
  290. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  291. package/dist/core/model-runtime-streaming.js +1 -1
  292. package/dist/core/model-runtime-streaming.js.map +1 -1
  293. package/dist/core/model-runtime-types.d.ts +1 -1
  294. package/dist/core/model-runtime-types.d.ts.map +1 -1
  295. package/dist/core/model-runtime-types.js.map +1 -1
  296. package/dist/core/model-runtime.d.ts +8 -1
  297. package/dist/core/model-runtime.d.ts.map +1 -1
  298. package/dist/core/model-runtime.js +15 -3
  299. package/dist/core/model-runtime.js.map +1 -1
  300. package/dist/core/models-store.d.ts +1 -1
  301. package/dist/core/models-store.d.ts.map +1 -1
  302. package/dist/core/models-store.js.map +1 -1
  303. package/dist/core/oauth-login.d.ts +1 -1
  304. package/dist/core/oauth-login.d.ts.map +1 -1
  305. package/dist/core/oauth-login.js.map +1 -1
  306. package/dist/core/oauth-provider-metadata.d.ts +1 -1
  307. package/dist/core/oauth-provider-metadata.d.ts.map +1 -1
  308. package/dist/core/oauth-provider-metadata.js.map +1 -1
  309. package/dist/core/openai-responses-payload-sanitizer.d.ts +1 -1
  310. package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -1
  311. package/dist/core/openai-responses-payload-sanitizer.js.map +1 -1
  312. package/dist/core/provider-attribution.d.ts +1 -1
  313. package/dist/core/provider-attribution.d.ts.map +1 -1
  314. package/dist/core/provider-attribution.js.map +1 -1
  315. package/dist/core/provider-composer-internal.d.ts +1 -1
  316. package/dist/core/provider-composer-internal.d.ts.map +1 -1
  317. package/dist/core/provider-composer-internal.js.map +1 -1
  318. package/dist/core/provider-composer.d.ts +1 -1
  319. package/dist/core/provider-composer.d.ts.map +1 -1
  320. package/dist/core/provider-composer.js +2 -2
  321. package/dist/core/provider-composer.js.map +1 -1
  322. package/dist/core/provider-context-usage.d.ts.map +1 -1
  323. package/dist/core/provider-context-usage.js.map +1 -1
  324. package/dist/core/remote-catalog-provider.d.ts +1 -1
  325. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  326. package/dist/core/remote-catalog-provider.js.map +1 -1
  327. package/dist/core/runtime-credentials.d.ts +1 -1
  328. package/dist/core/runtime-credentials.d.ts.map +1 -1
  329. package/dist/core/runtime-credentials.js.map +1 -1
  330. package/dist/core/sdk-types.d.ts +1 -1
  331. package/dist/core/sdk-types.d.ts.map +1 -1
  332. package/dist/core/sdk-types.js.map +1 -1
  333. package/dist/core/sdk.d.ts +1 -1
  334. package/dist/core/sdk.d.ts.map +1 -1
  335. package/dist/core/sdk.js +30 -6
  336. package/dist/core/sdk.js.map +1 -1
  337. package/dist/core/session-manager-core.d.ts +2 -2
  338. package/dist/core/session-manager-core.d.ts.map +1 -1
  339. package/dist/core/session-manager-core.js.map +1 -1
  340. package/dist/core/session-manager-entries.d.ts +1 -1
  341. package/dist/core/session-manager-entries.d.ts.map +1 -1
  342. package/dist/core/session-manager-entries.js.map +1 -1
  343. package/dist/core/session-manager-list.js.map +1 -1
  344. package/dist/core/session-manager-types.d.ts +1 -1
  345. package/dist/core/session-manager-types.d.ts.map +1 -1
  346. package/dist/core/session-manager-types.js.map +1 -1
  347. package/dist/core/session-manager-validation.js +1 -1
  348. package/dist/core/session-manager-validation.js.map +1 -1
  349. package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
  350. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  351. package/dist/core/settings-manager-basic-accessors.js +11 -0
  352. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  353. package/dist/core/settings-types.d.ts +2 -1
  354. package/dist/core/settings-types.d.ts.map +1 -1
  355. package/dist/core/settings-types.js.map +1 -1
  356. package/dist/core/summarization-retry.d.ts +1 -1
  357. package/dist/core/summarization-retry.d.ts.map +1 -1
  358. package/dist/core/summarization-retry.js.map +1 -1
  359. package/dist/core/tools/bash-session-environment.d.ts +1 -1
  360. package/dist/core/tools/bash-session-environment.d.ts.map +1 -1
  361. package/dist/core/tools/bash-session-environment.js.map +1 -1
  362. package/dist/core/tools/oversized-tool-result.d.ts +1 -1
  363. package/dist/core/tools/oversized-tool-result.d.ts.map +1 -1
  364. package/dist/core/tools/oversized-tool-result.js.map +1 -1
  365. package/dist/core/tools/read-url.d.ts +1 -1
  366. package/dist/core/tools/read-url.d.ts.map +1 -1
  367. package/dist/core/tools/read-url.js.map +1 -1
  368. package/dist/core/tools/read.d.ts.map +1 -1
  369. package/dist/core/tools/read.js.map +1 -1
  370. package/dist/core/tools/render-utils.d.ts +1 -1
  371. package/dist/core/tools/render-utils.d.ts.map +1 -1
  372. package/dist/core/tools/render-utils.js.map +1 -1
  373. package/dist/core/tools/resource-selectors.d.ts +1 -1
  374. package/dist/core/tools/resource-selectors.d.ts.map +1 -1
  375. package/dist/core/tools/resource-selectors.js +2 -7
  376. package/dist/core/tools/resource-selectors.js.map +1 -1
  377. package/dist/core/typebox-compat.js +1 -1
  378. package/dist/core/typebox-compat.js.map +1 -1
  379. package/dist/core/usage-totals.d.ts +1 -1
  380. package/dist/core/usage-totals.d.ts.map +1 -1
  381. package/dist/core/usage-totals.js.map +1 -1
  382. package/dist/extensions/llama/provider.d.ts +1 -1
  383. package/dist/extensions/llama/provider.d.ts.map +1 -1
  384. package/dist/extensions/llama/provider.js +1 -1
  385. package/dist/extensions/llama/provider.js.map +1 -1
  386. package/dist/main-app-mode.d.ts +1 -1
  387. package/dist/main-app-mode.d.ts.map +1 -1
  388. package/dist/main-app-mode.js.map +1 -1
  389. package/dist/main-session-options.js +1 -1
  390. package/dist/main-session-options.js.map +1 -1
  391. package/dist/modes/interactive/components/assistant-message.d.ts +1 -1
  392. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  393. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  394. package/dist/modes/interactive/components/chat-message-renderer.d.ts +1 -1
  395. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  396. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  397. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  398. package/dist/modes/interactive/components/login-dialog.d.ts +1 -1
  399. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  400. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  401. package/dist/modes/interactive/components/model-selector.d.ts +1 -1
  402. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  403. package/dist/modes/interactive/components/model-selector.js +1 -1
  404. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  405. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
  406. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  407. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  408. package/dist/modes/interactive/components/settings-selector-handlers.js.map +1 -1
  409. package/dist/modes/interactive/components/settings-selector-types.d.ts +1 -1
  410. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  411. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  412. package/dist/modes/interactive/interactive-auth-routing.js +1 -1
  413. package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
  414. package/dist/modes/interactive/interactive-deferred-startup.js +1 -1
  415. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  416. package/dist/modes/interactive/interactive-extension-context.js +26 -0
  417. package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
  418. package/dist/modes/interactive/interactive-extension-runtime.js +7 -2
  419. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  420. package/dist/modes/interactive/interactive-mode-base.d.ts +1 -0
  421. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  422. package/dist/modes/interactive/interactive-mode-base.js +1 -0
  423. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  424. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  425. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  426. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  427. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  428. package/dist/modes/interactive/interactive-mode-helpers.js +1 -1
  429. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  430. package/dist/modes/interactive/interactive-mode-surface.d.ts +2 -0
  431. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  432. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  433. package/dist/modes/interactive/model-catalog-refresh.d.ts +1 -1
  434. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
  435. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
  436. package/dist/modes/interactive/streaming-assistant-message.d.ts +1 -1
  437. package/dist/modes/interactive/streaming-assistant-message.d.ts.map +1 -1
  438. package/dist/modes/interactive/streaming-assistant-message.js.map +1 -1
  439. package/dist/modes/interactive-engine/engine-custom-ui.d.ts +3 -0
  440. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  441. package/dist/modes/interactive-engine/engine-custom-ui.js +26 -3
  442. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  443. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  444. package/dist/modes/interactive-engine/remote-component.d.ts +2 -1
  445. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  446. package/dist/modes/interactive-engine/remote-component.js +14 -0
  447. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  448. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
  449. package/dist/modes/json-event.d.ts +1 -1
  450. package/dist/modes/json-event.d.ts.map +1 -1
  451. package/dist/modes/json-event.js.map +1 -1
  452. package/dist/modes/print-mode.d.ts +1 -1
  453. package/dist/modes/print-mode.d.ts.map +1 -1
  454. package/dist/modes/print-mode.js.map +1 -1
  455. package/dist/modes/rpc/rpc-client-api.d.ts +2 -2
  456. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  457. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  458. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  459. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  460. package/dist/modes/rpc/rpc-client.js.map +1 -1
  461. package/dist/modes/rpc/rpc-extension-ui.d.ts.map +1 -1
  462. package/dist/modes/rpc/rpc-extension-ui.js +4 -1
  463. package/dist/modes/rpc/rpc-extension-ui.js.map +1 -1
  464. package/dist/modes/rpc/rpc-provider-auth.d.ts +1 -1
  465. package/dist/modes/rpc/rpc-provider-auth.d.ts.map +1 -1
  466. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  467. package/dist/modes/rpc/rpc-types.d.ts +2 -2
  468. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  469. package/dist/modes/rpc/rpc-types.js.map +1 -1
  470. package/dist/utils/tool-result-images.d.ts +1 -1
  471. package/dist/utils/tool-result-images.d.ts.map +1 -1
  472. package/dist/utils/tool-result-images.js.map +1 -1
  473. package/docs/custom-provider.md +11 -8
  474. package/docs/development.md +0 -2
  475. package/docs/extensions.md +2 -2
  476. package/docs/json.md +1 -1
  477. package/docs/models/artificial-analysis-index.md +2 -2
  478. package/docs/models/model-selection.md +8 -8
  479. package/docs/models/pareto-efficiency.md +10 -10
  480. package/docs/models.md +9 -3
  481. package/docs/packages.md +1 -1
  482. package/docs/providers.md +5 -3
  483. package/docs/quickstart.md +1 -1
  484. package/docs/rpc.md +1 -1
  485. package/docs/sdk.md +2 -2
  486. package/docs/session-format.md +2 -2
  487. package/docs/settings.md +2 -1
  488. package/docs/subagents.md +5 -6
  489. package/docs/tui.md +3 -0
  490. package/docs/workflows.md +3 -1
  491. package/examples/extensions/README.md +1 -1
  492. package/examples/extensions/custom-footer.ts +1 -1
  493. package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
  494. package/examples/extensions/custom-provider-gitlab-duo/index.ts +1 -1
  495. package/examples/extensions/custom-provider-gitlab-duo/test.ts +1 -1
  496. package/examples/extensions/handoff.ts +2 -2
  497. package/examples/extensions/hello.ts +1 -1
  498. package/examples/extensions/plan-mode/index.ts +1 -1
  499. package/examples/extensions/preset.ts +1 -1
  500. package/examples/extensions/qna.ts +1 -1
  501. package/examples/extensions/subagent/display.ts +1 -1
  502. package/examples/extensions/subagent/runner.ts +1 -1
  503. package/examples/extensions/subagent/types.ts +1 -1
  504. package/examples/extensions/summarize.ts +2 -2
  505. package/examples/extensions/tool-override.ts +1 -1
  506. package/examples/sdk/02-custom-model.ts +1 -1
  507. package/examples/sdk/12-full-control.ts +1 -1
  508. package/examples/sdk/README.md +1 -1
  509. package/npm-shrinkwrap.json +54 -31
  510. package/package.json +3 -3
  511. package/dist/builtin/subagents/src/extension/fanout-child.ts +0 -259
  512. package/dist/builtin/subagents/src/runs/inprocess/nested-routing.ts +0 -218
  513. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-api.ts +0 -55
  514. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-control.ts +0 -178
  515. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-core.ts +0 -187
  516. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-paths.ts +0 -57
  517. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-projection.ts +0 -42
  518. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-registry.ts +0 -352
  519. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-rendering.ts +0 -136
  520. package/dist/builtin/subagents/src/runs/inprocess/runtime-support/nested-sanitize.ts +0 -252
  521. package/dist/builtin/subagents/src/shared/types-nested.ts +0 -127
  522. package/dist/core/copilot-env-routing.d.ts +0 -36
  523. package/dist/core/copilot-env-routing.d.ts.map +0 -1
  524. package/dist/core/copilot-env-routing.js +0 -94
  525. package/dist/core/copilot-env-routing.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,uBAAuB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAKlG,8EAA8E;AAC9E,MAAM,CAAC,MAAM,kCAAkC,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;A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ACH,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 \"@earendil-works/pi-ai\";\nimport { ModelsError } from \"@earendil-works/pi-ai\";\nimport { resolveCliModel } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport type { Args } from \"./args.ts\";\n\nexport type CredentialPrintKind = \"api_key\" | \"bearer_token\";\n\n/** Bearer tokens are refreshed unless they still have this much life left. */\nexport const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;\n\n/**\n * Failure taxonomy. Each member owns one exit code, so a caller can branch on\n * the status without parsing stderr.\n */\nexport type CredentialPrintErrorCode =\n\t| \"Usage\"\n\t| \"NoCredentialConfigured\"\n\t| \"ProviderAmbiguous\"\n\t| \"KindUnsupportedForProvider\"\n\t| \"RefreshFailed\"\n\t| \"MinValidityUnreachable\"\n\t| \"OAuthUnavailable\"\n\t| \"CredentialNotEmitted\"\n\t| \"CredentialTruncated\";\n\n/**\n * Exported so a test can walk the whole taxonomy: every declared code has to\n * name an exercised path, and the record type makes a new member without an\n * exit code a compile error rather than a review miss.\n *\n * Every one of these leaves stdout empty except `CredentialTruncated`, which\n * exists to report the one case where it cannot be: bytes already went out and\n * cannot be recalled. `STDOUT_EMPTY_ON_EXIT` names that split so the taxonomy\n * test asserts it rather than assuming it.\n */\nexport const EXIT_CODES: Record<CredentialPrintErrorCode, number> = {\n\tUsage: 1,\n\tNoCredentialConfigured: 2,\n\tProviderAmbiguous: 3,\n\tKindUnsupportedForProvider: 4,\n\tRefreshFailed: 5,\n\tMinValidityUnreachable: 6,\n\tOAuthUnavailable: 7,\n\tCredentialNotEmitted: 8,\n\tCredentialTruncated: 9,\n};\n\n/** The codes whose contract is an empty stdout. See `EXIT_CODES`. */\nexport const STDOUT_EMPTY_ON_EXIT: ReadonlySet<CredentialPrintErrorCode> = new Set(\n\t(Object.keys(EXIT_CODES) as CredentialPrintErrorCode[]).filter((code) => code !== \"CredentialTruncated\"),\n);\n\nexport class CredentialPrintError extends Error {\n\treadonly code: CredentialPrintErrorCode;\n\treadonly exitCode: number;\n\n\tconstructor(code: CredentialPrintErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CredentialPrintError\";\n\t\tthis.code = code;\n\t\tthis.exitCode = EXIT_CODES[code];\n\t}\n}\n\n/**\n * A credential in transit.\n *\n * Every path that would copy the value into a string is closed: `toString`,\n * `toJSON`, and `Symbol.toPrimitive` throw rather than return, so a template\n * literal, `JSON.stringify`, or string concatenation fails loudly instead of\n * leaking into a log line, a transcript, or an error message. `inspect` — which\n * `console.log` and Node's error formatting use — renders a placeholder.\n *\n * `take()` is the single exit, and it works once.\n */\nexport class Secret {\n\t#value: string | undefined;\n\n\tconstructor(value: string) {\n\t\tthis.#value = value;\n\t}\n\n\t/** Consume the secret. A second call is a bug, not a second read. */\n\ttake(): string {\n\t\tconst value = this.#value;\n\t\tif (value === undefined) {\n\t\t\tthrow new Error(\"Secret has already been consumed\");\n\t\t}\n\t\tthis.#value = undefined;\n\t\treturn value;\n\t}\n\n\ttoString(): never {\n\t\tthrow new Error(\"A Secret cannot be converted to a string; use take()\");\n\t}\n\n\ttoJSON(): never {\n\t\tthrow new Error(\"A Secret cannot be serialized; use take()\");\n\t}\n\n\t[Symbol.toPrimitive](): never {\n\t\tthrow new Error(\"A Secret cannot be interpolated; use take()\");\n\t}\n\n\t[inspect.custom](): string {\n\t\treturn \"[Secret]\";\n\t}\n}\n\n/** Public readiness fields emitted with a credential under `auth check --json --credentials`. */\nexport interface CredentialJsonFields {\n\tstatus: string;\n\tprovider: string;\n\tauthType?: string;\n}\n\n/**\n * The only function in `src` that opens a `Secret`.\n *\n * Its two `Secret.take()` calls are the only call sites in `src`, and the\n * source-wide credential-egress test pins that list. This function builds one\n * payload and returns it only to `emitCredential`; no caller receives a plain\n * credential string.\n */\nfunction credentialPayload(secret: Secret, jsonFields: CredentialJsonFields | undefined): string {\n\tif (jsonFields === undefined) return `${secret.take()}\\n`;\n\n\tconst { status, provider, authType } = jsonFields;\n\tif (\n\t\ttypeof status !== \"string\" ||\n\t\ttypeof provider !== \"string\" ||\n\t\t(authType !== undefined && typeof authType !== \"string\")\n\t) {\n\t\tthrow new Error(\"Invalid credential JSON fields\");\n\t}\n\n\t// Allowlist the non-secret envelope before opening the Secret. That leaves no\n\t// formatter, logger, or error path between take() and the guarded stdout write.\n\tconst fields = JSON.stringify({\n\t\tstatus,\n\t\tprovider,\n\t\t...(authType === undefined ? {} : { authType }),\n\t});\n\tif (fields === undefined || !fields.startsWith(\"{\") || !fields.endsWith(\"}\")) {\n\t\tthrow new Error(\"Invalid credential JSON envelope\");\n\t}\n\treturn `${fields.slice(0, -1)},\"credentials\":${JSON.stringify(secret.take())}}\\n`;\n}\n\n/**\n * The single credential egress in `src`.\n *\n * `credentialPayload` opens the secret only while building this one payload,\n * and this guarded write is the only path that hands it to real stdout. A\n * caller — `main.ts` included — receives a `Secret` it cannot read, print, or\n * serialize, so it cannot add a second export path without crossing this door.\n * `test/credential-print.test.ts` pins both the `take()` sites and every\n * data-bearing real-stdout write in `packages/coding-agent/src`.\n *\n * A failed payload write is answered from the stream rather than from the shape\n * of the error, because `bytesWritten` says how much of the credential actually\n * left and the right report differs for each amount.\n *\n * Nothing left — the write call threw, or the callback failed with the counter\n * unmoved — is `CredentialNotEmitted` (exit 8) with stdout provably empty,\n * which is what that exit promises. It must not fall through to the caller's\n * credential-resolution catch, which would report exit 2.\n *\n * All of it left and the failure came after: the caller holds the credential it\n * asked for, so this is reported on stderr with the exit code left at 0, for\n * the same reason the trailing drain is. A non-zero exit over a stream carrying\n * a whole credential is the thing this door never produces.\n *\n * Part of it left is neither. Those bytes cannot be recalled, so stdout is not\n * empty and cannot be made empty; but they are a fragment, not a credential,\n * and reporting success over them would hand a caller a truncated secret it\n * cannot tell from a whole one. That case gets `CredentialTruncated` (exit 9),\n * the one code in this taxonomy whose contract is *not* an empty stdout —\n * stated as such in `EXIT_CODES` and asserted through `STDOUT_EMPTY_ON_EXIT`,\n * rather than left for a caller to discover.\n */\nexport async function emitCredential(secret: Secret, jsonFields: CredentialJsonFields | undefined): Promise<void> {\n\tconst payload = credentialPayload(secret, jsonFields);\n\ttry {\n\t\tawait writeRawStdoutOnce(payload);\n\t} catch (error) {\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"all\") {\n\t\t\t// The caller holds the whole credential. Exiting non-zero here would be\n\t\t\t// a non-zero exit over a stream carrying it, which this door never does.\n\t\t\tconsole.error(\n\t\t\t\t`Warning: the credential reached stdout but the write did not complete cleanly: ${error.message}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"partial\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"CredentialTruncated\",\n\t\t\t\t\"Only part of the credential reached stdout; discard the output, it is not a usable credential\",\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"CredentialNotEmitted\",\n\t\t\t\"Failed to write the credential to stdout; nothing was emitted\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\ttry {\n\t\tawait flushRawStdout();\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Warning: the credential was written to stdout but the stream did not drain cleanly: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n}\n\n/**\n * The single place a thrown value becomes an exit code for this door.\n *\n * `main.ts` routes every failure through here. Every code it can produce leaves\n * stdout empty, so an exit code from this door never contradicts the stream.\n */\nexport function toCredentialPrintError(error: unknown): CredentialPrintError {\n\tif (error instanceof CredentialPrintError) return error;\n\treturn new CredentialPrintError(\n\t\t\"NoCredentialConfigured\",\n\t\terror instanceof Error ? error.message : \"Failed to resolve credential\",\n\t\t{ cause: error },\n\t);\n}\n\n/**\n * The only two fields of `Args` this door accepts.\n *\n * Validation is an allowlist rather than a list of refusals, because the\n * refusal list only held while the dispatcher happened to ignore every other\n * flag. `--export <path>`, `--session-dir <path>`, `--print`, and `--help` are\n * all parsed by `parseArgs`; under an exclusion check they passed silently and\n * the door's \"no file sink\" guarantee rested on a downstream accident.\n */\nconst ACCEPTED_ARG_FIELDS: ReadonlySet<string> = new Set([\"model\", \"provider\"]);\n\n/** Names every field of a parsed `Args` that the caller actually set. */\nfunction populatedArgFields(args: Args): string[] {\n\tconst populated: string[] = [];\n\tfor (const [field, value] of Object.entries(args)) {\n\t\tif (ACCEPTED_ARG_FIELDS.has(field) || value === undefined) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length > 0) populated.push(field);\n\t\t} else if (value instanceof Map) {\n\t\t\tif (value.size > 0) populated.push(field);\n\t\t} else {\n\t\t\tpopulated.push(field);\n\t\t}\n\t}\n\treturn populated;\n}\n\nexport function validateCredentialPrintArgs(args: Args): void {\n\tif (!args.model?.trim()) {\n\t\tthrow new CredentialPrintError(\"Usage\", \"Credential printing requires --model <model>\");\n\t}\n\tif (args.apiKey !== undefined) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t\"Credential printing reads configured credentials; --api-key is not supported\",\n\t\t);\n\t}\n\tconst refused = populatedArgFields(args);\n\tif (refused.length > 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t`Credential printing only accepts --provider and --model (refused: ${refused.join(\", \")})`,\n\t\t);\n\t}\n}\n\n/**\n * Provider-supplied text with anything credential-bearing masked.\n *\n * A failed refresh is reported on stderr, and the provider composes that\n * message. Most describe the failure; some quote the request they sent or the\n * body they got back, either of which can carry the very value this door exists\n * to keep off every stream except stdout. Masking keeps the diagnosis — which\n * is what makes the exit code actionable — without putting the secret in a log,\n * a terminal scrollback, or a CI transcript.\n *\n * Two passes, because either alone leaves a gap. Shape catches a value wherever\n * it appears, but only for the formats that announce themselves. Context\n * catches an opaque value — an `x-api-key`, which is just bytes — by the name it\n * is filed under, in the header, JSON, and query spellings a quoted request or\n * response body uses.\n */\nconst CREDENTIAL_SHAPES: readonly RegExp[] = [\n\t// `Authorization: Bearer <token>`, the form an echoed request header takes.\n\t/\\bBearer\\s+[\\w.~+/-]+=*/giu,\n\t// JWTs, which several providers return verbatim in an error body.\n\t/\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]+/gu,\n\t// Prefixed API keys: sk-…, sk_live_…, api-key-…, and the same shapes again.\n\t/\\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\\w-]{12,}/giu,\n];\n\n/**\n * Field names whose value is the credential, however opaque that value looks.\n * `x-api-key` is the case shape-matching cannot reach: the value is just bytes.\n */\nconst CREDENTIAL_FIELD_NAME =\n\t\"(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)\";\n\n/**\n * Auth schemes that stand between the field name and the value it introduces.\n *\n * Without them the header matcher stops at the space after `Bearer`: it redacts\n * the scheme and leaves the token, and having consumed the `Bearer` the shape\n * pass depends on, that pass can no longer reach the token either. An opaque\n * `Authorization: Bearer <token>` then survives both passes.\n */\nconst CREDENTIAL_AUTH_SCHEME = \"(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)\";\n\nconst CREDENTIAL_CONTEXTS: readonly RegExp[] = [\n\t// Header or YAML-ish: `x-api-key: abc123`, to end of line, and the scheme\n\t// form `Authorization: Bearer abc123` with it.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*:\\s*(?:${CREDENTIAL_AUTH_SCHEME}\\s+)?[^\\s,;}\"']+`, \"giu\"),\n\t// JSON: `\"api_key\": \"abc123\"` / `'token':'abc123'`, quoted value.\n\tnew RegExp(String.raw`([\"']?)${CREDENTIAL_FIELD_NAME}\\1\\s*:\\s*([\"'])(?:(?!\\2).)*\\2`, \"giu\"),\n\t// Query string or form body: `?api_key=abc123&…`.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*=\\s*[^\\s&,;}\"']+`, \"giu\"),\n];\n\nexport function redactCredentialShapes(text: string): string {\n\tconst byContext = CREDENTIAL_CONTEXTS.reduce(\n\t\t(masked, context) =>\n\t\t\tmasked.replace(context, (match) => {\n\t\t\t\t// Keep the field name so the diagnosis still says which one failed;\n\t\t\t\t// replace only what follows the separator.\n\t\t\t\tconst separator = /[:=]/u.exec(match);\n\t\t\t\treturn separator ? `${match.slice(0, separator.index + 1)} [redacted]` : \"[redacted]\";\n\t\t\t}),\n\t\ttext,\n\t);\n\treturn CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, \"[redacted]\"), byContext);\n}\n\n/**\n * The literal phrase pi-ai throws when a refresh itself failed, from inside\n * `credentials.modify` and therefore before anything is persisted. This is the\n * only oauth-coded error that can claim the stored credential was left alone.\n */\nexport const OAUTH_REFRESH_FAILED_PHRASE = \"OAuth refresh failed for\";\n\n/**\n * The literal phrase pi-ai throws when a refresh succeeded but the rotated\n * token still expires inside the requested window. It is the only signal that\n * separates exit 6 from exit 5.\n */\nexport const OAUTH_EXPIRES_TOO_SOON_PHRASE = \"expires too soon\";\n\n/**\n * pi-ai raises three different `oauth`-coded failures from\n * `dist/auth/resolve.js`, and only one of them is a failed refresh.\n *\n * `OAuth auth derivation failed for <provider>` is thrown after\n * `credentials.modify` has already persisted a rotated credential, and also on\n * the branch where no refresh was attempted at all — so it gets its own code\n * and a message that makes no claim about the stored credential. Treating it as\n * `RefreshFailed` asserted a rollback the command never verified.\n *\n * Classification reads the raw message, because redaction could rewrite the\n * phrase it matches on; only the text that becomes a user-facing message is\n * redacted. The unredacted error stays reachable as `cause`, which this door\n * never logs.\n *\n * `test/credential-print.test.ts` pins both phrases against the installed\n * pi-ai build, so an upstream rewording fails the suite rather than silently\n * collapsing exit 6 into exit 5.\n */\nexport function classifyOAuthFailure(error: ModelsError): CredentialPrintError {\n\tconst detail = redactCredentialShapes(error.message);\n\tif (error.message.includes(OAUTH_EXPIRES_TOO_SOON_PHRASE)) {\n\t\treturn new CredentialPrintError(\n\t\t\t\"MinValidityUnreachable\",\n\t\t\t`The provider refreshed the token but it still expires sooner than requested: ${detail}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\tif (error.message.startsWith(OAUTH_REFRESH_FAILED_PHRASE)) {\n\t\treturn new CredentialPrintError(\"RefreshFailed\", `${detail} (the stored credential was left untouched)`, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn new CredentialPrintError(\"OAuthUnavailable\", detail, { cause: error });\n}\n\n/**\n * Providers whose credential the caller could have meant.\n *\n * With `--provider` the caller named one, so failing to resolve it is an error.\n * Without it, eligibility is *not* narrowed to providers holding a persisted\n * credential: a provider authenticated by an environment variable or a custom\n * resolver has nothing in `auth.json`, and filtering on that list dropped it\n * before `getAuth()` could produce its working key. Candidacy is therefore\n * \"offers the named model\", and `getAuth()` — the same call a real request\n * makes — decides which candidate actually authenticates.\n */\nfunction candidateModels(args: Args, modelRuntime: ModelRuntime): Model<Api>[] {\n\tif (args.provider) {\n\t\tconst resolved = resolveCliModel({ cliProvider: args.provider, cliModel: args.model, modelRuntime });\n\t\tif (resolved.error || !resolved.model) {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tresolved.error ?? \"Unable to resolve the requested provider/model\",\n\t\t\t);\n\t\t}\n\t\treturn [resolved.model];\n\t}\n\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveCliModel({ cliProvider: provider.id, cliModel: args.model, modelRuntime });\n\t\tif (resolved.model && !resolved.error && !resolved.warning?.includes(\"Using custom model id\")) {\n\t\t\tmodels.push(resolved.model);\n\t\t}\n\t}\n\tif (models.length === 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`Model \"${args.model}\" not found among the available providers. Use --list-models to see available models.`,\n\t\t);\n\t}\n\treturn models;\n}\n\nfunction bearerFromHeaders(headers: Record<string, unknown> | undefined): string | undefined {\n\tconst authorization = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === \"authorization\")?.[1];\n\treturn typeof authorization === \"string\" ? /^Bearer\\s+(.+)$/iu.exec(authorization)?.[1] : undefined;\n}\n\n/**\n * Resolve exactly one credential for a named provider/model pair.\n *\n * Goes through `ModelRuntime.getAuth()`, the same request-auth path a real\n * model call uses, so an OAuth credential is refreshed and persisted by the one\n * implementation that already handles concurrent refresh under a lock.\n */\nexport async function resolveCredentialForPrint(\n\targs: Args,\n\tmodelRuntime: ModelRuntime,\n\tkind: CredentialPrintKind,\n\tminExpiryMs?: number,\n): Promise<Secret> {\n\tvalidateCredentialPrintArgs(args);\n\n\t// The effective auth type per candidate provider, taken from the runtime\n\t// rather than from auth.json.\n\t//\n\t// `checkAuth` reports what a provider would actually authenticate with,\n\t// including a credential supplied by an environment variable or a custom\n\t// resolver that persists nothing, and it answers without refreshing OAuth.\n\t// `listCredentials()` sees only what was stored, which both hid working\n\t// credentials and — for a provider offering an API key *and* OAuth — could not\n\t// say which of the two a request would use. Provider capability cannot say\n\t// either: several providers send an API key as `Authorization: Bearer`, so\n\t// neither that header nor `apiKey` identifies the credential's kind on its own.\n\tconst wantedAuthType: AuthType = kind === \"api_key\" ? \"api_key\" : \"oauth\";\n\tconst resolvedAuthTypes = new Map<string, AuthType | undefined>();\n\tconst models = candidateModels(args, modelRuntime);\n\tfor (const { provider } of models) {\n\t\tif (resolvedAuthTypes.has(provider)) continue;\n\t\tresolvedAuthTypes.set(provider, (await modelRuntime.checkAuth(provider))?.type);\n\t}\n\t// A named provider, or a single candidate, is the one the caller meant, so its\n\t// authentication failure is reported with its own exit code. Among several\n\t// inferred candidates a failure only means \"not this one\" — reporting it would\n\t// let an unrelated provider that happens to offer the model decide the exit\n\t// code for a request another candidate can satisfy.\n\tconst authFailureIsFatal = args.provider !== undefined || models.length === 1;\n\n\tconst credentials: Array<{ providerId: string; value: string }> = [];\n\t// The classified diagnosis from a candidate that could not authenticate.\n\t// Skipping a candidate must not discard why it failed: a refresh that failed,\n\t// or a token that cannot reach the requested validity, is the real answer if\n\t// nothing else produces a credential, and keeping it is what leaves exits 5\n\t// and 6 reachable instead of collapsing every inferred failure into exit 2.\n\t// It holds a `CredentialPrintError`, never a credential — the provider's text\n\t// is redacted on the way in.\n\tlet deferredDiagnosis: CredentialPrintError | undefined;\n\tfor (const model of models) {\n\t\tconst type = resolvedAuthTypes.get(model.provider);\n\t\tif (type !== wantedAuthType) continue;\n\n\t\t// Every eligible candidate is asked here, before `ProviderAmbiguous` is\n\t\t// known, so an ambiguous export can refresh and persist credentials it\n\t\t// emits nothing for. Deciding eligibility earlier is not available:\n\t\t// `checkAuth()` is the only non-mutating probe and cannot tell a candidate\n\t\t// that will authenticate from one that will fail, which is what keeps\n\t\t// exits 5 and 6 reachable. Nor does resolving without refreshing exist —\n\t\t// `resolveStoredOAuth` in `@earendil-works/pi-ai` refreshes whenever the\n\t\t// token falls inside `max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,\n\t\t// minOAuthValidityMs ?? 0)`, so omitting `minOAuthValidityMs` only lowers\n\t\t// that window to five minutes and drops the post-refresh check exit 6 is\n\t\t// decided by. Bounded: the refresh rotates a valid credential, it does not\n\t\t// invalidate one. Closing it needs a non-mutating probe upstream.\n\t\tlet auth: Awaited<ReturnType<ModelRuntime[\"getAuth\"]>>;\n\t\ttry {\n\t\t\tauth = await modelRuntime.getAuth(\n\t\t\t\tmodel,\n\t\t\t\tkind === \"bearer_token\" ? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS } : {},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst diagnosis =\n\t\t\t\terror instanceof ModelsError && error.code === \"oauth\" ? classifyOAuthFailure(error) : undefined;\n\t\t\tif (!authFailureIsFatal) {\n\t\t\t\tdeferredDiagnosis ??= diagnosis;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (diagnosis) throw diagnosis;\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tredactCredentialShapes(error instanceof Error ? error.message : String(error)),\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tconst value =\n\t\t\tkind === \"bearer_token\" ? (auth?.auth.apiKey ?? bearerFromHeaders(auth?.auth.headers)) : auth?.auth.apiKey;\n\t\tif (value) credentials.push({ providerId: model.provider, value });\n\t}\n\n\tif (credentials.length === 1) return new Secret(credentials[0].value);\n\n\tif (credentials.length === 0) {\n\t\tif (deferredDiagnosis) throw deferredDiagnosis;\n\t\tconst providerId = models[0]?.provider;\n\t\tconst type = providerId ? resolvedAuthTypes.get(providerId) : undefined;\n\t\tif (args.provider && kind === \"api_key\" && type === \"oauth\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is configured with OAuth, not an API key`,\n\t\t\t);\n\t\t}\n\t\tif (args.provider && kind === \"bearer_token\" && type === \"api_key\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is not configured with an OAuth bearer token`,\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`No usable ${kind === \"api_key\" ? \"API key\" : \"OAuth bearer token\"} is configured`,\n\t\t);\n\t}\n\n\tthrow new CredentialPrintError(\n\t\t\"ProviderAmbiguous\",\n\t\t`Model \"${args.model}\" has multiple configured providers (${credentials\n\t\t\t.map(({ providerId }) => providerId)\n\t\t\t.join(\", \")}). Specify --provider.`,\n\t);\n}\n"]}
1
+ {"version":3,"file":"credential-print.js","sourceRoot":"","sources":["../../src/cli/credential-print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAKlG,8EAA8E;AAC9E,MAAM,CAAC,MAAM,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,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C,CAAC;AACH,CAAC","sourcesContent":["/**\n * `atomic auth print-api-key` / `atomic auth print-bearer-token` and the\n * explicit `atomic auth check --credentials` export path.\n *\n * The only door in Atomic whose purpose is emitting a secret. Everything here\n * exists to keep that egress narrow:\n * - the secret leaves as a `Secret`, which cannot be interpolated, serialized,\n * or inspected, and is consumed exactly once by the stdout writer;\n * - every export has an explicit target: the print commands require `--model`,\n * and auth checks require `--provider` or an exact `--model` plus\n * `--credentials`;\n * - there is no `--output <file>` and no clipboard path — stdout only;\n * - every failure is a distinct exit code, and stdout stays empty on all of\n * them but one — `CredentialTruncated` (exit 9) exists to report the case\n * where it cannot be, because bytes already left and cannot be recalled;\n * - a failed OAuth refresh never mutates the stored credential.\n *\n * One residual, and it is upstream: when a model infers several eligible\n * providers, each is asked for its credential before the ambiguity is known, so\n * a *successful* refresh can rotate and persist a credential this command then\n * declines to emit (exit 3). See the note on the `getAuth()` call in the\n * candidate loop.\n */\n\nimport { inspect } from \"node:util\";\nimport type { Api, AuthType, Model } from \"@bastani/pi-ai\";\nimport { ModelsError } from \"@bastani/pi-ai\";\nimport { resolveCliModel } from \"../core/model-resolver.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\nimport { flushRawStdout, RawStdoutWriteError, writeRawStdoutOnce } from \"../core/output-guard.ts\";\nimport type { Args } from \"./args.ts\";\n\nexport type CredentialPrintKind = \"api_key\" | \"bearer_token\";\n\n/** Bearer tokens are refreshed unless they still have this much life left. */\nexport const DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS = 30 * 60_000;\n\n/**\n * Failure taxonomy. Each member owns one exit code, so a caller can branch on\n * the status without parsing stderr.\n */\nexport type CredentialPrintErrorCode =\n\t| \"Usage\"\n\t| \"NoCredentialConfigured\"\n\t| \"ProviderAmbiguous\"\n\t| \"KindUnsupportedForProvider\"\n\t| \"RefreshFailed\"\n\t| \"MinValidityUnreachable\"\n\t| \"OAuthUnavailable\"\n\t| \"CredentialNotEmitted\"\n\t| \"CredentialTruncated\";\n\n/**\n * Exported so a test can walk the whole taxonomy: every declared code has to\n * name an exercised path, and the record type makes a new member without an\n * exit code a compile error rather than a review miss.\n *\n * Every one of these leaves stdout empty except `CredentialTruncated`, which\n * exists to report the one case where it cannot be: bytes already went out and\n * cannot be recalled. `STDOUT_EMPTY_ON_EXIT` names that split so the taxonomy\n * test asserts it rather than assuming it.\n */\nexport const EXIT_CODES: Record<CredentialPrintErrorCode, number> = {\n\tUsage: 1,\n\tNoCredentialConfigured: 2,\n\tProviderAmbiguous: 3,\n\tKindUnsupportedForProvider: 4,\n\tRefreshFailed: 5,\n\tMinValidityUnreachable: 6,\n\tOAuthUnavailable: 7,\n\tCredentialNotEmitted: 8,\n\tCredentialTruncated: 9,\n};\n\n/** The codes whose contract is an empty stdout. See `EXIT_CODES`. */\nexport const STDOUT_EMPTY_ON_EXIT: ReadonlySet<CredentialPrintErrorCode> = new Set(\n\t(Object.keys(EXIT_CODES) as CredentialPrintErrorCode[]).filter((code) => code !== \"CredentialTruncated\"),\n);\n\nexport class CredentialPrintError extends Error {\n\treadonly code: CredentialPrintErrorCode;\n\treadonly exitCode: number;\n\n\tconstructor(code: CredentialPrintErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"CredentialPrintError\";\n\t\tthis.code = code;\n\t\tthis.exitCode = EXIT_CODES[code];\n\t}\n}\n\n/**\n * A credential in transit.\n *\n * Every path that would copy the value into a string is closed: `toString`,\n * `toJSON`, and `Symbol.toPrimitive` throw rather than return, so a template\n * literal, `JSON.stringify`, or string concatenation fails loudly instead of\n * leaking into a log line, a transcript, or an error message. `inspect` — which\n * `console.log` and Node's error formatting use — renders a placeholder.\n *\n * `take()` is the single exit, and it works once.\n */\nexport class Secret {\n\t#value: string | undefined;\n\n\tconstructor(value: string) {\n\t\tthis.#value = value;\n\t}\n\n\t/** Consume the secret. A second call is a bug, not a second read. */\n\ttake(): string {\n\t\tconst value = this.#value;\n\t\tif (value === undefined) {\n\t\t\tthrow new Error(\"Secret has already been consumed\");\n\t\t}\n\t\tthis.#value = undefined;\n\t\treturn value;\n\t}\n\n\ttoString(): never {\n\t\tthrow new Error(\"A Secret cannot be converted to a string; use take()\");\n\t}\n\n\ttoJSON(): never {\n\t\tthrow new Error(\"A Secret cannot be serialized; use take()\");\n\t}\n\n\t[Symbol.toPrimitive](): never {\n\t\tthrow new Error(\"A Secret cannot be interpolated; use take()\");\n\t}\n\n\t[inspect.custom](): string {\n\t\treturn \"[Secret]\";\n\t}\n}\n\n/** Public readiness fields emitted with a credential under `auth check --json --credentials`. */\nexport interface CredentialJsonFields {\n\tstatus: string;\n\tprovider: string;\n\tauthType?: string;\n}\n\n/**\n * The only function in `src` that opens a `Secret`.\n *\n * Its two `Secret.take()` calls are the only call sites in `src`, and the\n * source-wide credential-egress test pins that list. This function builds one\n * payload and returns it only to `emitCredential`; no caller receives a plain\n * credential string.\n */\nfunction credentialPayload(secret: Secret, jsonFields: CredentialJsonFields | undefined): string {\n\tif (jsonFields === undefined) return `${secret.take()}\\n`;\n\n\tconst { status, provider, authType } = jsonFields;\n\tif (\n\t\ttypeof status !== \"string\" ||\n\t\ttypeof provider !== \"string\" ||\n\t\t(authType !== undefined && typeof authType !== \"string\")\n\t) {\n\t\tthrow new Error(\"Invalid credential JSON fields\");\n\t}\n\n\t// Allowlist the non-secret envelope before opening the Secret. That leaves no\n\t// formatter, logger, or error path between take() and the guarded stdout write.\n\tconst fields = JSON.stringify({\n\t\tstatus,\n\t\tprovider,\n\t\t...(authType === undefined ? {} : { authType }),\n\t});\n\tif (fields === undefined || !fields.startsWith(\"{\") || !fields.endsWith(\"}\")) {\n\t\tthrow new Error(\"Invalid credential JSON envelope\");\n\t}\n\treturn `${fields.slice(0, -1)},\"credentials\":${JSON.stringify(secret.take())}}\\n`;\n}\n\n/**\n * The single credential egress in `src`.\n *\n * `credentialPayload` opens the secret only while building this one payload,\n * and this guarded write is the only path that hands it to real stdout. A\n * caller — `main.ts` included — receives a `Secret` it cannot read, print, or\n * serialize, so it cannot add a second export path without crossing this door.\n * `test/credential-print.test.ts` pins both the `take()` sites and every\n * data-bearing real-stdout write in `packages/coding-agent/src`.\n *\n * A failed payload write is answered from the stream rather than from the shape\n * of the error, because `bytesWritten` says how much of the credential actually\n * left and the right report differs for each amount.\n *\n * Nothing left — the write call threw, or the callback failed with the counter\n * unmoved — is `CredentialNotEmitted` (exit 8) with stdout provably empty,\n * which is what that exit promises. It must not fall through to the caller's\n * credential-resolution catch, which would report exit 2.\n *\n * All of it left and the failure came after: the caller holds the credential it\n * asked for, so this is reported on stderr with the exit code left at 0, for\n * the same reason the trailing drain is. A non-zero exit over a stream carrying\n * a whole credential is the thing this door never produces.\n *\n * Part of it left is neither. Those bytes cannot be recalled, so stdout is not\n * empty and cannot be made empty; but they are a fragment, not a credential,\n * and reporting success over them would hand a caller a truncated secret it\n * cannot tell from a whole one. That case gets `CredentialTruncated` (exit 9),\n * the one code in this taxonomy whose contract is *not* an empty stdout —\n * stated as such in `EXIT_CODES` and asserted through `STDOUT_EMPTY_ON_EXIT`,\n * rather than left for a caller to discover.\n */\nexport async function emitCredential(secret: Secret, jsonFields: CredentialJsonFields | undefined): Promise<void> {\n\tconst payload = credentialPayload(secret, jsonFields);\n\ttry {\n\t\tawait writeRawStdoutOnce(payload);\n\t} catch (error) {\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"all\") {\n\t\t\t// The caller holds the whole credential. Exiting non-zero here would be\n\t\t\t// a non-zero exit over a stream carrying it, which this door never does.\n\t\t\tconsole.error(\n\t\t\t\t`Warning: the credential reached stdout but the write did not complete cleanly: ${error.message}`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (error instanceof RawStdoutWriteError && error.emitted === \"partial\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"CredentialTruncated\",\n\t\t\t\t\"Only part of the credential reached stdout; discard the output, it is not a usable credential\",\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"CredentialNotEmitted\",\n\t\t\t\"Failed to write the credential to stdout; nothing was emitted\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\ttry {\n\t\tawait flushRawStdout();\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Warning: the credential was written to stdout but the stream did not drain cleanly: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n}\n\n/**\n * The single place a thrown value becomes an exit code for this door.\n *\n * `main.ts` routes every failure through here. Every code it can produce leaves\n * stdout empty, so an exit code from this door never contradicts the stream.\n */\nexport function toCredentialPrintError(error: unknown): CredentialPrintError {\n\tif (error instanceof CredentialPrintError) return error;\n\treturn new CredentialPrintError(\n\t\t\"NoCredentialConfigured\",\n\t\terror instanceof Error ? error.message : \"Failed to resolve credential\",\n\t\t{ cause: error },\n\t);\n}\n\n/**\n * The only two fields of `Args` this door accepts.\n *\n * Validation is an allowlist rather than a list of refusals, because the\n * refusal list only held while the dispatcher happened to ignore every other\n * flag. `--export <path>`, `--session-dir <path>`, `--print`, and `--help` are\n * all parsed by `parseArgs`; under an exclusion check they passed silently and\n * the door's \"no file sink\" guarantee rested on a downstream accident.\n */\nconst ACCEPTED_ARG_FIELDS: ReadonlySet<string> = new Set([\"model\", \"provider\"]);\n\n/** Names every field of a parsed `Args` that the caller actually set. */\nfunction populatedArgFields(args: Args): string[] {\n\tconst populated: string[] = [];\n\tfor (const [field, value] of Object.entries(args)) {\n\t\tif (ACCEPTED_ARG_FIELDS.has(field) || value === undefined) continue;\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length > 0) populated.push(field);\n\t\t} else if (value instanceof Map) {\n\t\t\tif (value.size > 0) populated.push(field);\n\t\t} else {\n\t\t\tpopulated.push(field);\n\t\t}\n\t}\n\treturn populated;\n}\n\nexport function validateCredentialPrintArgs(args: Args): void {\n\tif (!args.model?.trim()) {\n\t\tthrow new CredentialPrintError(\"Usage\", \"Credential printing requires --model <model>\");\n\t}\n\tif (args.apiKey !== undefined) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t\"Credential printing reads configured credentials; --api-key is not supported\",\n\t\t);\n\t}\n\tconst refused = populatedArgFields(args);\n\tif (refused.length > 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"Usage\",\n\t\t\t`Credential printing only accepts --provider and --model (refused: ${refused.join(\", \")})`,\n\t\t);\n\t}\n}\n\n/**\n * Provider-supplied text with anything credential-bearing masked.\n *\n * A failed refresh is reported on stderr, and the provider composes that\n * message. Most describe the failure; some quote the request they sent or the\n * body they got back, either of which can carry the very value this door exists\n * to keep off every stream except stdout. Masking keeps the diagnosis — which\n * is what makes the exit code actionable — without putting the secret in a log,\n * a terminal scrollback, or a CI transcript.\n *\n * Two passes, because either alone leaves a gap. Shape catches a value wherever\n * it appears, but only for the formats that announce themselves. Context\n * catches an opaque value — an `x-api-key`, which is just bytes — by the name it\n * is filed under, in the header, JSON, and query spellings a quoted request or\n * response body uses.\n */\nconst CREDENTIAL_SHAPES: readonly RegExp[] = [\n\t// `Authorization: Bearer <token>`, the form an echoed request header takes.\n\t/\\bBearer\\s+[\\w.~+/-]+=*/giu,\n\t// JWTs, which several providers return verbatim in an error body.\n\t/\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]+/gu,\n\t// Prefixed API keys: sk-…, sk_live_…, api-key-…, and the same shapes again.\n\t/\\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\\w-]{12,}/giu,\n];\n\n/**\n * Field names whose value is the credential, however opaque that value looks.\n * `x-api-key` is the case shape-matching cannot reach: the value is just bytes.\n */\nconst CREDENTIAL_FIELD_NAME =\n\t\"(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)\";\n\n/**\n * Auth schemes that stand between the field name and the value it introduces.\n *\n * Without them the header matcher stops at the space after `Bearer`: it redacts\n * the scheme and leaves the token, and having consumed the `Bearer` the shape\n * pass depends on, that pass can no longer reach the token either. An opaque\n * `Authorization: Bearer <token>` then survives both passes.\n */\nconst CREDENTIAL_AUTH_SCHEME = \"(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)\";\n\nconst CREDENTIAL_CONTEXTS: readonly RegExp[] = [\n\t// Header or YAML-ish: `x-api-key: abc123`, to end of line, and the scheme\n\t// form `Authorization: Bearer abc123` with it.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*:\\s*(?:${CREDENTIAL_AUTH_SCHEME}\\s+)?[^\\s,;}\"']+`, \"giu\"),\n\t// JSON: `\"api_key\": \"abc123\"` / `'token':'abc123'`, quoted value.\n\tnew RegExp(String.raw`([\"']?)${CREDENTIAL_FIELD_NAME}\\1\\s*:\\s*([\"'])(?:(?!\\2).)*\\2`, \"giu\"),\n\t// Query string or form body: `?api_key=abc123&…`.\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*=\\s*[^\\s&,;}\"']+`, \"giu\"),\n];\n\nexport function redactCredentialShapes(text: string): string {\n\tconst byContext = CREDENTIAL_CONTEXTS.reduce(\n\t\t(masked, context) =>\n\t\t\tmasked.replace(context, (match) => {\n\t\t\t\t// Keep the field name so the diagnosis still says which one failed;\n\t\t\t\t// replace only what follows the separator.\n\t\t\t\tconst separator = /[:=]/u.exec(match);\n\t\t\t\treturn separator ? `${match.slice(0, separator.index + 1)} [redacted]` : \"[redacted]\";\n\t\t\t}),\n\t\ttext,\n\t);\n\treturn CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, \"[redacted]\"), byContext);\n}\n\n/**\n * The literal phrase pi-ai throws when a refresh itself failed, from inside\n * `credentials.modify` and therefore before anything is persisted. This is the\n * only oauth-coded error that can claim the stored credential was left alone.\n */\nexport const OAUTH_REFRESH_FAILED_PHRASE = \"OAuth refresh failed for\";\n\n/**\n * The literal phrase pi-ai throws when a refresh succeeded but the rotated\n * token still expires inside the requested window. It is the only signal that\n * separates exit 6 from exit 5.\n */\nexport const OAUTH_EXPIRES_TOO_SOON_PHRASE = \"expires too soon\";\n\n/**\n * pi-ai raises three different `oauth`-coded failures from\n * `dist/auth/resolve.js`, and only one of them is a failed refresh.\n *\n * `OAuth auth derivation failed for <provider>` is thrown after\n * `credentials.modify` has already persisted a rotated credential, and also on\n * the branch where no refresh was attempted at all — so it gets its own code\n * and a message that makes no claim about the stored credential. Treating it as\n * `RefreshFailed` asserted a rollback the command never verified.\n *\n * Classification reads the raw message, because redaction could rewrite the\n * phrase it matches on; only the text that becomes a user-facing message is\n * redacted. The unredacted error stays reachable as `cause`, which this door\n * never logs.\n *\n * `test/credential-print.test.ts` pins both phrases against the installed\n * pi-ai build, so an upstream rewording fails the suite rather than silently\n * collapsing exit 6 into exit 5.\n */\nexport function classifyOAuthFailure(error: ModelsError): CredentialPrintError {\n\tconst detail = redactCredentialShapes(error.message);\n\tif (error.message.includes(OAUTH_EXPIRES_TOO_SOON_PHRASE)) {\n\t\treturn new CredentialPrintError(\n\t\t\t\"MinValidityUnreachable\",\n\t\t\t`The provider refreshed the token but it still expires sooner than requested: ${detail}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\tif (error.message.startsWith(OAUTH_REFRESH_FAILED_PHRASE)) {\n\t\treturn new CredentialPrintError(\"RefreshFailed\", `${detail} (the stored credential was left untouched)`, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn new CredentialPrintError(\"OAuthUnavailable\", detail, { cause: error });\n}\n\n/**\n * Providers whose credential the caller could have meant.\n *\n * With `--provider` the caller named one, so failing to resolve it is an error.\n * Without it, eligibility is *not* narrowed to providers holding a persisted\n * credential: a provider authenticated by an environment variable or a custom\n * resolver has nothing in `auth.json`, and filtering on that list dropped it\n * before `getAuth()` could produce its working key. Candidacy is therefore\n * \"offers the named model\", and `getAuth()` — the same call a real request\n * makes — decides which candidate actually authenticates.\n */\nfunction candidateModels(args: Args, modelRuntime: ModelRuntime): Model<Api>[] {\n\tif (args.provider) {\n\t\tconst resolved = resolveCliModel({ cliProvider: args.provider, cliModel: args.model, modelRuntime });\n\t\tif (resolved.error || !resolved.model) {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tresolved.error ?? \"Unable to resolve the requested provider/model\",\n\t\t\t);\n\t\t}\n\t\treturn [resolved.model];\n\t}\n\n\tconst models: Model<Api>[] = [];\n\tfor (const provider of modelRuntime.getProviders()) {\n\t\tconst resolved = resolveCliModel({ cliProvider: provider.id, cliModel: args.model, modelRuntime });\n\t\tif (resolved.model && !resolved.error && !resolved.warning?.includes(\"Using custom model id\")) {\n\t\t\tmodels.push(resolved.model);\n\t\t}\n\t}\n\tif (models.length === 0) {\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`Model \"${args.model}\" not found among the available providers. Use --list-models to see available models.`,\n\t\t);\n\t}\n\treturn models;\n}\n\nfunction bearerFromHeaders(headers: Record<string, unknown> | undefined): string | undefined {\n\tconst authorization = Object.entries(headers ?? {}).find(([name]) => name.toLowerCase() === \"authorization\")?.[1];\n\treturn typeof authorization === \"string\" ? /^Bearer\\s+(.+)$/iu.exec(authorization)?.[1] : undefined;\n}\n\n/**\n * Resolve exactly one credential for a named provider/model pair.\n *\n * Goes through `ModelRuntime.getAuth()`, the same request-auth path a real\n * model call uses, so an OAuth credential is refreshed and persisted by the one\n * implementation that already handles concurrent refresh under a lock.\n */\nexport async function resolveCredentialForPrint(\n\targs: Args,\n\tmodelRuntime: ModelRuntime,\n\tkind: CredentialPrintKind,\n\tminExpiryMs?: number,\n): Promise<Secret> {\n\tvalidateCredentialPrintArgs(args);\n\n\t// The effective auth type per candidate provider, taken from the runtime\n\t// rather than from auth.json.\n\t//\n\t// `checkAuth` reports what a provider would actually authenticate with,\n\t// including a credential supplied by an environment variable or a custom\n\t// resolver that persists nothing, and it answers without refreshing OAuth.\n\t// `listCredentials()` sees only what was stored, which both hid working\n\t// credentials and — for a provider offering an API key *and* OAuth — could not\n\t// say which of the two a request would use. Provider capability cannot say\n\t// either: several providers send an API key as `Authorization: Bearer`, so\n\t// neither that header nor `apiKey` identifies the credential's kind on its own.\n\tconst wantedAuthType: AuthType = kind === \"api_key\" ? \"api_key\" : \"oauth\";\n\tconst resolvedAuthTypes = new Map<string, AuthType | undefined>();\n\tconst models = candidateModels(args, modelRuntime);\n\tfor (const { provider } of models) {\n\t\tif (resolvedAuthTypes.has(provider)) continue;\n\t\tresolvedAuthTypes.set(provider, (await modelRuntime.checkAuth(provider))?.type);\n\t}\n\t// A named provider, or a single candidate, is the one the caller meant, so its\n\t// authentication failure is reported with its own exit code. Among several\n\t// inferred candidates a failure only means \"not this one\" — reporting it would\n\t// let an unrelated provider that happens to offer the model decide the exit\n\t// code for a request another candidate can satisfy.\n\tconst authFailureIsFatal = args.provider !== undefined || models.length === 1;\n\n\tconst credentials: Array<{ providerId: string; value: string }> = [];\n\t// The classified diagnosis from a candidate that could not authenticate.\n\t// Skipping a candidate must not discard why it failed: a refresh that failed,\n\t// or a token that cannot reach the requested validity, is the real answer if\n\t// nothing else produces a credential, and keeping it is what leaves exits 5\n\t// and 6 reachable instead of collapsing every inferred failure into exit 2.\n\t// It holds a `CredentialPrintError`, never a credential — the provider's text\n\t// is redacted on the way in.\n\tlet deferredDiagnosis: CredentialPrintError | undefined;\n\tfor (const model of models) {\n\t\tconst type = resolvedAuthTypes.get(model.provider);\n\t\tif (type !== wantedAuthType) continue;\n\n\t\t// Every eligible candidate is asked here, before `ProviderAmbiguous` is\n\t\t// known, so an ambiguous export can refresh and persist credentials it\n\t\t// emits nothing for. Deciding eligibility earlier is not available:\n\t\t// `checkAuth()` is the only non-mutating probe and cannot tell a candidate\n\t\t// that will authenticate from one that will fail, which is what keeps\n\t\t// exits 5 and 6 reachable. Nor does resolving without refreshing exist —\n\t\t// `resolveStoredOAuth` in `@bastani/pi-ai` refreshes whenever the\n\t\t// token falls inside `max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,\n\t\t// minOAuthValidityMs ?? 0)`, so omitting `minOAuthValidityMs` only lowers\n\t\t// that window to five minutes and drops the post-refresh check exit 6 is\n\t\t// decided by. Bounded: the refresh rotates a valid credential, it does not\n\t\t// invalidate one. Closing it needs a non-mutating probe upstream.\n\t\tlet auth: Awaited<ReturnType<ModelRuntime[\"getAuth\"]>>;\n\t\ttry {\n\t\t\tauth = await modelRuntime.getAuth(\n\t\t\t\tmodel,\n\t\t\t\tkind === \"bearer_token\" ? { minOAuthValidityMs: minExpiryMs ?? DEFAULT_BEARER_TOKEN_MIN_EXPIRY_MS } : {},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst diagnosis =\n\t\t\t\terror instanceof ModelsError && error.code === \"oauth\" ? classifyOAuthFailure(error) : undefined;\n\t\t\tif (!authFailureIsFatal) {\n\t\t\t\tdeferredDiagnosis ??= diagnosis;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (diagnosis) throw diagnosis;\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"NoCredentialConfigured\",\n\t\t\t\tredactCredentialShapes(error instanceof Error ? error.message : String(error)),\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tconst value =\n\t\t\tkind === \"bearer_token\" ? (auth?.auth.apiKey ?? bearerFromHeaders(auth?.auth.headers)) : auth?.auth.apiKey;\n\t\tif (value) credentials.push({ providerId: model.provider, value });\n\t}\n\n\tif (credentials.length === 1) return new Secret(credentials[0].value);\n\n\tif (credentials.length === 0) {\n\t\tif (deferredDiagnosis) throw deferredDiagnosis;\n\t\tconst providerId = models[0]?.provider;\n\t\tconst type = providerId ? resolvedAuthTypes.get(providerId) : undefined;\n\t\tif (args.provider && kind === \"api_key\" && type === \"oauth\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is configured with OAuth, not an API key`,\n\t\t\t);\n\t\t}\n\t\tif (args.provider && kind === \"bearer_token\" && type === \"api_key\") {\n\t\t\tthrow new CredentialPrintError(\n\t\t\t\t\"KindUnsupportedForProvider\",\n\t\t\t\t`Provider \"${providerId}\" is not configured with an OAuth bearer token`,\n\t\t\t);\n\t\t}\n\t\tthrow new CredentialPrintError(\n\t\t\t\"NoCredentialConfigured\",\n\t\t\t`No usable ${kind === \"api_key\" ? \"API key\" : \"OAuth bearer token\"} is configured`,\n\t\t);\n\t}\n\n\tthrow new CredentialPrintError(\n\t\t\"ProviderAmbiguous\",\n\t\t`Model \"${args.model}\" has multiple configured providers (${credentials\n\t\t\t.map(({ providerId }) => providerId)\n\t\t\t.join(\", \")}). Specify --provider.`,\n\t);\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Process @file CLI arguments into text content and image attachments
3
3
  */
4
- import type { ImageContent } from "@earendil-works/pi-ai/compat";
4
+ import type { ImageContent } from "@bastani/pi-ai/compat";
5
5
  export interface ProcessedFiles {
6
6
  text: string;
7
7
  images: ImageContent[];
@@ -1 +1 @@
1
- {"version":3,"file":"file-processor.d.ts","sourceRoot":"","sources":["../../src/cli/file-processor.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAOjE,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,YAAY,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,kBAAkB;IAClC,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,sEAAsE;AACtE,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,cAAc,CAAC,CA+DpH"}
1
+ {"version":3,"file":"file-processor.d.ts","sourceRoot":"","sources":["../../src/cli/file-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eAAe,YAAY,aAAa,CAAC;YAClD,CAAC;QACF,CAAC;aAAM,CAAC;YACP,mBAAmB;YACnB,IAAI,CAAC;gBACJ,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;gBACtD,IAAI,IAAI,eAAe,YAAY,OAAO,OAAO,aAAa,CAAC;YAChE,CAAC;YAAC,OAAO,KAAc,EAAE,CAAC;gBACzB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACvE,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,8BAA8B,YAAY,KAAK,OAAO,EAAE,CAAC,CAAC,CAAC;gBACnF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YACjB,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC","sourcesContent":["/**\n * Process @file CLI arguments into text content and image attachments\n */\n\nimport { access, readFile, stat } from \"node:fs/promises\";\nimport type { ImageContent } from \"@earendil-works/pi-ai/compat\";\nimport chalk from \"chalk\";\nimport { resolve } from \"path\";\nimport { resolveReadPath } from \"../core/tools/path-utils.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../utils/mime.ts\";\n\nexport interface ProcessedFiles {\n\ttext: string;\n\timages: ImageContent[];\n}\n\nexport interface ProcessFileOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n}\n\n/** Process @file arguments into text content and image attachments */\nexport async function processFileArguments(fileArgs: string[], options?: ProcessFileOptions): Promise<ProcessedFiles> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tlet text = \"\";\n\tconst images: ImageContent[] = [];\n\n\tfor (const fileArg of fileArgs) {\n\t\t// Expand and resolve path (handles ~ expansion and macOS screenshot Unicode spaces)\n\t\tconst absolutePath = resolve(resolveReadPath(fileArg, process.cwd()));\n\n\t\t// Check if file exists\n\t\ttry {\n\t\t\tawait access(absolutePath);\n\t\t} catch {\n\t\t\tconsole.error(chalk.red(`Error: File not found: ${absolutePath}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\t// Check if file is empty\n\t\tconst stats = await stat(absolutePath);\n\t\tif (stats.size === 0) {\n\t\t\t// Skip empty files\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst mimeType = await detectSupportedImageMimeTypeFromFile(absolutePath);\n\n\t\tif (mimeType) {\n\t\t\t// Handle image file\n\t\t\tconst content = await readFile(absolutePath);\n\t\t\tconst processed = await processImage(content, mimeType, { autoResizeImages });\n\n\t\t\tif (!processed.ok) {\n\t\t\t\ttext += `<file name=\"${absolutePath}\">${processed.message}</file>\\n`;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst attachment: ImageContent = {\n\t\t\t\ttype: \"image\",\n\t\t\t\tmimeType: processed.mimeType,\n\t\t\t\tdata: processed.data,\n\t\t\t};\n\t\t\timages.push(attachment);\n\n\t\t\t// Add text reference to image with optional processing hints\n\t\t\tif (processed.hints.length > 0) {\n\t\t\t\ttext += `<file name=\"${absolutePath}\">${processed.hints.join(\"\\n\")}</file>\\n`;\n\t\t\t} else {\n\t\t\t\ttext += `<file name=\"${absolutePath}\"></file>\\n`;\n\t\t\t}\n\t\t} else {\n\t\t\t// Handle text file\n\t\t\ttry {\n\t\t\t\tconst content = await readFile(absolutePath, \"utf-8\");\n\t\t\t\ttext += `<file name=\"${absolutePath}\">\\n${content}\\n</file>\\n`;\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconsole.error(chalk.red(`Error: Could not read file ${absolutePath}: ${message}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { text, images };\n}\n"]}
1
+ {"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AG,CAAC,8BAA8B,YAAY,KAAK,OAAO,EAAE,CAAC,CAAC,CAAC;gBACnF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YACjB,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC","sourcesContent":["/**\n * Process @file CLI arguments into text content and image attachments\n */\n\nimport { access, readFile, stat } from \"node:fs/promises\";\nimport type { ImageContent } from \"@bastani/pi-ai/compat\";\nimport chalk from \"chalk\";\nimport { resolve } from \"path\";\nimport { resolveReadPath } from \"../core/tools/path-utils.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../utils/mime.ts\";\n\nexport interface ProcessedFiles {\n\ttext: string;\n\timages: ImageContent[];\n}\n\nexport interface ProcessFileOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n}\n\n/** Process @file arguments into text content and image attachments */\nexport async function processFileArguments(fileArgs: string[], options?: ProcessFileOptions): Promise<ProcessedFiles> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tlet text = \"\";\n\tconst images: ImageContent[] = [];\n\n\tfor (const fileArg of fileArgs) {\n\t\t// Expand and resolve path (handles ~ expansion and macOS screenshot Unicode spaces)\n\t\tconst absolutePath = resolve(resolveReadPath(fileArg, process.cwd()));\n\n\t\t// Check if file exists\n\t\ttry {\n\t\t\tawait access(absolutePath);\n\t\t} catch {\n\t\t\tconsole.error(chalk.red(`Error: File not found: ${absolutePath}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\n\t\t// Check if file is empty\n\t\tconst stats = await stat(absolutePath);\n\t\tif (stats.size === 0) {\n\t\t\t// Skip empty files\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst mimeType = await detectSupportedImageMimeTypeFromFile(absolutePath);\n\n\t\tif (mimeType) {\n\t\t\t// Handle image file\n\t\t\tconst content = await readFile(absolutePath);\n\t\t\tconst processed = await processImage(content, mimeType, { autoResizeImages });\n\n\t\t\tif (!processed.ok) {\n\t\t\t\ttext += `<file name=\"${absolutePath}\">${processed.message}</file>\\n`;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst attachment: ImageContent = {\n\t\t\t\ttype: \"image\",\n\t\t\t\tmimeType: processed.mimeType,\n\t\t\t\tdata: processed.data,\n\t\t\t};\n\t\t\timages.push(attachment);\n\n\t\t\t// Add text reference to image with optional processing hints\n\t\t\tif (processed.hints.length > 0) {\n\t\t\t\ttext += `<file name=\"${absolutePath}\">${processed.hints.join(\"\\n\")}</file>\\n`;\n\t\t\t} else {\n\t\t\t\ttext += `<file name=\"${absolutePath}\"></file>\\n`;\n\t\t\t}\n\t\t} else {\n\t\t\t// Handle text file\n\t\t\ttry {\n\t\t\t\tconst content = await readFile(absolutePath, \"utf-8\");\n\t\t\t\ttext += `<file name=\"${absolutePath}\">\\n${content}\\n</file>\\n`;\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconsole.error(chalk.red(`Error: Could not read file ${absolutePath}: ${message}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { text, images };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { ImageContent } from "@earendil-works/pi-ai/compat";
1
+ import type { ImageContent } from "@bastani/pi-ai/compat";
2
2
  import type { Args } from "./args.ts";
3
3
  export interface InitialMessageInput {
4
4
  parsed: Args;
@@ -1 +1 @@
1
- {"version":3,"file":"initial-message.d.ts","sourceRoot":"","sources":["../../src/cli/initial-message.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEtC,MAAM,WAAW,mBAAmB;IACnC,MAAM,EAAE,IAAI,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,YAAY,EAAE,CAAC;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,oBAAoB;IACpC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,EACnC,MAAM,EACN,QAAQ,EACR,UAAU,EACV,YAAY,GACZ,EAAE,mBAAmB,GAAG,oBAAoB,CAkB5C"}
1
+ {"version":3,"file":"initial-message.d.ts","sourceRoot":"","sources":["../../src/cli/initial-message.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEtC,MAAM,WAAW,mBAAmB;IACnC,MAAM,EAAE,IAAI,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,YAAY,EAAE,CAAC;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,oBAAoB;IACpC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,EACnC,MAAM,EACN,QAAQ,EACR,UAAU,EACV,YAAY,GACZ,EAAE,mBAAmB,GAAG,oBAAoB,CAkB5C"}
@@ -1 +1 @@
1
- {"version":3,"file":"initial-message.js","sourceRoot":"","sources":["../../src/cli/initial-message.ts"],"names":[],"mappings":"AAeA;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,EACnC,MAAM,EACN,QAAQ,EACR,UAAU,EACV,YAAY,GACS;IACrB,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAChC,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC1B,CAAC;IACD,IAAI,QAAQ,EAAE,CAAC;QACd,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/B,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,OAAO;QACN,cAAc,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS;QAC7D,aAAa,EAAE,UAAU,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS;KAC3E,CAAC;AACH,CAAC","sourcesContent":["import type { ImageContent } from \"@earendil-works/pi-ai/compat\";\nimport type { Args } from \"./args.ts\";\n\nexport interface InitialMessageInput {\n\tparsed: Args;\n\tfileText?: string;\n\tfileImages?: ImageContent[];\n\tstdinContent?: string;\n}\n\nexport interface InitialMessageResult {\n\tinitialMessage?: string;\n\tinitialImages?: ImageContent[];\n}\n\n/**\n * Combine stdin content, @file text, and the first CLI message into a single\n * initial prompt for non-interactive mode.\n */\nexport function buildInitialMessage({\n\tparsed,\n\tfileText,\n\tfileImages,\n\tstdinContent,\n}: InitialMessageInput): InitialMessageResult {\n\tconst parts: string[] = [];\n\tif (stdinContent !== undefined) {\n\t\tparts.push(stdinContent);\n\t}\n\tif (fileText) {\n\t\tparts.push(fileText);\n\t}\n\n\tif (parsed.messages.length > 0) {\n\t\tparts.push(parsed.messages[0]);\n\t\tparsed.messages.shift();\n\t}\n\n\treturn {\n\t\tinitialMessage: parts.length > 0 ? parts.join(\"\") : undefined,\n\t\tinitialImages: fileImages && fileImages.length > 0 ? fileImages : undefined,\n\t};\n}\n"]}
1
+ {"version":3,"file":"initial-message.js","sourceRoot":"","sources":["../../src/cli/initial-message.ts"],"names":[],"mappings":"AAeA;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,EACnC,MAAM,EACN,QAAQ,EACR,UAAU,EACV,YAAY,GACS;IACrB,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAChC,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC1B,CAAC;IACD,IAAI,QAAQ,EAAE,CAAC;QACd,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/B,MAAM,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,OAAO;QACN,cAAc,EAAE,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS;QAC7D,aAAa,EAAE,UAAU,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS;KAC3E,CAAC;AACH,CAAC","sourcesContent":["import type { ImageContent } from \"@bastani/pi-ai/compat\";\nimport type { Args } from \"./args.ts\";\n\nexport interface InitialMessageInput {\n\tparsed: Args;\n\tfileText?: string;\n\tfileImages?: ImageContent[];\n\tstdinContent?: string;\n}\n\nexport interface InitialMessageResult {\n\tinitialMessage?: string;\n\tinitialImages?: ImageContent[];\n}\n\n/**\n * Combine stdin content, @file text, and the first CLI message into a single\n * initial prompt for non-interactive mode.\n */\nexport function buildInitialMessage({\n\tparsed,\n\tfileText,\n\tfileImages,\n\tstdinContent,\n}: InitialMessageInput): InitialMessageResult {\n\tconst parts: string[] = [];\n\tif (stdinContent !== undefined) {\n\t\tparts.push(stdinContent);\n\t}\n\tif (fileText) {\n\t\tparts.push(fileText);\n\t}\n\n\tif (parsed.messages.length > 0) {\n\t\tparts.push(parsed.messages[0]);\n\t\tparsed.messages.shift();\n\t}\n\n\treturn {\n\t\tinitialMessage: parts.length > 0 ? parts.join(\"\") : undefined,\n\t\tinitialImages: fileImages && fileImages.length > 0 ? fileImages : undefined,\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"list-models.js","sourceRoot":"","sources":["../../src/cli/list-models.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;AAG1E;;GAEG;AACH,SAAS,gBAAgB,CAAC,KAAa;IACtC,IAAI,KAAK,IAAI,SAAS,EAAE,CAAC;QACxB,MAAM,QAAQ,GAAG,KAAK,GAAG,SAAS,CAAC;QACnC,OAAO,QAAQ,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;QACpB,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK,CAAC;QAChC,OAAO,SAAS,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IAC3E,CAAC;IACD,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,C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CAAC,MAAM,CAAC,KAAK,CAAC;YAC9B,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC;YAClC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;YAChC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC;YACpC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;SAChC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC;AACF,CAAC","sourcesContent":["/**\n * List available models with optional fuzzy search\n */\n\nimport type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { fuzzyFilter } from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { formatNoModelsAvailableMessage } from \"../core/auth-guidance.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\n\n/**\n * Format a number as human-readable (e.g., 200000 -> \"200K\", 1000000 -> \"1M\")\n */\nfunction formatTokenCount(count: number): string {\n\tif (count >= 1_000_000) {\n\t\tconst millions = count / 1_000_000;\n\t\treturn millions % 1 === 0 ? `${millions}M` : `${millions.toFixed(1)}M`;\n\t}\n\tif (count >= 1_000) {\n\t\tconst thousands = count / 1_000;\n\t\treturn thousands % 1 === 0 ? `${thousands}K` : `${thousands.toFixed(1)}K`;\n\t}\n\treturn count.toString();\n}\n\n/**\n * List available models, optionally filtered by search pattern\n */\nexport async function listModels(modelRuntime: ModelRuntime, searchPattern?: string): Promise<void> {\n\tconst loadError = modelRuntime.getError();\n\tif (loadError) {\n\t\tconsole.error(chalk.yellow(`Warning: errors loading models.json:\\n${loadError}`));\n\t}\n\n\tconst models = modelRuntime.getAvailableSnapshot();\n\n\tif (models.length === 0) {\n\t\tconsole.log(formatNoModelsAvailableMessage());\n\t\treturn;\n\t}\n\n\t// Apply fuzzy filter if search pattern provided\n\tlet filteredModels: Model<Api>[] = [...models];\n\tif (searchPattern) {\n\t\tfilteredModels = fuzzyFilter([...models], searchPattern, (m) => `${m.provider} ${m.id}`);\n\t}\n\n\tif (filteredModels.length === 0) {\n\t\tconsole.log(`No models matching \"${searchPattern}\"`);\n\t\treturn;\n\t}\n\n\t// Sort by provider, then by model id\n\tfilteredModels.sort((a, b) => {\n\t\tconst providerCmp = a.provider.localeCompare(b.provider);\n\t\tif (providerCmp !== 0) return providerCmp;\n\t\treturn a.id.localeCompare(b.id);\n\t});\n\n\t// Calculate column widths\n\tconst rows = filteredModels.map((m) => ({\n\t\tprovider: m.provider,\n\t\tmodel: m.id,\n\t\tcontext: formatTokenCount(m.contextWindow),\n\t\tmaxOut: formatTokenCount(m.maxTokens),\n\t\tthinking: m.reasoning ? \"yes\" : \"no\",\n\t\timages: m.input.includes(\"image\") ? \"yes\" : \"no\",\n\t}));\n\n\tconst headers = {\n\t\tprovider: \"provider\",\n\t\tmodel: \"model\",\n\t\tcontext: \"context\",\n\t\tmaxOut: \"max-out\",\n\t\tthinking: \"thinking\",\n\t\timages: \"images\",\n\t};\n\n\tconst widths = {\n\t\tprovider: Math.max(headers.provider.length, ...rows.map((r) => r.provider.length)),\n\t\tmodel: Math.max(headers.model.length, ...rows.map((r) => r.model.length)),\n\t\tcontext: Math.max(headers.context.length, ...rows.map((r) => r.context.length)),\n\t\tmaxOut: Math.max(headers.maxOut.length, ...rows.map((r) => r.maxOut.length)),\n\t\tthinking: Math.max(headers.thinking.length, ...rows.map((r) => r.thinking.length)),\n\t\timages: Math.max(headers.images.length, ...rows.map((r) => r.images.length)),\n\t};\n\n\t// Print header\n\tconst headerLine = [\n\t\theaders.provider.padEnd(widths.provider),\n\t\theaders.model.padEnd(widths.model),\n\t\theaders.context.padEnd(widths.context),\n\t\theaders.maxOut.padEnd(widths.maxOut),\n\t\theaders.thinking.padEnd(widths.thinking),\n\t\theaders.images.padEnd(widths.images),\n\t].join(\" \");\n\tconsole.log(headerLine);\n\n\t// Print rows\n\tfor (const row of rows) {\n\t\tconst line = [\n\t\t\trow.provider.padEnd(widths.provider),\n\t\t\trow.model.padEnd(widths.model),\n\t\t\trow.context.padEnd(widths.context),\n\t\t\trow.maxOut.padEnd(widths.maxOut),\n\t\t\trow.thinking.padEnd(widths.thinking),\n\t\t\trow.images.padEnd(widths.images),\n\t\t].join(\" \");\n\t\tconsole.log(line);\n\t}\n}\n"]}
1
+ {"version":3,"file":"list-models.js","sourceRoot":"","sources":["../../src/cli/list-models.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;AAG1E;;GAEG;AACH,SAAS,gBAAgB,CAAC,KAAa;IACtC,IAAI,KAAK,IAAI,SAAS,EAAE,CAAC;QACxB,MAAM,QAAQ,GAAG,KAAK,GAAG,SAAS,CAAC;QACnC,OAAO,QAAQ,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IACxE,CAAC;IACD,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;QACpB,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK,CAAC;QAChC,OAAO,SAAS,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IAC3E,CAAC;IACD,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,YAA0B,EAAE,aAAsB;IAClF,MAAM,SAAS,GAAG,YAAY,CAAC,QAAQ,EAAE,C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AM,CAAC,OAAO,CAAC;YAClC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;YAChC,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC;YACpC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;SAChC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC;AACF,CAAC","sourcesContent":["/**\n * List available models with optional fuzzy search\n */\n\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport { fuzzyFilter } from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { formatNoModelsAvailableMessage } from \"../core/auth-guidance.ts\";\nimport type { ModelRuntime } from \"../core/model-runtime.js\";\n\n/**\n * Format a number as human-readable (e.g., 200000 -> \"200K\", 1000000 -> \"1M\")\n */\nfunction formatTokenCount(count: number): string {\n\tif (count >= 1_000_000) {\n\t\tconst millions = count / 1_000_000;\n\t\treturn millions % 1 === 0 ? `${millions}M` : `${millions.toFixed(1)}M`;\n\t}\n\tif (count >= 1_000) {\n\t\tconst thousands = count / 1_000;\n\t\treturn thousands % 1 === 0 ? `${thousands}K` : `${thousands.toFixed(1)}K`;\n\t}\n\treturn count.toString();\n}\n\n/**\n * List available models, optionally filtered by search pattern\n */\nexport async function listModels(modelRuntime: ModelRuntime, searchPattern?: string): Promise<void> {\n\tconst loadError = modelRuntime.getError();\n\tif (loadError) {\n\t\tconsole.error(chalk.yellow(`Warning: errors loading models.json:\\n${loadError}`));\n\t}\n\n\tconst models = modelRuntime.getAvailableSnapshot();\n\n\tif (models.length === 0) {\n\t\tconsole.log(formatNoModelsAvailableMessage());\n\t\treturn;\n\t}\n\n\t// Apply fuzzy filter if search pattern provided\n\tlet filteredModels: Model<Api>[] = [...models];\n\tif (searchPattern) {\n\t\tfilteredModels = fuzzyFilter([...models], searchPattern, (m) => `${m.provider} ${m.id}`);\n\t}\n\n\tif (filteredModels.length === 0) {\n\t\tconsole.log(`No models matching \"${searchPattern}\"`);\n\t\treturn;\n\t}\n\n\t// Sort by provider, then by model id\n\tfilteredModels.sort((a, b) => {\n\t\tconst providerCmp = a.provider.localeCompare(b.provider);\n\t\tif (providerCmp !== 0) return providerCmp;\n\t\treturn a.id.localeCompare(b.id);\n\t});\n\n\t// Calculate column widths\n\tconst rows = filteredModels.map((m) => ({\n\t\tprovider: m.provider,\n\t\tmodel: m.id,\n\t\tcontext: formatTokenCount(m.contextWindow),\n\t\tmaxOut: formatTokenCount(m.maxTokens),\n\t\tthinking: m.reasoning ? \"yes\" : \"no\",\n\t\timages: m.input.includes(\"image\") ? \"yes\" : \"no\",\n\t}));\n\n\tconst headers = {\n\t\tprovider: \"provider\",\n\t\tmodel: \"model\",\n\t\tcontext: \"context\",\n\t\tmaxOut: \"max-out\",\n\t\tthinking: \"thinking\",\n\t\timages: \"images\",\n\t};\n\n\tconst widths = {\n\t\tprovider: Math.max(headers.provider.length, ...rows.map((r) => r.provider.length)),\n\t\tmodel: Math.max(headers.model.length, ...rows.map((r) => r.model.length)),\n\t\tcontext: Math.max(headers.context.length, ...rows.map((r) => r.context.length)),\n\t\tmaxOut: Math.max(headers.maxOut.length, ...rows.map((r) => r.maxOut.length)),\n\t\tthinking: Math.max(headers.thinking.length, ...rows.map((r) => r.thinking.length)),\n\t\timages: Math.max(headers.images.length, ...rows.map((r) => r.images.length)),\n\t};\n\n\t// Print header\n\tconst headerLine = [\n\t\theaders.provider.padEnd(widths.provider),\n\t\theaders.model.padEnd(widths.model),\n\t\theaders.context.padEnd(widths.context),\n\t\theaders.maxOut.padEnd(widths.maxOut),\n\t\theaders.thinking.padEnd(widths.thinking),\n\t\theaders.images.padEnd(widths.images),\n\t].join(\" \");\n\tconsole.log(headerLine);\n\n\t// Print rows\n\tfor (const row of rows) {\n\t\tconst line = [\n\t\t\trow.provider.padEnd(widths.provider),\n\t\t\trow.model.padEnd(widths.model),\n\t\t\trow.context.padEnd(widths.context),\n\t\t\trow.maxOut.padEnd(widths.maxOut),\n\t\t\trow.thinking.padEnd(widths.thinking),\n\t\t\trow.images.padEnd(widths.images),\n\t\t].join(\" \");\n\t\tconsole.log(line);\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { AssistantMessage } from "@earendil-works/pi-ai/compat";
1
+ import type { AssistantMessage } from "@bastani/pi-ai/compat";
2
2
  import type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from "./agent-session-methods.ts";
3
3
  import { type CompactionUrgency } from "./compaction/index.ts";
4
4
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACxH,OAAO,EACN,KAAK,iBAAiB,EAItB,MAAM,uBAAuB,CAAC;AAI/B;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,eAAO,MAAM,6CAA6C,IAAI,CAAC;AAS/D,6EAA6E;AAC7E,wBAAgB,8BAA8B,IAAI;IACjD,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,EAAE,MAAM,IAAI,CAAC;CACpB,CAMA;AAOD,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,YAAY,EAClB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,UAAO,GACrB,OAAO,CAAC,IAAI,CAAC,CAmLf;AAED,wBAAgB,uBAAuB,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAEnF;AAED,wBAAgB,wBAAwB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,GAA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AAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQrE;AAYD,wBAAgB,kCAAkC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAE9E;AAED,wBAAsB,kBAAkB,CACvC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,EAClB,OAAO,GAAE,iBAA0E,GACjF,OAAO,CAAC,wBAAwB,CAAC,CAmHnC;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;;CAQ7C,CAAC"}
@@ -1,4 +1,4 @@
1
- import { isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai/compat";
1
+ import { isContextOverflow, isRecoverableLength } from "@bastani/pi-ai/compat";
2
2
  import { calculateContextTokens, estimateContextTokens, shouldCompact, } from "./compaction/index.js";
3
3
  import { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from "./openai-responses-payload-sanitizer.js";
4
4
  import { getLatestCompactionBoundaryEntry } from "./session-manager.js";
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAEtF,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE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AiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QAC1E,UAAU,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@earendil-works/pi-ai/compat\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\n}\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\tconst contextOverflow = sameModel && isContextOverflow(assistantMessage, contextWindow);\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion && sameModel && isRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage: contextOverflow\n\t\t\t\t\t? \"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\"\n\t\t\t\t\t: \"Response truncation recovery stopped after one retry.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst restoreIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._restoreFallbackModel !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._restoreFallbackModel();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The model\n\t\t\t\t\t\t// state was already restored before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Restore before\n\t\t\t\t\t\t// Agent snapshots the next request's model.\n\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted =\n\t\t\terrorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
1
+ {"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE/E,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC;AAED,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+B,uBAAuB,CACtI,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAErC,gBAAkC,EAClC,gBAAgB,GAAG,IAAI;IAEvB,IAAI,IAAI,CAAC,+BAA+B,EAAE,CAAC;QAC1C,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,+BAA+B,CAAC;QACxD,IAAI,CAAC,+BAA+B,GAAG,SAAS,CAAC;QACjD,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,WAAW;YACnB,MAAM;YACN,OAAO,EAAE,IAAI;YACb,SAAS,EAAE,KAAK;YAChB,OAAO,EAAE,IAAI;YACb,GAAG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CAAC;YACtF,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACjE,YAAY,EAAE,OAAO;gBACpB,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,KAAK,UAAU;oBACtB,CAAC,CAAC,OAAO,KAAK,aAAa;wBAC1B,CAAC,CAAC,wCAAwC,YAAY,EAAE;wBACxD,CAAC,CAAC,qCAAqC,YAAY,EAAE;oBACtD,CAAC,CAAC,2BAA2B,YAAY,EAAE;SAC7C,CAAC,CAAC;QACH,OAAO,qBAAqB,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;IACtD,CAAC;YAAS,CAAC;QACV,IAAI,IAAI,CAAC,8BAA8B,KAAK,UAAU;YAAE,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QACxG,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QAC1E,UAAU,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\n}\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\tconst contextOverflow = sameModel && isContextOverflow(assistantMessage, contextWindow);\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion && sameModel && isRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage: contextOverflow\n\t\t\t\t\t? \"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\"\n\t\t\t\t\t: \"Response truncation recovery stopped after one retry.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst restoreIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._restoreFallbackModel !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._restoreFallbackModel();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The model\n\t\t\t\t\t\t// state was already restored before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Restore before\n\t\t\t\t\t\t// Agent snapshots the next request's model.\n\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted =\n\t\t\terrorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
@@ -1,5 +1,5 @@
1
+ import type { AssistantMessage, Message } from "@bastani/pi-ai/compat";
1
2
  import type { AgentEvent, AgentMessage } from "@earendil-works/pi-agent-core";
2
- import type { AssistantMessage, Message } from "@earendil-works/pi-ai/compat";
3
3
  import type { AgentSessionInternalSurface as AgentSession } from "./agent-session-methods.ts";
4
4
  import { type AgentSessionEvent, type AgentSessionEventListener } from "./agent-session-types.ts";
5
5
  export declare function _emit(this: AgentSession, event: AgentSessionEvent): void;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-events.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAe,MAAM,8BAA8B,CAAC;AAE3F,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAS9F,OAAO,EACN,KAAK,iBAAiB,EACtB,KAAK,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
@@ -1,4 +1,4 @@
1
- import { cleanupSessionResources } from "@earendil-works/pi-ai/compat";
1
+ import { cleanupSessionResources } from "@bastani/pi-ai/compat";
2
2
  import { isProtectedStreamingCustomMessage, markProtectedStreamingCustomMessageConsumed, markProtectedStreamingCustomMessagePersistenceFailed, persistProtectedStreamingCustomMessage, prepareProtectedStreamingCustomMessagesForDisposal, retryConsumedProtectedStreamingCustomMessages, } from "./agent-session-persistent-custom-messages.js";
3
3
  import { customMessageExcludesContext, isSingleGenericAbortTextContent, replacementAbortContent, } from "./agent-session-types.js";
4
4
  import { formatCodexProviderError } from "./codex-errors.js";