@code-yeongyu/senpi 2026.5.29 → 2026.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/CHANGELOG.md +131 -1
  2. package/README.md +12 -2
  3. package/dist/cli/args.d.ts +3 -0
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +28 -0
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +9 -1
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/agent-session-services.d.ts +1 -0
  11. package/dist/core/agent-session-services.d.ts.map +1 -1
  12. package/dist/core/agent-session-services.js +1 -0
  13. package/dist/core/agent-session-services.js.map +1 -1
  14. package/dist/core/agent-session.d.ts +9 -2
  15. package/dist/core/agent-session.d.ts.map +1 -1
  16. package/dist/core/agent-session.js +36 -13
  17. package/dist/core/agent-session.js.map +1 -1
  18. package/dist/core/compaction/branch-summarization.d.ts +3 -1
  19. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  20. package/dist/core/compaction/branch-summarization.js +9 -3
  21. package/dist/core/compaction/branch-summarization.js.map +1 -1
  22. package/dist/core/extensions/index.d.ts +1 -1
  23. package/dist/core/extensions/index.d.ts.map +1 -1
  24. package/dist/core/extensions/index.js.map +1 -1
  25. package/dist/core/extensions/runner.d.ts +5 -3
  26. package/dist/core/extensions/runner.d.ts.map +1 -1
  27. package/dist/core/extensions/runner.js +21 -3
  28. package/dist/core/extensions/runner.js.map +1 -1
  29. package/dist/core/extensions/types.d.ts +14 -6
  30. package/dist/core/extensions/types.d.ts.map +1 -1
  31. package/dist/core/extensions/types.js.map +1 -1
  32. package/dist/core/footer-data-provider.d.ts +2 -0
  33. package/dist/core/footer-data-provider.d.ts.map +1 -1
  34. package/dist/core/footer-data-provider.js +29 -1
  35. package/dist/core/footer-data-provider.js.map +1 -1
  36. package/dist/core/model-registry.d.ts.map +1 -1
  37. package/dist/core/model-registry.js +82 -21
  38. package/dist/core/model-registry.js.map +1 -1
  39. package/dist/core/model-resolver.d.ts.map +1 -1
  40. package/dist/core/model-resolver.js +2 -1
  41. package/dist/core/model-resolver.js.map +1 -1
  42. package/dist/core/provider-attribution.d.ts +4 -0
  43. package/dist/core/provider-attribution.d.ts.map +1 -0
  44. package/dist/core/provider-attribution.js +73 -0
  45. package/dist/core/provider-attribution.js.map +1 -0
  46. package/dist/core/provider-display-names.d.ts.map +1 -1
  47. package/dist/core/provider-display-names.js +1 -0
  48. package/dist/core/provider-display-names.js.map +1 -1
  49. package/dist/core/resolve-config-value.d.ts +9 -1
  50. package/dist/core/resolve-config-value.d.ts.map +1 -1
  51. package/dist/core/resolve-config-value.js +134 -11
  52. package/dist/core/resolve-config-value.js.map +1 -1
  53. package/dist/core/sdk.d.ts +2 -0
  54. package/dist/core/sdk.d.ts.map +1 -1
  55. package/dist/core/sdk.js +18 -40
  56. package/dist/core/sdk.js.map +1 -1
  57. package/dist/core/session-manager.d.ts +6 -7
  58. package/dist/core/session-manager.d.ts.map +1 -1
  59. package/dist/core/session-manager.js +167 -96
  60. package/dist/core/session-manager.js.map +1 -1
  61. package/dist/core/settings-manager.d.ts +3 -1
  62. package/dist/core/settings-manager.d.ts.map +1 -1
  63. package/dist/core/settings-manager.js +15 -11
  64. package/dist/core/settings-manager.js.map +1 -1
  65. package/dist/core/system-prompt.d.ts.map +1 -1
  66. package/dist/core/system-prompt.js +0 -3
  67. package/dist/core/system-prompt.js.map +1 -1
  68. package/dist/core/thinking-levels.d.ts.map +1 -1
  69. package/dist/core/thinking-levels.js +6 -2
  70. package/dist/core/thinking-levels.js.map +1 -1
  71. package/dist/core/tools/edit.d.ts.map +1 -1
  72. package/dist/core/tools/edit.js +7 -10
  73. package/dist/core/tools/edit.js.map +1 -1
  74. package/dist/core/tools/find.d.ts.map +1 -1
  75. package/dist/core/tools/find.js.map +1 -1
  76. package/dist/core/tools/grep.d.ts.map +1 -1
  77. package/dist/core/tools/grep.js.map +1 -1
  78. package/dist/core/tools/ls.d.ts.map +1 -1
  79. package/dist/core/tools/ls.js +5 -7
  80. package/dist/core/tools/ls.js.map +1 -1
  81. package/dist/core/tools/read.d.ts.map +1 -1
  82. package/dist/core/tools/read.js +6 -7
  83. package/dist/core/tools/read.js.map +1 -1
  84. package/dist/core/tools/render-utils.d.ts +5 -2
  85. package/dist/core/tools/render-utils.d.ts.map +1 -1
  86. package/dist/core/tools/render-utils.js +17 -1
  87. package/dist/core/tools/render-utils.js.map +1 -1
  88. package/dist/core/tools/write.d.ts.map +1 -1
  89. package/dist/core/tools/write.js +5 -6
  90. package/dist/core/tools/write.js.map +1 -1
  91. package/dist/index.d.ts +2 -0
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +2 -0
  94. package/dist/index.js.map +1 -1
  95. package/dist/main.d.ts.map +1 -1
  96. package/dist/main.js +76 -16
  97. package/dist/main.js.map +1 -1
  98. package/dist/migrations.d.ts.map +1 -1
  99. package/dist/migrations.js +118 -1
  100. package/dist/migrations.js.map +1 -1
  101. package/dist/modes/interactive/components/login-dialog.d.ts +1 -3
  102. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  103. package/dist/modes/interactive/components/login-dialog.js +2 -4
  104. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  105. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  106. package/dist/modes/interactive/components/tool-execution.js +25 -1
  107. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  108. package/dist/modes/interactive/interactive-mode.d.ts +3 -0
  109. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  110. package/dist/modes/interactive/interactive-mode.js +64 -6
  111. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  112. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  113. package/dist/modes/interactive/theme/theme.js +10 -0
  114. package/dist/modes/interactive/theme/theme.js.map +1 -1
  115. package/dist/modes/print-mode.d.ts.map +1 -1
  116. package/dist/modes/print-mode.js +1 -0
  117. package/dist/modes/print-mode.js.map +1 -1
  118. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  119. package/dist/modes/rpc/rpc-mode.js +4 -1
  120. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  121. package/dist/modes/rpc/rpc-types.d.ts +1 -0
  122. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  123. package/dist/modes/rpc/rpc-types.js.map +1 -1
  124. package/dist/utils/deprecation.d.ts +4 -0
  125. package/dist/utils/deprecation.d.ts.map +1 -0
  126. package/dist/utils/deprecation.js +13 -0
  127. package/dist/utils/deprecation.js.map +1 -0
  128. package/dist/utils/json.d.ts +3 -0
  129. package/dist/utils/json.d.ts.map +1 -0
  130. package/dist/utils/json.js +7 -0
  131. package/dist/utils/json.js.map +1 -0
  132. package/docs/custom-provider.md +13 -10
  133. package/docs/extensions.md +47 -17
  134. package/docs/models.md +25 -12
  135. package/docs/providers.md +15 -5
  136. package/docs/quickstart.md +1 -0
  137. package/docs/rpc.md +3 -2
  138. package/docs/sdk.md +6 -0
  139. package/docs/session-format.md +1 -1
  140. package/docs/sessions.md +8 -0
  141. package/docs/settings.md +4 -2
  142. package/docs/terminal-setup.md +2 -0
  143. package/docs/tui.md +12 -3
  144. package/docs/usage.md +10 -1
  145. package/examples/extensions/README.md +1 -0
  146. package/examples/extensions/custom-header.ts +1 -1
  147. package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
  148. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  149. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  150. package/examples/extensions/custom-provider-gitlab-duo/index.ts +54 -3
  151. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  152. package/examples/extensions/doom-overlay/index.ts +1 -1
  153. package/examples/extensions/git-merge-and-resolve.ts +115 -0
  154. package/examples/extensions/handoff.ts +1 -1
  155. package/examples/extensions/input-transform-streaming.ts +39 -0
  156. package/examples/extensions/interactive-shell.ts +1 -1
  157. package/examples/extensions/overlay-qa-tests.ts +152 -81
  158. package/examples/extensions/qna.ts +1 -1
  159. package/examples/extensions/question.ts +1 -1
  160. package/examples/extensions/questionnaire.ts +1 -1
  161. package/examples/extensions/sandbox/package-lock.json +2 -2
  162. package/examples/extensions/sandbox/package.json +1 -1
  163. package/examples/extensions/snake.ts +1 -1
  164. package/examples/extensions/space-invaders.ts +1 -1
  165. package/examples/extensions/summarize.ts +1 -1
  166. package/examples/extensions/tic-tac-toe.ts +1 -1
  167. package/examples/extensions/todo.ts +1 -1
  168. package/examples/extensions/tools.ts +5 -0
  169. package/examples/extensions/with-deps/package-lock.json +2 -2
  170. package/examples/extensions/with-deps/package.json +1 -1
  171. package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts +1 -0
  172. package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts.map +1 -1
  173. package/node_modules/@earendil-works/pi-agent-core/dist/agent.js +15 -0
  174. package/node_modules/@earendil-works/pi-agent-core/dist/agent.js.map +1 -1
  175. package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.d.ts +5 -2
  176. package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.d.ts.map +1 -1
  177. package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +81 -18
  178. package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js.map +1 -1
  179. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
  180. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +1 -0
  181. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js.map +1 -1
  182. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.d.ts.map +1 -1
  183. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +1 -0
  184. package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js.map +1 -1
  185. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.d.ts +1 -0
  186. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.d.ts.map +1 -1
  187. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +14 -1
  188. package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js.map +1 -1
  189. package/node_modules/@earendil-works/pi-agent-core/dist/harness/types.d.ts +22 -8
  190. package/node_modules/@earendil-works/pi-agent-core/dist/harness/types.d.ts.map +1 -1
  191. package/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js.map +1 -1
  192. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  193. package/node_modules/@earendil-works/pi-ai/README.md +5 -3
  194. package/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  195. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  196. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +1 -0
  197. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  198. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +15 -0
  199. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  200. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +15 -0
  201. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  202. package/node_modules/@earendil-works/pi-ai/dist/models.d.ts +2 -2
  203. package/node_modules/@earendil-works/pi-ai/dist/models.d.ts.map +1 -1
  204. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts +1294 -412
  205. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts.map +1 -1
  206. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js +1278 -652
  207. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js.map +1 -1
  208. package/node_modules/@earendil-works/pi-ai/dist/models.js +9 -4
  209. package/node_modules/@earendil-works/pi-ai/dist/models.js.map +1 -1
  210. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.d.ts +1 -1
  211. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.d.ts.map +1 -1
  212. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.js +89 -21
  213. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.js.map +1 -1
  214. package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.d.ts.map +1 -1
  215. package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.js +27 -14
  216. package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.js.map +1 -1
  217. package/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.d.ts.map +1 -1
  218. package/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js +5 -9
  219. package/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js.map +1 -1
  220. package/node_modules/@earendil-works/pi-ai/dist/providers/google-vertex.d.ts.map +1 -1
  221. package/node_modules/@earendil-works/pi-ai/dist/providers/google-vertex.js +1 -1
  222. package/node_modules/@earendil-works/pi-ai/dist/providers/google-vertex.js.map +1 -1
  223. package/node_modules/@earendil-works/pi-ai/dist/providers/google.d.ts.map +1 -1
  224. package/node_modules/@earendil-works/pi-ai/dist/providers/google.js +5 -3
  225. package/node_modules/@earendil-works/pi-ai/dist/providers/google.js.map +1 -1
  226. package/node_modules/@earendil-works/pi-ai/dist/providers/images/openrouter.d.ts.map +1 -1
  227. package/node_modules/@earendil-works/pi-ai/dist/providers/images/openrouter.js +2 -3
  228. package/node_modules/@earendil-works/pi-ai/dist/providers/images/openrouter.js.map +1 -1
  229. package/node_modules/@earendil-works/pi-ai/dist/providers/mistral.d.ts.map +1 -1
  230. package/node_modules/@earendil-works/pi-ai/dist/providers/mistral.js +2 -3
  231. package/node_modules/@earendil-works/pi-ai/dist/providers/mistral.js.map +1 -1
  232. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-codex-responses.d.ts.map +1 -1
  233. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-codex-responses.js +118 -52
  234. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-codex-responses.js.map +1 -1
  235. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-completions.d.ts.map +1 -1
  236. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-completions.js +27 -17
  237. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-completions.js.map +1 -1
  238. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses-shared.d.ts +1 -0
  239. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses-shared.d.ts.map +1 -1
  240. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses-shared.js +5 -1
  241. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses-shared.js.map +1 -1
  242. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses.d.ts.map +1 -1
  243. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses.js +5 -9
  244. package/node_modules/@earendil-works/pi-ai/dist/providers/openai-responses.js.map +1 -1
  245. package/node_modules/@earendil-works/pi-ai/dist/providers/simple-options.d.ts.map +1 -1
  246. package/node_modules/@earendil-works/pi-ai/dist/providers/simple-options.js +1 -0
  247. package/node_modules/@earendil-works/pi-ai/dist/providers/simple-options.js.map +1 -1
  248. package/node_modules/@earendil-works/pi-ai/dist/providers/transform-messages.d.ts +7 -0
  249. package/node_modules/@earendil-works/pi-ai/dist/providers/transform-messages.d.ts.map +1 -1
  250. package/node_modules/@earendil-works/pi-ai/dist/providers/transform-messages.js +8 -4
  251. package/node_modules/@earendil-works/pi-ai/dist/providers/transform-messages.js.map +1 -1
  252. package/node_modules/@earendil-works/pi-ai/dist/stream.d.ts.map +1 -1
  253. package/node_modules/@earendil-works/pi-ai/dist/stream.js +18 -4
  254. package/node_modules/@earendil-works/pi-ai/dist/stream.js.map +1 -1
  255. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +21 -5
  256. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  257. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  258. package/node_modules/@earendil-works/pi-ai/dist/utils/abort-signals.d.ts +6 -0
  259. package/node_modules/@earendil-works/pi-ai/dist/utils/abort-signals.d.ts.map +1 -0
  260. package/node_modules/@earendil-works/pi-ai/dist/utils/abort-signals.js +34 -0
  261. package/node_modules/@earendil-works/pi-ai/dist/utils/abort-signals.js.map +1 -0
  262. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.d.ts +9 -7
  263. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.d.ts.map +1 -1
  264. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.js +8 -7
  265. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.js.map +1 -1
  266. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/github-copilot.d.ts.map +1 -1
  267. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/github-copilot.js +1 -1
  268. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/github-copilot.js.map +1 -1
  269. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.d.ts +1 -1
  270. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.d.ts.map +1 -1
  271. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.js +1 -1
  272. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.js.map +1 -1
  273. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/openai-codex.d.ts +10 -1
  274. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/openai-codex.d.ts.map +1 -1
  275. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/openai-codex.js +179 -79
  276. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/openai-codex.js.map +1 -1
  277. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  278. package/node_modules/@earendil-works/pi-tui/README.md +15 -3
  279. package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +1 -1
  280. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +9 -53
  281. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +1 -1
  282. package/node_modules/@earendil-works/pi-tui/dist/components/input.d.ts.map +1 -1
  283. package/node_modules/@earendil-works/pi-tui/dist/components/input.js +6 -54
  284. package/node_modules/@earendil-works/pi-tui/dist/components/input.js.map +1 -1
  285. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +1 -1
  286. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +1 -1
  287. package/node_modules/@earendil-works/pi-tui/dist/index.js.map +1 -1
  288. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.d.ts +1 -1
  289. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.d.ts.map +1 -1
  290. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +34 -7
  291. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.js.map +1 -1
  292. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +33 -10
  293. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
  294. package/node_modules/@earendil-works/pi-tui/dist/terminal.js +173 -39
  295. package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
  296. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +18 -3
  297. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
  298. package/node_modules/@earendil-works/pi-tui/dist/tui.js +166 -22
  299. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  300. package/node_modules/@earendil-works/pi-tui/dist/utils.d.ts +1 -0
  301. package/node_modules/@earendil-works/pi-tui/dist/utils.d.ts.map +1 -1
  302. package/node_modules/@earendil-works/pi-tui/dist/utils.js +11 -3
  303. package/node_modules/@earendil-works/pi-tui/dist/utils.js.map +1 -1
  304. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.d.ts +25 -0
  305. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.d.ts.map +1 -0
  306. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.js +96 -0
  307. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.js.map +1 -0
  308. package/node_modules/@earendil-works/pi-tui/package.json +2 -2
  309. package/npm-shrinkwrap.json +56 -56
  310. package/package.json +5 -5
@@ -15,13 +15,13 @@
15
15
  * /overlay-sidepanel - Responsive sidepanel (hides when terminal < 100 cols)
16
16
  * /overlay-toggle - Toggle visibility demo (demonstrates OverlayHandle.setHidden)
17
17
  * /overlay-passive - Non-capturing overlay demo (passive info panel alongside active overlay)
18
- * /overlay-focus - Focus cycling and rendering order with non-capturing overlays
18
+ * /overlay-focus - Focus cycling, input routing, dismissal, and rendering order with overlays
19
19
  * /overlay-streaming - Multiple input panels with simulated streaming (Tab to cycle focus)
20
20
  */
21
21
 
22
22
  import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@code-yeongyu/senpi";
23
23
  import type { Component, OverlayAnchor, OverlayHandle, OverlayOptions, TUI } from "@earendil-works/pi-tui";
24
- import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
24
+ import { Input, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
25
25
  import { spawn } from "child_process";
26
26
 
27
27
  // Global handle for toggle demo (in real code, use a more elegant pattern)
@@ -272,9 +272,9 @@ export default function (pi: ExtensionAPI) {
272
272
  },
273
273
  });
274
274
 
275
- // Focus cycling demo - demonstrates focus(), unfocus(), isFocused() and rendering order
275
+ // Focus cycling demo - demonstrates focus(), input routing, per-panel dismissal, and rendering order
276
276
  pi.registerCommand("overlay-focus", {
277
- description: "Test focus cycling and rendering order with non-capturing overlays",
277
+ description: "Test focus cycling, input routing, dismissal, and rendering order with overlays",
278
278
  handler: async (_args: string, ctx: ExtensionCommandContext) => {
279
279
  ctx.ui.setEditorText("");
280
280
  await ctx.ui.custom<void>((tui, theme, _kb, done) => new FocusDemoController(tui, theme, done), {
@@ -1031,57 +1031,66 @@ class TimerPanel extends BaseOverlay {
1031
1031
 
1032
1032
  // === Focus cycling demo ===
1033
1033
 
1034
+ type FocusPanelColor = "error" | "success" | "accent";
1035
+ type FocusPanelConfig = { label: string; color: FocusPanelColor; options: OverlayOptions };
1036
+ type FocusPanelEntry = { panel: FocusPanel; handle: OverlayHandle };
1037
+
1038
+ const FOCUS_PANEL_CONFIGS = [
1039
+ { label: "Alpha", color: "error", options: { row: 2, col: 4, width: 34 } },
1040
+ { label: "Beta", color: "success", options: { row: 5, col: 28, width: 34 } },
1041
+ { label: "Gamma", color: "accent", options: { row: 8, col: 52, width: 34 } },
1042
+ ] satisfies FocusPanelConfig[];
1043
+
1034
1044
  class FocusDemoController extends BaseOverlay {
1035
- private tui: TUI;
1036
- private panels: FocusPanel[] = [];
1037
- private handles: OverlayHandle[] = [];
1038
- private focusIndex = -1;
1039
- private done: () => void;
1045
+ private readonly tui: TUI;
1046
+ private entries: FocusPanelEntry[] = [];
1047
+ private readonly done: () => void;
1048
+ private closed = false;
1040
1049
 
1041
1050
  constructor(tui: TUI, theme: Theme, done: () => void) {
1042
1051
  super(theme);
1043
1052
  this.tui = tui;
1044
1053
  this.done = done;
1045
- const colors = ["error", "success", "accent"] as const;
1046
- const labels = ["Alpha", "Beta", "Gamma"];
1047
1054
 
1048
- for (let i = 0; i < 3; i++) {
1049
- const panel = new FocusPanel(
1050
- theme,
1051
- labels[i]!,
1052
- colors[i]!,
1053
- () => this.cycleFocus(),
1054
- () => this.close(),
1055
- );
1056
- const handle = this.tui.showOverlay(panel, {
1057
- nonCapturing: true,
1058
- row: 2,
1059
- col: 5 + i * 6,
1060
- width: 28,
1061
- });
1062
- panel.handle = handle;
1063
- this.panels.push(panel);
1064
- this.handles.push(handle);
1055
+ for (const config of FOCUS_PANEL_CONFIGS) {
1056
+ const panel = new FocusPanel({ theme, config, controller: this });
1057
+ const handle = this.tui.showOverlay(panel, { nonCapturing: true, ...config.options });
1058
+ this.entries.push({ panel, handle });
1065
1059
  }
1060
+
1061
+ this.focusFirstOpenPanel();
1066
1062
  }
1067
1063
 
1068
- private cycleFocus(): void {
1069
- if (this.focusIndex >= 0 && this.focusIndex < this.handles.length) {
1070
- this.handles[this.focusIndex]!.unfocus();
1071
- }
1072
- this.focusIndex++;
1073
- if (this.focusIndex >= this.handles.length) {
1074
- this.focusIndex = -1;
1075
- } else {
1076
- this.handles[this.focusIndex]!.focus();
1064
+ focusNext(current: FocusPanel, direction: 1 | -1 = 1): void {
1065
+ const openEntries = this.openEntries();
1066
+ const currentOpenPosition = openEntries.findIndex((entry) => entry.panel === current);
1067
+ if (currentOpenPosition === -1) throw new Error(`Panel ${current.label} is not open`);
1068
+ const nextOpenPosition = (currentOpenPosition + direction + openEntries.length) % openEntries.length;
1069
+ this.focusEntryAt(openEntries, nextOpenPosition);
1070
+ }
1071
+
1072
+ dismiss(panel: FocusPanel): void {
1073
+ const openEntries = this.openEntries();
1074
+ const currentOpenPosition = openEntries.findIndex((candidate) => candidate.panel === panel);
1075
+ if (currentOpenPosition === -1) return;
1076
+ const entry = openEntries[currentOpenPosition];
1077
+ if (!entry) throw new Error(`Invalid focus panel index ${currentOpenPosition}`);
1078
+ const remainingEntries = openEntries.filter((candidate) => candidate.panel !== panel);
1079
+
1080
+ entry.panel.closed = true;
1081
+ entry.handle.hide();
1082
+ if (remainingEntries.length === 0) {
1083
+ this.close();
1084
+ return;
1077
1085
  }
1078
- this.tui.requestRender();
1086
+
1087
+ this.focusEntryAt(remainingEntries, currentOpenPosition % remainingEntries.length);
1079
1088
  }
1080
1089
 
1081
- private close(): void {
1082
- for (const handle of this.handles) handle.hide();
1083
- this.handles = [];
1084
- this.panels = [];
1090
+ close(): void {
1091
+ if (this.closed) return;
1092
+ this.closed = true;
1093
+ this.hidePanels();
1085
1094
  this.done();
1086
1095
  }
1087
1096
 
@@ -1089,86 +1098,148 @@ class FocusDemoController extends BaseOverlay {
1089
1098
  if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
1090
1099
  this.close();
1091
1100
  } else if (matchesKey(data, "tab")) {
1092
- this.cycleFocus();
1101
+ this.focusFirstOpenPanel();
1093
1102
  }
1094
1103
  }
1095
1104
 
1096
1105
  render(width: number): string[] {
1097
1106
  const th = this.theme;
1098
- const focused = this.focusIndex === -1 ? "Controller" : (this.panels[this.focusIndex]?.label ?? "?");
1107
+ const focused = this.entries.find((entry) => entry.handle.isFocused())?.panel.label ?? "Controller";
1099
1108
  return this.box(
1100
1109
  [
1101
1110
  "",
1102
1111
  ` Current focus: ${th.fg("accent", focused)}`,
1103
1112
  "",
1104
1113
  " Three overlapping panels above are",
1105
- ` all ${th.fg("accent", "nonCapturing")}. Press Tab to`,
1106
- " cycle focus() between them.",
1114
+ ` ${th.fg("accent", "nonCapturing")} overlays controlled with`,
1115
+ " raw OverlayHandle.focus()/hide().",
1107
1116
  "",
1108
- " Focused panel renders on top",
1109
- " (focus-based rendering order).",
1117
+ " Type in the focused panel's input.",
1118
+ " Focused panel renders on top.",
1110
1119
  "",
1111
- th.fg("dim", " Tab = cycle focus | Esc = close"),
1120
+ th.fg("dim", " Tab/Shift+Tab = cycle panels"),
1121
+ th.fg("dim", " Esc/Ctrl+D = dismiss panel"),
1122
+ th.fg("dim", " Ctrl+C = close all"),
1112
1123
  "",
1113
1124
  ],
1114
1125
  width,
1115
- "Focus Demo",
1126
+ "Focus + Input Demo",
1116
1127
  );
1117
1128
  }
1118
1129
 
1119
1130
  override dispose(): void {
1120
- for (const handle of this.handles) handle.hide();
1131
+ if (this.closed) return;
1132
+ this.closed = true;
1133
+ this.hidePanels();
1134
+ }
1135
+
1136
+ private focusFirstOpenPanel(): void {
1137
+ const firstOpen = this.openEntries()[0];
1138
+ if (firstOpen) {
1139
+ firstOpen.handle.focus();
1140
+ this.tui.requestRender();
1141
+ }
1142
+ }
1143
+
1144
+ private focusEntryAt(entries: FocusPanelEntry[], index: number): void {
1145
+ const entry = entries[index];
1146
+ if (!entry) throw new Error(`Invalid focus panel index ${index}`);
1147
+ entry.handle.focus();
1148
+ this.tui.requestRender();
1149
+ }
1150
+
1151
+ private hidePanels(): void {
1152
+ for (const entry of this.entries) {
1153
+ if (!entry.panel.closed) {
1154
+ entry.panel.closed = true;
1155
+ entry.handle.hide();
1156
+ }
1157
+ }
1158
+ this.entries = [];
1159
+ }
1160
+
1161
+ private openEntries(): FocusPanelEntry[] {
1162
+ return this.entries.filter((entry) => !entry.panel.closed);
1121
1163
  }
1122
1164
  }
1123
1165
 
1124
1166
  class FocusPanel extends BaseOverlay {
1125
- handle: OverlayHandle | null = null;
1167
+ focused = false;
1168
+ closed = false;
1126
1169
  readonly label: string;
1127
- private color: "error" | "success" | "accent";
1128
- private onTab: () => void;
1129
- private onClose: () => void;
1130
-
1131
- constructor(
1132
- theme: Theme,
1133
- label: string,
1134
- color: "error" | "success" | "accent",
1135
- onTab: () => void,
1136
- onClose: () => void,
1137
- ) {
1170
+ private readonly color: FocusPanelColor;
1171
+ private readonly controller: FocusDemoController;
1172
+ private readonly input = new Input();
1173
+ private inputs: string[] = [];
1174
+
1175
+ constructor({
1176
+ theme,
1177
+ config,
1178
+ controller,
1179
+ }: {
1180
+ theme: Theme;
1181
+ config: FocusPanelConfig;
1182
+ controller: FocusDemoController;
1183
+ }) {
1138
1184
  super(theme);
1139
- this.label = label;
1140
- this.color = color;
1141
- this.onTab = onTab;
1142
- this.onClose = onClose;
1185
+ this.label = config.label;
1186
+ this.color = config.color;
1187
+ this.controller = controller;
1143
1188
  }
1144
1189
 
1145
1190
  handleInput(data: string): void {
1146
1191
  if (matchesKey(data, "tab")) {
1147
- this.onTab();
1148
- } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
1149
- this.onClose();
1192
+ this.controller.focusNext(this);
1193
+ } else if (matchesKey(data, "shift+tab")) {
1194
+ this.controller.focusNext(this, -1);
1195
+ } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+d")) {
1196
+ this.controller.dismiss(this);
1197
+ } else if (matchesKey(data, "ctrl+c")) {
1198
+ this.controller.close();
1199
+ } else if (matchesKey(data, "return")) {
1200
+ this.inputs.push("Enter");
1201
+ } else if (matchesKey(data, "up")) {
1202
+ this.inputs.push("↑");
1203
+ } else if (matchesKey(data, "down")) {
1204
+ this.inputs.push("↓");
1205
+ } else if (matchesKey(data, "left")) {
1206
+ this.input.handleInput(data);
1207
+ this.inputs.push("←");
1208
+ } else if (matchesKey(data, "right")) {
1209
+ this.input.handleInput(data);
1210
+ this.inputs.push("→");
1211
+ } else if (matchesKey(data, "backspace")) {
1212
+ this.input.handleInput(data);
1213
+ this.inputs.push("Backspace");
1214
+ } else {
1215
+ this.input.handleInput(data);
1216
+ this.inputs.push(JSON.stringify(data));
1150
1217
  }
1151
1218
  }
1152
1219
 
1153
1220
  render(width: number): string[] {
1154
1221
  const th = this.theme;
1155
- const focused = this.handle?.isFocused() ?? false;
1156
1222
  const innerW = Math.max(1, width - 2);
1157
- const border = (c: string) => th.fg(this.color, c);
1223
+ const border = (c: string) => th.fg(this.focused ? this.color : "dim", c);
1158
1224
  const padLine = (s: string) => truncateToWidth(s, innerW, "...", true);
1225
+ const recent = this.inputs.length === 0 ? "(none)" : this.inputs.slice(-6).join(" ");
1159
1226
  const lines: string[] = [];
1160
1227
 
1228
+ this.input.focused = this.focused;
1229
+ const [inputLine = ""] = this.input.render(Math.max(1, innerW - 8));
1161
1230
  lines.push(border(`╭${"─".repeat(innerW)}╮`));
1162
- lines.push(border("│") + padLine(` ${th.fg("accent", this.label)}`) + border("│"));
1163
- lines.push(border("│") + padLine("") + border("│"));
1164
- if (focused) {
1165
- lines.push(border("│") + padLine(th.fg("success", "FOCUSED")) + border(""));
1166
- lines.push(border("│") + padLine(th.fg("dim", " (receiving input)")) + border("│"));
1167
- } else {
1168
- lines.push(border("│") + padLine(th.fg("dim", " ○ unfocused")) + border("│"));
1169
- lines.push(border("│") + padLine(th.fg("dim", " (passive)")) + border("│"));
1170
- }
1231
+ lines.push(
1232
+ border("│") +
1233
+ padLine(
1234
+ ` ${th.fg(this.color, this.label)} ${this.focused ? th.fg("success", "FOCUSED") : th.fg("dim", "visible")}`,
1235
+ ) +
1236
+ border("│"),
1237
+ );
1171
1238
  lines.push(border("│") + padLine("") + border("│"));
1239
+ lines.push(border("│") + padLine(` Input: ${inputLine}`) + border("│"));
1240
+ lines.push(border("│") + padLine(` Keys: ${recent}`) + border("│"));
1241
+ lines.push(border("│") + padLine(th.fg("dim", " Tab/Shift+Tab focus")) + border("│"));
1242
+ lines.push(border("│") + padLine(th.fg("dim", " Esc/Ctrl+D dismiss")) + border("│"));
1172
1243
  lines.push(border(`╰${"─".repeat(innerW)}╯`));
1173
1244
 
1174
1245
  return lines;
@@ -31,7 +31,7 @@ export default function (pi: ExtensionAPI) {
31
31
  pi.registerCommand("qna", {
32
32
  description: "Extract questions from last assistant message into editor",
33
33
  handler: async (_args, ctx) => {
34
- if (!ctx.hasUI) {
34
+ if (ctx.mode !== "tui") {
35
35
  ctx.ui.notify("qna requires interactive mode", "error");
36
36
  return;
37
37
  }
@@ -41,7 +41,7 @@ export default function question(pi: ExtensionAPI) {
41
41
  parameters: QuestionParams,
42
42
 
43
43
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
44
- if (!ctx.hasUI) {
44
+ if (ctx.mode !== "tui") {
45
45
  return {
46
46
  content: [{ type: "text", text: "Error: UI not available (running in non-interactive mode)" }],
47
47
  details: {
@@ -82,7 +82,7 @@ export default function questionnaire(pi: ExtensionAPI) {
82
82
  parameters: QuestionnaireParams,
83
83
 
84
84
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
85
- if (!ctx.hasUI) {
85
+ if (ctx.mode !== "tui") {
86
86
  return errorResult("Error: UI not available (running in non-interactive mode)");
87
87
  }
88
88
  if (params.questions.length === 0) {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pi-extension-sandbox",
3
- "version": "1.5.5",
3
+ "version": "1.8.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pi-extension-sandbox",
9
- "version": "1.5.5",
9
+ "version": "1.8.0",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sandbox-runtime": "^0.0.26"
12
12
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-extension-sandbox",
3
3
  "private": true,
4
- "version": "1.5.5",
4
+ "version": "1.8.0",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "clean": "echo 'nothing to clean'",
@@ -311,7 +311,7 @@ export default function (pi: ExtensionAPI) {
311
311
  description: "Play Snake!",
312
312
 
313
313
  handler: async (_args, ctx) => {
314
- if (!ctx.hasUI) {
314
+ if (ctx.mode !== "tui") {
315
315
  ctx.ui.notify("Snake requires interactive mode", "error");
316
316
  return;
317
317
  }
@@ -529,7 +529,7 @@ export default function (pi: ExtensionAPI) {
529
529
  description: "Play Space Invaders!",
530
530
 
531
531
  handler: async (_args, ctx) => {
532
- if (!ctx.hasUI) {
532
+ if (ctx.mode !== "tui") {
533
533
  ctx.ui.notify("Space Invaders requires interactive mode", "error");
534
534
  return;
535
535
  }
@@ -115,7 +115,7 @@ const buildSummaryPrompt = (conversationText: string): string =>
115
115
  ].join("\n");
116
116
 
117
117
  const showSummaryUi = async (summary: string, ctx: ExtensionCommandContext) => {
118
- if (!ctx.hasUI) {
118
+ if (ctx.mode !== "tui") {
119
119
  return;
120
120
  }
121
121
 
@@ -779,7 +779,7 @@ Decide the target cell first, then dump every action for the turn in one go.
779
779
  description: "Play tic-tac-toe against the agent",
780
780
 
781
781
  handler: async (_args, ctx) => {
782
- if (!ctx.hasUI) {
782
+ if (ctx.mode !== "tui") {
783
783
  ctx.ui.notify("Tic-tac-toe requires interactive mode", "error");
784
784
  return;
785
785
  }
@@ -284,7 +284,7 @@ export default function (pi: ExtensionAPI) {
284
284
  pi.registerCommand("todos", {
285
285
  description: "Show all todos on the current branch",
286
286
  handler: async (_args, ctx) => {
287
- if (!ctx.hasUI) {
287
+ if (ctx.mode !== "tui") {
288
288
  ctx.ui.notify("/todos requires interactive mode", "error");
289
289
  return;
290
290
  }
@@ -67,6 +67,11 @@ export default function toolsExtension(pi: ExtensionAPI) {
67
67
  pi.registerCommand("tools", {
68
68
  description: "Enable/disable tools",
69
69
  handler: async (_args, ctx) => {
70
+ if (ctx.mode !== "tui") {
71
+ ctx.ui.notify("/tools requires TUI mode", "error");
72
+ return;
73
+ }
74
+
70
75
  // Refresh tool list
71
76
  allTools = pi.getAllTools();
72
77
 
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pi-extension-with-deps",
3
- "version": "0.75.5",
3
+ "version": "0.78.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pi-extension-with-deps",
9
- "version": "0.75.5",
9
+ "version": "0.78.0",
10
10
  "dependencies": {
11
11
  "ms": "^2.1.3"
12
12
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-extension-with-deps",
3
3
  "private": true,
4
- "version": "0.75.5",
4
+ "version": "0.78.0",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "clean": "echo 'nothing to clean'",
@@ -113,6 +113,7 @@ export declare class Agent {
113
113
  private createContextSnapshot;
114
114
  private createLoopConfig;
115
115
  private runWithLifecycle;
116
+ private runQueuedMessagesAfterAgentEnd;
116
117
  private handleRunFailure;
117
118
  private finishRun;
118
119
  private processEvents;
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EAEV,mBAAmB,EACnB,YAAY,EACZ,UAAU,EAEV,qBAAqB,EACrB,oBAAoB,EACpB,SAAS,EACT,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;IACvD,IAAI,MAAM,IAAI,WAAW,GAAG,SAAS,CAEpC;IAED,+CAA+C;IAC/C,KAAK,IAAI,IAAI,CAEZ;IAED;;;;OAIG;IACH,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3B;IAED,kEAAkE;IAClE,KAAK,IAAI,IAAI,CAQZ;IAED,8EAA8E;IACxE,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAWpE,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA2B9B;IAED,OAAO,CAAC,oBAAoB;YAmBd,iBAAiB;YAgBjB,eAAe;IAY7B,OAAO,CAAC,qBAAqB;IAQ7B,OAAO,CAAC,gBAAgB;YA8BV,gBAAgB;YAyBhB,gBAAgB;IAkB9B,OAAO,CAAC,SAAS;YAeH,aAAa;CAgD3B","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@earendil-works/pi-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\ttimeoutMs?: number;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\tpublic timeoutMs?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.timeoutMs = options.timeoutMs;\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\ttimeoutMs: this.timeoutMs,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAGxB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EAEV,mBAAmB,EACnB,YAAY,EACZ,UAAU,EAEV,qBAAqB,EACrB,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAkE5C,iDAAiD;AACjD,MAAM,WAAW,YAAY;IAC5B,YAAY,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,kBAAkB,GAAG,aAAa,GAAG,kBAAkB,GAAG,cAAc,CAAC,CAAC,CAAC;IACnH,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5E,gBAAgB,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,EAAE,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC;IAC/F,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,GAAG,SAAS,CAAC;IACnF,SAAS,CAAC,EAAE,mBAAmB,CAAC,WAAW,CAAC,CAAC;IAC7C,UAAU,CAAC,EAAE,mBAAmB,CAAC,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tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@earendil-works/pi-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\ttimeoutMs?: number;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\tpublic timeoutMs?: number;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.timeoutMs = options.timeoutMs;\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\ttimeoutMs: this.timeoutMs,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t\twhile (!abortController.signal.aborted && this.hasQueuedMessages()) {\n\t\t\t\tawait this.runQueuedMessagesAfterAgentEnd(abortController.signal);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async runQueuedMessagesAfterAgentEnd(signal: AbortSignal): Promise<void> {\n\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\tif (queuedSteering.length > 0) {\n\t\t\tawait runAgentLoop(\n\t\t\t\tqueuedSteering,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig({ skipInitialSteeringPoll: true }),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\tif (queuedFollowUps.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait runAgentLoop(\n\t\t\tqueuedFollowUps,\n\t\t\tthis.createContextSnapshot(),\n\t\t\tthis.createLoopConfig(),\n\t\t\t(event) => this.processEvents(event),\n\t\t\tsignal,\n\t\t\tthis.streamFn,\n\t\t);\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
@@ -321,6 +321,9 @@ export class Agent {
321
321
  this._state.errorMessage = undefined;
322
322
  try {
323
323
  await executor(abortController.signal);
324
+ while (!abortController.signal.aborted && this.hasQueuedMessages()) {
325
+ await this.runQueuedMessagesAfterAgentEnd(abortController.signal);
326
+ }
324
327
  }
325
328
  catch (error) {
326
329
  await this.handleRunFailure(error, abortController.signal.aborted);
@@ -329,6 +332,18 @@ export class Agent {
329
332
  this.finishRun();
330
333
  }
331
334
  }
335
+ async runQueuedMessagesAfterAgentEnd(signal) {
336
+ const queuedSteering = this.steeringQueue.drain();
337
+ if (queuedSteering.length > 0) {
338
+ await runAgentLoop(queuedSteering, this.createContextSnapshot(), this.createLoopConfig({ skipInitialSteeringPoll: true }), (event) => this.processEvents(event), signal, this.streamFn);
339
+ return;
340
+ }
341
+ const queuedFollowUps = this.followUpQueue.drain();
342
+ if (queuedFollowUps.length === 0) {
343
+ return;
344
+ }
345
+ await runAgentLoop(queuedFollowUps, this.createContextSnapshot(), this.createLoopConfig(), (event) => this.processEvents(event), signal, this.streamFn);
346
+ }
332
347
  async handleRunFailure(error, aborted) {
333
348
  const failureMessage = {
334
349
  role: "assistant",