@bastani/atomic 0.9.3-alpha.4 → 0.9.3-alpha.6

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 (335) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/builtin/cursor/CHANGELOG.md +12 -0
  3. package/dist/builtin/cursor/package.json +3 -3
  4. package/dist/builtin/cursor/src/auth.ts +1 -1
  5. package/dist/builtin/cursor/src/model-mapper.ts +1 -1
  6. package/dist/builtin/cursor/src/model-reference.ts +1 -1
  7. package/dist/builtin/cursor/src/proto/protobuf-codec-request.ts +1 -1
  8. package/dist/builtin/cursor/src/provider.ts +1 -1
  9. package/dist/builtin/cursor/src/stream.ts +1 -1
  10. package/dist/builtin/cursor/src/transport-types.ts +1 -1
  11. package/dist/builtin/intercom/CHANGELOG.md +12 -0
  12. package/dist/builtin/intercom/package.json +2 -2
  13. package/dist/builtin/mcp/CHANGELOG.md +12 -0
  14. package/dist/builtin/mcp/package.json +3 -3
  15. package/dist/builtin/mcp/sampling-handler.ts +1 -1
  16. package/dist/builtin/mcp/types.ts +1 -1
  17. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  18. package/dist/builtin/subagents/agents/code-simplifier.md +1 -1
  19. package/dist/builtin/subagents/agents/codebase-analyzer.md +1 -1
  20. package/dist/builtin/subagents/agents/codebase-locator.md +1 -1
  21. package/dist/builtin/subagents/agents/codebase-online-researcher.md +1 -1
  22. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +1 -1
  23. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +1 -1
  24. package/dist/builtin/subagents/agents/codebase-research-locator.md +1 -1
  25. package/dist/builtin/subagents/agents/debugger.md +1 -1
  26. package/dist/builtin/subagents/agents/worker.md +1 -1
  27. package/dist/builtin/subagents/package.json +4 -4
  28. package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +1 -1
  29. package/dist/builtin/subagents/src/runs/background/subagent-runner-types.ts +1 -1
  30. package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +1 -1
  31. package/dist/builtin/subagents/src/runs/shared/structured-output.ts +1 -1
  32. package/dist/builtin/subagents/src/shared/types-results.ts +1 -1
  33. package/dist/builtin/subagents/src/shared/utils.ts +1 -1
  34. package/dist/builtin/subagents/src/slash/slash-live-state.ts +1 -1
  35. package/dist/builtin/web-access/CHANGELOG.md +12 -0
  36. package/dist/builtin/web-access/package.json +2 -2
  37. package/dist/builtin/web-access/summary-review.ts +1 -1
  38. package/dist/builtin/web-access/web-search-summary.ts +1 -1
  39. package/dist/builtin/web-access/web-search-tool.ts +1 -1
  40. package/dist/builtin/workflows/CHANGELOG.md +12 -0
  41. package/dist/builtin/workflows/builtin/deep-research-codebase-utils.ts +6 -1
  42. package/dist/builtin/workflows/builtin/goal-runner.ts +12 -2
  43. package/dist/builtin/workflows/builtin/open-claude-design-runner.ts +4 -0
  44. package/dist/builtin/workflows/builtin/ralph-models.ts +40 -6
  45. package/dist/builtin/workflows/package.json +2 -2
  46. package/dist/bun/register-bedrock.d.ts.map +1 -1
  47. package/dist/bun/register-bedrock.js +1 -1
  48. package/dist/bun/register-bedrock.js.map +1 -1
  49. package/dist/cli/file-processor.d.ts +1 -1
  50. package/dist/cli/file-processor.d.ts.map +1 -1
  51. package/dist/cli/file-processor.js.map +1 -1
  52. package/dist/cli/initial-message.d.ts +1 -1
  53. package/dist/cli/initial-message.d.ts.map +1 -1
  54. package/dist/cli/initial-message.js.map +1 -1
  55. package/dist/cli/list-models.d.ts.map +1 -1
  56. package/dist/cli/list-models.js.map +1 -1
  57. package/dist/core/agent-session-auto-compaction.d.ts +1 -1
  58. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  59. package/dist/core/agent-session-auto-compaction.js +1 -1
  60. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  61. package/dist/core/agent-session-events.d.ts +1 -1
  62. package/dist/core/agent-session-events.d.ts.map +1 -1
  63. package/dist/core/agent-session-events.js +1 -1
  64. package/dist/core/agent-session-events.js.map +1 -1
  65. package/dist/core/agent-session-export.d.ts.map +1 -1
  66. package/dist/core/agent-session-export.js.map +1 -1
  67. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  68. package/dist/core/agent-session-extension-bindings.js +1 -1
  69. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  70. package/dist/core/agent-session-message-queue.d.ts +1 -1
  71. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  72. package/dist/core/agent-session-message-queue.js.map +1 -1
  73. package/dist/core/agent-session-methods.d.ts +1 -1
  74. package/dist/core/agent-session-methods.d.ts.map +1 -1
  75. package/dist/core/agent-session-methods.js.map +1 -1
  76. package/dist/core/agent-session-models.d.ts +1 -1
  77. package/dist/core/agent-session-models.d.ts.map +1 -1
  78. package/dist/core/agent-session-models.js +1 -1
  79. package/dist/core/agent-session-models.js.map +1 -1
  80. package/dist/core/agent-session-prompt.d.ts +1 -1
  81. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  82. package/dist/core/agent-session-prompt.js.map +1 -1
  83. package/dist/core/agent-session-retry.d.ts +1 -1
  84. package/dist/core/agent-session-retry.d.ts.map +1 -1
  85. package/dist/core/agent-session-retry.js +1 -1
  86. package/dist/core/agent-session-retry.js.map +1 -1
  87. package/dist/core/agent-session-services.d.ts +1 -1
  88. package/dist/core/agent-session-services.d.ts.map +1 -1
  89. package/dist/core/agent-session-services.js.map +1 -1
  90. package/dist/core/agent-session-state.d.ts +1 -1
  91. package/dist/core/agent-session-state.d.ts.map +1 -1
  92. package/dist/core/agent-session-state.js.map +1 -1
  93. package/dist/core/agent-session-types.d.ts +1 -1
  94. package/dist/core/agent-session-types.d.ts.map +1 -1
  95. package/dist/core/agent-session-types.js.map +1 -1
  96. package/dist/core/agent-session.d.ts +1 -1
  97. package/dist/core/agent-session.d.ts.map +1 -1
  98. package/dist/core/agent-session.js.map +1 -1
  99. package/dist/core/anthropic-thinking-guard.d.ts +1 -1
  100. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  101. package/dist/core/anthropic-thinking-guard.js.map +1 -1
  102. package/dist/core/auth-storage.d.ts +2 -2
  103. package/dist/core/auth-storage.d.ts.map +1 -1
  104. package/dist/core/auth-storage.js +1 -1
  105. package/dist/core/auth-storage.js.map +1 -1
  106. package/dist/core/codex-fast-mode.d.ts +1 -1
  107. package/dist/core/codex-fast-mode.d.ts.map +1 -1
  108. package/dist/core/codex-fast-mode.js +1 -1
  109. package/dist/core/codex-fast-mode.js.map +1 -1
  110. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  111. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  112. package/dist/core/compaction/branch-summarization.js +1 -1
  113. package/dist/core/compaction/branch-summarization.js.map +1 -1
  114. package/dist/core/compaction/compaction.d.ts +1 -1
  115. package/dist/core/compaction/compaction.d.ts.map +1 -1
  116. package/dist/core/compaction/compaction.js.map +1 -1
  117. package/dist/core/compaction/context-compaction-runner.d.ts +1 -1
  118. package/dist/core/compaction/context-compaction-runner.d.ts.map +1 -1
  119. package/dist/core/compaction/context-compaction-runner.js +1 -1
  120. package/dist/core/compaction/context-compaction-runner.js.map +1 -1
  121. package/dist/core/compaction/context-deletion-tool-definitions.d.ts.map +1 -1
  122. package/dist/core/compaction/context-deletion-tool-definitions.js +1 -1
  123. package/dist/core/compaction/context-deletion-tool-definitions.js.map +1 -1
  124. package/dist/core/compaction/context-transcript-analysis.d.ts.map +1 -1
  125. package/dist/core/compaction/context-transcript-analysis.js.map +1 -1
  126. package/dist/core/compaction/utils.d.ts +1 -1
  127. package/dist/core/compaction/utils.d.ts.map +1 -1
  128. package/dist/core/compaction/utils.js.map +1 -1
  129. package/dist/core/context-window.d.ts +2 -2
  130. package/dist/core/context-window.d.ts.map +1 -1
  131. package/dist/core/context-window.js.map +1 -1
  132. package/dist/core/copilot-gemini-payload-sanitizer.d.ts +1 -1
  133. package/dist/core/copilot-gemini-payload-sanitizer.d.ts.map +1 -1
  134. package/dist/core/copilot-gemini-payload-sanitizer.js.map +1 -1
  135. package/dist/core/copilot-gemini-reasoning.d.ts +1 -1
  136. package/dist/core/copilot-gemini-reasoning.d.ts.map +1 -1
  137. package/dist/core/copilot-gemini-reasoning.js.map +1 -1
  138. package/dist/core/copilot-gemini-tool-arguments.d.ts +1 -1
  139. package/dist/core/copilot-gemini-tool-arguments.d.ts.map +1 -1
  140. package/dist/core/copilot-gemini-tool-arguments.js.map +1 -1
  141. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  142. package/dist/core/export-html/tool-renderer.js.map +1 -1
  143. package/dist/core/extensions/agent-events.d.ts +1 -1
  144. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  145. package/dist/core/extensions/agent-events.js.map +1 -1
  146. package/dist/core/extensions/api-types.d.ts +1 -1
  147. package/dist/core/extensions/api-types.d.ts.map +1 -1
  148. package/dist/core/extensions/api-types.js.map +1 -1
  149. package/dist/core/extensions/context-types.d.ts +1 -1
  150. package/dist/core/extensions/context-types.d.ts.map +1 -1
  151. package/dist/core/extensions/context-types.js.map +1 -1
  152. package/dist/core/extensions/event-results.d.ts +1 -1
  153. package/dist/core/extensions/event-results.d.ts.map +1 -1
  154. package/dist/core/extensions/event-results.js.map +1 -1
  155. package/dist/core/extensions/loader-virtual-modules.d.ts +12 -0
  156. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  157. package/dist/core/extensions/loader-virtual-modules.js +18 -2
  158. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  159. package/dist/core/extensions/provider-types.d.ts +1 -1
  160. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  161. package/dist/core/extensions/provider-types.js.map +1 -1
  162. package/dist/core/extensions/runner-context.d.ts +1 -1
  163. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  164. package/dist/core/extensions/runner-context.js.map +1 -1
  165. package/dist/core/extensions/runner-events.d.ts +1 -1
  166. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  167. package/dist/core/extensions/runner-events.js.map +1 -1
  168. package/dist/core/extensions/runner.d.ts +1 -1
  169. package/dist/core/extensions/runner.d.ts.map +1 -1
  170. package/dist/core/extensions/runner.js.map +1 -1
  171. package/dist/core/extensions/runtime-types.d.ts +1 -1
  172. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  173. package/dist/core/extensions/runtime-types.js.map +1 -1
  174. package/dist/core/extensions/tool-events.d.ts +1 -1
  175. package/dist/core/extensions/tool-events.d.ts.map +1 -1
  176. package/dist/core/extensions/tool-events.js.map +1 -1
  177. package/dist/core/footer-data-provider.d.ts +5 -0
  178. package/dist/core/footer-data-provider.d.ts.map +1 -1
  179. package/dist/core/footer-data-provider.js +46 -12
  180. package/dist/core/footer-data-provider.js.map +1 -1
  181. package/dist/core/http-dispatcher.d.ts +3 -1
  182. package/dist/core/http-dispatcher.d.ts.map +1 -1
  183. package/dist/core/http-dispatcher.js +4 -1
  184. package/dist/core/http-dispatcher.js.map +1 -1
  185. package/dist/core/keybindings.d.ts +1 -1
  186. package/dist/core/messages.d.ts +1 -1
  187. package/dist/core/messages.d.ts.map +1 -1
  188. package/dist/core/messages.js.map +1 -1
  189. package/dist/core/model-registry-auth.d.ts +1 -1
  190. package/dist/core/model-registry-auth.d.ts.map +1 -1
  191. package/dist/core/model-registry-auth.js.map +1 -1
  192. package/dist/core/model-registry-builtins.d.ts +1 -1
  193. package/dist/core/model-registry-builtins.d.ts.map +1 -1
  194. package/dist/core/model-registry-builtins.js +1 -1
  195. package/dist/core/model-registry-builtins.js.map +1 -1
  196. package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
  197. package/dist/core/model-registry-custom-loader.js +1 -1
  198. package/dist/core/model-registry-custom-loader.js.map +1 -1
  199. package/dist/core/model-registry-dynamic.d.ts +1 -1
  200. package/dist/core/model-registry-dynamic.d.ts.map +1 -1
  201. package/dist/core/model-registry-dynamic.js +1 -1
  202. package/dist/core/model-registry-dynamic.js.map +1 -1
  203. package/dist/core/model-registry-loader.d.ts.map +1 -1
  204. package/dist/core/model-registry-loader.js.map +1 -1
  205. package/dist/core/model-registry-types.d.ts +1 -1
  206. package/dist/core/model-registry-types.d.ts.map +1 -1
  207. package/dist/core/model-registry-types.js.map +1 -1
  208. package/dist/core/model-registry.d.ts +1 -1
  209. package/dist/core/model-registry.d.ts.map +1 -1
  210. package/dist/core/model-registry.js +1 -1
  211. package/dist/core/model-registry.js.map +1 -1
  212. package/dist/core/model-resolver-cli.d.ts.map +1 -1
  213. package/dist/core/model-resolver-cli.js.map +1 -1
  214. package/dist/core/model-resolver-defaults.d.ts +1 -1
  215. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  216. package/dist/core/model-resolver-defaults.js.map +1 -1
  217. package/dist/core/model-resolver-initial.d.ts +1 -1
  218. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  219. package/dist/core/model-resolver-initial.js.map +1 -1
  220. package/dist/core/model-resolver-patterns.d.ts +1 -1
  221. package/dist/core/model-resolver-patterns.d.ts.map +1 -1
  222. package/dist/core/model-resolver-patterns.js.map +1 -1
  223. package/dist/core/model-resolver-scope.d.ts.map +1 -1
  224. package/dist/core/model-resolver-scope.js +1 -1
  225. package/dist/core/model-resolver-scope.js.map +1 -1
  226. package/dist/core/model-resolver-types.d.ts +1 -1
  227. package/dist/core/model-resolver-types.d.ts.map +1 -1
  228. package/dist/core/model-resolver-types.js.map +1 -1
  229. package/dist/core/provider-attribution.d.ts +2 -2
  230. package/dist/core/provider-attribution.d.ts.map +1 -1
  231. package/dist/core/provider-attribution.js +4 -0
  232. package/dist/core/provider-attribution.js.map +1 -1
  233. package/dist/core/sdk-types.d.ts +1 -1
  234. package/dist/core/sdk-types.d.ts.map +1 -1
  235. package/dist/core/sdk-types.js.map +1 -1
  236. package/dist/core/sdk.d.ts +1 -1
  237. package/dist/core/sdk.d.ts.map +1 -1
  238. package/dist/core/sdk.js +2 -2
  239. package/dist/core/sdk.js.map +1 -1
  240. package/dist/core/session-manager-core.d.ts +1 -1
  241. package/dist/core/session-manager-core.d.ts.map +1 -1
  242. package/dist/core/session-manager-core.js.map +1 -1
  243. package/dist/core/session-manager-entries.d.ts +1 -1
  244. package/dist/core/session-manager-entries.d.ts.map +1 -1
  245. package/dist/core/session-manager-entries.js.map +1 -1
  246. package/dist/core/session-manager-list.d.ts.map +1 -1
  247. package/dist/core/session-manager-list.js.map +1 -1
  248. package/dist/core/session-manager-types.d.ts +1 -1
  249. package/dist/core/session-manager-types.d.ts.map +1 -1
  250. package/dist/core/session-manager-types.js.map +1 -1
  251. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  252. package/dist/core/settings-manager-basic-accessors.js +1 -1
  253. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  254. package/dist/core/settings-types.d.ts +1 -1
  255. package/dist/core/settings-types.d.ts.map +1 -1
  256. package/dist/core/settings-types.js.map +1 -1
  257. package/dist/core/tools/oversized-tool-result.d.ts +1 -1
  258. package/dist/core/tools/oversized-tool-result.d.ts.map +1 -1
  259. package/dist/core/tools/oversized-tool-result.js.map +1 -1
  260. package/dist/core/tools/read-url.d.ts +1 -1
  261. package/dist/core/tools/read-url.d.ts.map +1 -1
  262. package/dist/core/tools/read-url.js.map +1 -1
  263. package/dist/core/tools/read.d.ts.map +1 -1
  264. package/dist/core/tools/read.js.map +1 -1
  265. package/dist/core/tools/render-utils.d.ts +1 -1
  266. package/dist/core/tools/render-utils.d.ts.map +1 -1
  267. package/dist/core/tools/render-utils.js.map +1 -1
  268. package/dist/core/tools/todos-types.d.ts.map +1 -1
  269. package/dist/core/tools/todos-types.js +1 -1
  270. package/dist/core/tools/todos-types.js.map +1 -1
  271. package/dist/main-app-mode.d.ts +1 -1
  272. package/dist/main-app-mode.d.ts.map +1 -1
  273. package/dist/main-app-mode.js.map +1 -1
  274. package/dist/main-session-options.d.ts.map +1 -1
  275. package/dist/main-session-options.js +1 -1
  276. package/dist/main-session-options.js.map +1 -1
  277. package/dist/modes/interactive/components/assistant-message.d.ts +1 -1
  278. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  279. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  280. package/dist/modes/interactive/components/chat-message-renderer.d.ts +1 -1
  281. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  282. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  283. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  284. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  285. package/dist/modes/interactive/components/model-selector.d.ts +1 -1
  286. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  287. package/dist/modes/interactive/components/model-selector.js +1 -1
  288. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  289. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
  290. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  291. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  292. package/dist/modes/interactive/components/settings-selector-handlers.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/settings-selector-handlers.js +2 -2
  294. package/dist/modes/interactive/components/settings-selector-handlers.js.map +1 -1
  295. package/dist/modes/interactive/components/settings-selector-types.d.ts +1 -1
  296. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  297. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  298. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  299. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  300. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  301. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  302. package/dist/modes/print-mode.d.ts +1 -1
  303. package/dist/modes/print-mode.d.ts.map +1 -1
  304. package/dist/modes/print-mode.js.map +1 -1
  305. package/dist/modes/rpc/rpc-client.d.ts +1 -1
  306. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  307. package/dist/modes/rpc/rpc-client.js.map +1 -1
  308. package/dist/modes/rpc/rpc-types.d.ts +1 -1
  309. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  310. package/dist/modes/rpc/rpc-types.js.map +1 -1
  311. package/docs/changelog.mdx +15 -0
  312. package/docs/custom-provider.md +2 -1
  313. package/docs/sdk.md +2 -2
  314. package/docs/settings.md +7 -7
  315. package/examples/extensions/custom-footer.ts +1 -1
  316. package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
  317. package/examples/extensions/custom-provider-gitlab-duo/index.ts +1 -1
  318. package/examples/extensions/custom-provider-gitlab-duo/test.ts +1 -1
  319. package/examples/extensions/handoff.ts +1 -1
  320. package/examples/extensions/hello.ts +1 -1
  321. package/examples/extensions/plan-mode/index.ts +1 -1
  322. package/examples/extensions/preset.ts +1 -1
  323. package/examples/extensions/qna.ts +1 -1
  324. package/examples/extensions/subagent/display.ts +1 -1
  325. package/examples/extensions/subagent/runner.ts +1 -1
  326. package/examples/extensions/subagent/schemas.ts +1 -1
  327. package/examples/extensions/subagent/types.ts +1 -1
  328. package/examples/extensions/summarize.ts +1 -1
  329. package/examples/extensions/tic-tac-toe.ts +1 -1
  330. package/examples/extensions/todo.ts +1 -1
  331. package/examples/extensions/tool-override.ts +1 -1
  332. package/examples/sdk/02-custom-model.ts +1 -1
  333. package/examples/sdk/12-full-control.ts +1 -1
  334. package/examples/sdk/README.md +1 -1
  335. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-gemini-tool-arguments.d.ts","sourceRoot":"","sources":["../../src/core/copilot-gemini-tool-arguments.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAkFxD;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAMrF;AAED;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,OAAO,EACb,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,IAAI,CAAC,GAAG,SAAS,EAC9D,MAAM,CAAC,EAAE,OAAO,GACf,OAAO,CAGT;AAoBD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,yCAAyC,CACvD,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,IAAI,CAAC,GACjD,OAAO,CA2CT","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { unflattenArgumentsWithSchema } from \"./flattened-tool-arguments.ts\";\n\n/**\n * Normalizes GitHub Copilot Gemini tool-call arguments.\n *\n * Why this exists\n * ---------------\n * `github-copilot` Gemini models are served through Copilot's CAPI gateway,\n * which proxies to Google's GenAI API. When a function/tool argument is an\n * array (or a nested object/array), Gemini serializes it on the wire as\n * **flattened, indexed keys** instead of a real JSON array/object. For example\n * a tool called with `{ keywords: [\"a\", \"b\"] }` arrives as:\n *\n * ```json\n * { \"keywords[0]\": \"a\", \"keywords[1]\": \"b\" }\n * ```\n *\n * This was confirmed by capturing the raw CAPI SSE stream: the\n * `tool_calls[].function.arguments` JSON itself contains the `name[index]`\n * keys, so the runtime parses valid-but-wrong JSON. Schema validation then\n * fails (`keywords: must have required properties keywords` and\n * `root: must not have additional properties`) and the model retries forever,\n * because it keeps re-emitting the same flattened shape. This is most visible\n * with the workflow `structured_output` tool but affects any Gemini tool call\n * whose schema contains an array or nested object.\n *\n * What it does\n * ------------\n * Reconstructs flattened keys (`name[i]`, `name[i].sub`, `parent.child`) back\n * into the intended nested arrays/objects, before tool-argument validation\n * runs. Bracket-indexed keys (`name[<digit>]`) are always reconstructed. A\n * purely dotted key (`parent.child`, with no array anywhere) is ambiguous —\n * a legitimate argument key can itself contain a dot — so it is only split when\n * the optional tool `schema` marks its head segment as an object/array\n * container property. When Gemini omits a required empty array entirely (there\n * are no `name[0]` keys to send), the schema is also used to synthesize `[]` for\n * missing required top-level array properties so normal validation can proceed.\n * The transform is gated to GitHub Copilot Gemini models, so it never touches\n * well-formed arguments from any other provider/model.\n */\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction schemaTypeIncludes(schema: JsonRecord, type: string): boolean {\n if (schema.type === type) return true;\n return Array.isArray(schema.type) && schema.type.includes(type);\n}\n\nfunction isArraySchema(schema: unknown): boolean {\n if (!isPlainObject(schema)) return false;\n if (schemaTypeIncludes(schema, \"array\")) return true;\n if (\"items\" in schema && !schemaTypeIncludes(schema, \"object\")) return true;\n const union = schema.anyOf ?? schema.oneOf;\n return Array.isArray(union) && union.some((branch) => isArraySchema(branch));\n}\n\nfunction requiredArrayPropertyNames(schema: unknown): readonly string[] {\n if (!isPlainObject(schema)) return [];\n const required = schema.required;\n const properties = schema.properties;\n if (!Array.isArray(required) || !isPlainObject(properties)) return [];\n return required.filter((name): name is string => (\n typeof name === \"string\" &&\n Object.hasOwn(properties, name) &&\n isArraySchema(properties[name])\n ));\n}\n\nfunction fillMissingRequiredArrayProperties(args: JsonRecord, schema: unknown): JsonRecord {\n const missing = requiredArrayPropertyNames(schema).filter((name) => !Object.hasOwn(args, name));\n if (missing.length === 0) return args;\n const next: JsonRecord = { ...args };\n for (const name of missing) next[name] = [];\n return next;\n}\n\n/**\n * Reconstruct flattened Gemini tool-call arguments into proper nested\n * arrays/objects. Returns the original reference unchanged when there is nothing\n * to reconstruct. Bracket-indexed keys are always reconstructed; purely dotted\n * keys are reconstructed only when the optional `schema` marks their head\n * segment as an object/array container property. Reconstruction (and its\n * prototype-pollution guard) is delegated to the shared canonical helper.\n */\nexport function unflattenGeminiToolArguments(args: unknown, schema?: unknown): unknown {\n if (!isPlainObject(args)) return args;\n const reconstructed = unflattenArgumentsWithSchema(args, schema);\n return isPlainObject(reconstructed)\n ? fillMissingRequiredArrayProperties(reconstructed, schema)\n : reconstructed;\n}\n\n/**\n * If `model` is a GitHub Copilot Gemini model, normalize flattened tool-call\n * arguments; otherwise return them unchanged. Used to gate\n * {@link unflattenGeminiToolArguments} by model at tool-call time. The optional\n * `schema` is the tool's parameter schema, used to disambiguate dotted keys.\n */\nexport function normalizeToolArgumentsForModel(\n args: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\"> | undefined,\n schema?: unknown,\n): unknown {\n if (!model || !isCopilotGeminiModel(model)) return args;\n return unflattenGeminiToolArguments(args, schema);\n}\n\n/** Map each tool name in an OpenAI chat-completions payload to its parameter schema. */\nfunction toolParameterSchemas(tools: unknown): Map<string, unknown> {\n const schemas = new Map<string, unknown>();\n if (!Array.isArray(tools)) return schemas;\n for (const tool of tools) {\n if (!isPlainObject(tool)) continue;\n // OpenAI chat-completions tool shape: { type: \"function\", function: { name, parameters } }.\n const fn = tool.function;\n if (isPlainObject(fn) && typeof fn.name === \"string\") {\n schemas.set(fn.name, fn.parameters);\n continue;\n }\n // Defensive: flat tool shape { name, parameters }.\n if (typeof tool.name === \"string\") schemas.set(tool.name, tool.parameters);\n }\n return schemas;\n}\n\n/**\n * Reconstruct flattened GitHub Copilot Gemini tool-call arguments on the\n * **outbound replay payload**, so prior assistant tool calls are sent back to\n * CAPI in the nested array/object shape Gemini originally produced.\n *\n * Why this exists\n * ---------------\n * {@link normalizeToolArgumentsForModel} only unflattens at tool *execution*\n * time; the persisted assistant message keeps the raw flattened arguments CAPI\n * delivered (for example `{ \"edits[0].newText\": \"...\" }`). When that message is\n * replayed on the next turn, CAPI parses those literal keys straight into the\n * Gemini `FunctionCall.Args`, producing a function call that does not match the\n * tool's declared schema (nor the structure Gemini signed). Gemini then ends\n * the turn with `MALFORMED_FUNCTION_CALL` / `UNEXPECTED_TOOL_CALL` / `OTHER`,\n * which CAPI surfaces as a bare `finish_reason: \"error\"` — so multi-turn tool\n * use dies one turn after any array/object tool call (such as `edit`).\n *\n * This rewrites each replayed assistant `tool_calls[].function.arguments` JSON\n * into the reconstructed nested shape (reusing {@link unflattenGeminiToolArguments}\n * with the tool's own parameter schema, looked up from the payload's `tools`),\n * fixing both new and already-persisted sessions. Gated to GitHub Copilot Gemini\n * models, fail-open on non-JSON arguments, and a no-op for well-formed args.\n */\nexport function normalizeCopilotGeminiReplayToolArguments(\n payload: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\">,\n): unknown {\n if (!isCopilotGeminiModel(model)) return payload;\n if (!isPlainObject(payload)) return payload;\n const messages = payload.messages;\n if (!Array.isArray(messages)) return payload;\n\n const schemas = toolParameterSchemas(payload.tools);\n let mutated = false;\n\n const nextMessages = messages.map((message) => {\n if (!isPlainObject(message) || message.role !== \"assistant\") return message;\n const toolCalls = message.tool_calls;\n if (!Array.isArray(toolCalls) || toolCalls.length === 0) return message;\n\n let messageMutated = false;\n const nextToolCalls = toolCalls.map((toolCall) => {\n if (!isPlainObject(toolCall)) return toolCall;\n const fn = toolCall.function;\n if (!isPlainObject(fn) || typeof fn.arguments !== \"string\") return toolCall;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fn.arguments);\n } catch {\n return toolCall; // fail open: never corrupt a replayed argument string\n }\n if (!isPlainObject(parsed)) return toolCall;\n\n const schema = typeof fn.name === \"string\" ? schemas.get(fn.name) : undefined;\n const reconstructed = unflattenGeminiToolArguments(parsed, schema);\n if (reconstructed === parsed) return toolCall;\n\n messageMutated = true;\n return { ...toolCall, function: { ...fn, arguments: JSON.stringify(reconstructed) } };\n });\n\n if (!messageMutated) return message;\n mutated = true;\n return { ...message, tool_calls: nextToolCalls };\n });\n\n if (!mutated) return payload;\n return { ...payload, messages: nextMessages };\n}\n"]}
1
+ {"version":3,"file":"copilot-gemini-tool-arguments.d.ts","sourceRoot":"","sources":["../../src/core/copilot-gemini-tool-arguments.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAkF/D;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAMrF;AAED;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,OAAO,EACb,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,IAAI,CAAC,GAAG,SAAS,EAC9D,MAAM,CAAC,EAAE,OAAO,GACf,OAAO,CAGT;AAoBD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,yCAAyC,CACvD,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,UAAU,GAAG,KAAK,GAAG,IAAI,CAAC,GACjD,OAAO,CA2CT","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { unflattenArgumentsWithSchema } from \"./flattened-tool-arguments.ts\";\n\n/**\n * Normalizes GitHub Copilot Gemini tool-call arguments.\n *\n * Why this exists\n * ---------------\n * `github-copilot` Gemini models are served through Copilot's CAPI gateway,\n * which proxies to Google's GenAI API. When a function/tool argument is an\n * array (or a nested object/array), Gemini serializes it on the wire as\n * **flattened, indexed keys** instead of a real JSON array/object. For example\n * a tool called with `{ keywords: [\"a\", \"b\"] }` arrives as:\n *\n * ```json\n * { \"keywords[0]\": \"a\", \"keywords[1]\": \"b\" }\n * ```\n *\n * This was confirmed by capturing the raw CAPI SSE stream: the\n * `tool_calls[].function.arguments` JSON itself contains the `name[index]`\n * keys, so the runtime parses valid-but-wrong JSON. Schema validation then\n * fails (`keywords: must have required properties keywords` and\n * `root: must not have additional properties`) and the model retries forever,\n * because it keeps re-emitting the same flattened shape. This is most visible\n * with the workflow `structured_output` tool but affects any Gemini tool call\n * whose schema contains an array or nested object.\n *\n * What it does\n * ------------\n * Reconstructs flattened keys (`name[i]`, `name[i].sub`, `parent.child`) back\n * into the intended nested arrays/objects, before tool-argument validation\n * runs. Bracket-indexed keys (`name[<digit>]`) are always reconstructed. A\n * purely dotted key (`parent.child`, with no array anywhere) is ambiguous —\n * a legitimate argument key can itself contain a dot — so it is only split when\n * the optional tool `schema` marks its head segment as an object/array\n * container property. When Gemini omits a required empty array entirely (there\n * are no `name[0]` keys to send), the schema is also used to synthesize `[]` for\n * missing required top-level array properties so normal validation can proceed.\n * The transform is gated to GitHub Copilot Gemini models, so it never touches\n * well-formed arguments from any other provider/model.\n */\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction schemaTypeIncludes(schema: JsonRecord, type: string): boolean {\n if (schema.type === type) return true;\n return Array.isArray(schema.type) && schema.type.includes(type);\n}\n\nfunction isArraySchema(schema: unknown): boolean {\n if (!isPlainObject(schema)) return false;\n if (schemaTypeIncludes(schema, \"array\")) return true;\n if (\"items\" in schema && !schemaTypeIncludes(schema, \"object\")) return true;\n const union = schema.anyOf ?? schema.oneOf;\n return Array.isArray(union) && union.some((branch) => isArraySchema(branch));\n}\n\nfunction requiredArrayPropertyNames(schema: unknown): readonly string[] {\n if (!isPlainObject(schema)) return [];\n const required = schema.required;\n const properties = schema.properties;\n if (!Array.isArray(required) || !isPlainObject(properties)) return [];\n return required.filter((name): name is string => (\n typeof name === \"string\" &&\n Object.hasOwn(properties, name) &&\n isArraySchema(properties[name])\n ));\n}\n\nfunction fillMissingRequiredArrayProperties(args: JsonRecord, schema: unknown): JsonRecord {\n const missing = requiredArrayPropertyNames(schema).filter((name) => !Object.hasOwn(args, name));\n if (missing.length === 0) return args;\n const next: JsonRecord = { ...args };\n for (const name of missing) next[name] = [];\n return next;\n}\n\n/**\n * Reconstruct flattened Gemini tool-call arguments into proper nested\n * arrays/objects. Returns the original reference unchanged when there is nothing\n * to reconstruct. Bracket-indexed keys are always reconstructed; purely dotted\n * keys are reconstructed only when the optional `schema` marks their head\n * segment as an object/array container property. Reconstruction (and its\n * prototype-pollution guard) is delegated to the shared canonical helper.\n */\nexport function unflattenGeminiToolArguments(args: unknown, schema?: unknown): unknown {\n if (!isPlainObject(args)) return args;\n const reconstructed = unflattenArgumentsWithSchema(args, schema);\n return isPlainObject(reconstructed)\n ? fillMissingRequiredArrayProperties(reconstructed, schema)\n : reconstructed;\n}\n\n/**\n * If `model` is a GitHub Copilot Gemini model, normalize flattened tool-call\n * arguments; otherwise return them unchanged. Used to gate\n * {@link unflattenGeminiToolArguments} by model at tool-call time. The optional\n * `schema` is the tool's parameter schema, used to disambiguate dotted keys.\n */\nexport function normalizeToolArgumentsForModel(\n args: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\"> | undefined,\n schema?: unknown,\n): unknown {\n if (!model || !isCopilotGeminiModel(model)) return args;\n return unflattenGeminiToolArguments(args, schema);\n}\n\n/** Map each tool name in an OpenAI chat-completions payload to its parameter schema. */\nfunction toolParameterSchemas(tools: unknown): Map<string, unknown> {\n const schemas = new Map<string, unknown>();\n if (!Array.isArray(tools)) return schemas;\n for (const tool of tools) {\n if (!isPlainObject(tool)) continue;\n // OpenAI chat-completions tool shape: { type: \"function\", function: { name, parameters } }.\n const fn = tool.function;\n if (isPlainObject(fn) && typeof fn.name === \"string\") {\n schemas.set(fn.name, fn.parameters);\n continue;\n }\n // Defensive: flat tool shape { name, parameters }.\n if (typeof tool.name === \"string\") schemas.set(tool.name, tool.parameters);\n }\n return schemas;\n}\n\n/**\n * Reconstruct flattened GitHub Copilot Gemini tool-call arguments on the\n * **outbound replay payload**, so prior assistant tool calls are sent back to\n * CAPI in the nested array/object shape Gemini originally produced.\n *\n * Why this exists\n * ---------------\n * {@link normalizeToolArgumentsForModel} only unflattens at tool *execution*\n * time; the persisted assistant message keeps the raw flattened arguments CAPI\n * delivered (for example `{ \"edits[0].newText\": \"...\" }`). When that message is\n * replayed on the next turn, CAPI parses those literal keys straight into the\n * Gemini `FunctionCall.Args`, producing a function call that does not match the\n * tool's declared schema (nor the structure Gemini signed). Gemini then ends\n * the turn with `MALFORMED_FUNCTION_CALL` / `UNEXPECTED_TOOL_CALL` / `OTHER`,\n * which CAPI surfaces as a bare `finish_reason: \"error\"` — so multi-turn tool\n * use dies one turn after any array/object tool call (such as `edit`).\n *\n * This rewrites each replayed assistant `tool_calls[].function.arguments` JSON\n * into the reconstructed nested shape (reusing {@link unflattenGeminiToolArguments}\n * with the tool's own parameter schema, looked up from the payload's `tools`),\n * fixing both new and already-persisted sessions. Gated to GitHub Copilot Gemini\n * models, fail-open on non-JSON arguments, and a no-op for well-formed args.\n */\nexport function normalizeCopilotGeminiReplayToolArguments(\n payload: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\">,\n): unknown {\n if (!isCopilotGeminiModel(model)) return payload;\n if (!isPlainObject(payload)) return payload;\n const messages = payload.messages;\n if (!Array.isArray(messages)) return payload;\n\n const schemas = toolParameterSchemas(payload.tools);\n let mutated = false;\n\n const nextMessages = messages.map((message) => {\n if (!isPlainObject(message) || message.role !== \"assistant\") return message;\n const toolCalls = message.tool_calls;\n if (!Array.isArray(toolCalls) || toolCalls.length === 0) return message;\n\n let messageMutated = false;\n const nextToolCalls = toolCalls.map((toolCall) => {\n if (!isPlainObject(toolCall)) return toolCall;\n const fn = toolCall.function;\n if (!isPlainObject(fn) || typeof fn.arguments !== \"string\") return toolCall;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fn.arguments);\n } catch {\n return toolCall; // fail open: never corrupt a replayed argument string\n }\n if (!isPlainObject(parsed)) return toolCall;\n\n const schema = typeof fn.name === \"string\" ? schemas.get(fn.name) : undefined;\n const reconstructed = unflattenGeminiToolArguments(parsed, schema);\n if (reconstructed === parsed) return toolCall;\n\n messageMutated = true;\n return { ...toolCall, function: { ...fn, arguments: JSON.stringify(reconstructed) } };\n });\n\n if (!messageMutated) return message;\n mutated = true;\n return { ...message, tool_calls: nextToolCalls };\n });\n\n if (!mutated) return payload;\n return { ...payload, messages: nextMessages };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-gemini-tool-arguments.js","sourceRoot":"","sources":["../../src/core/copilot-gemini-tool-arguments.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AA2C7E,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAkB,EAAE,IAAY;IAC1D,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IACtC,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,aAAa,CAAC,MAAe;IACpC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IACzC,IAAI,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IACrD,IAAI,OAAO,IAAI,MAAM,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,QAAQ,CAAC;QAAE,OAAO,IAAI,CAAC;IAC5E,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,CAAC;IAC3C,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,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AC,aAAa,CAAC,MAAM,CAAC;gBAAE,OAAO,QAAQ,CAAC;YAE5C,MAAM,MAAM,GAAG,OAAO,EAAE,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAC9E,MAAM,aAAa,GAAG,4BAA4B,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YACnE,IAAI,aAAa,KAAK,MAAM;gBAAE,OAAO,QAAQ,CAAC;YAE9C,cAAc,GAAG,IAAI,CAAC;YACtB,OAAO,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC;QACxF,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,cAAc;YAAE,OAAO,OAAO,CAAC;QACpC,OAAO,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC;IACnD,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC;IAC7B,OAAO,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { unflattenArgumentsWithSchema } from \"./flattened-tool-arguments.ts\";\n\n/**\n * Normalizes GitHub Copilot Gemini tool-call arguments.\n *\n * Why this exists\n * ---------------\n * `github-copilot` Gemini models are served through Copilot's CAPI gateway,\n * which proxies to Google's GenAI API. When a function/tool argument is an\n * array (or a nested object/array), Gemini serializes it on the wire as\n * **flattened, indexed keys** instead of a real JSON array/object. For example\n * a tool called with `{ keywords: [\"a\", \"b\"] }` arrives as:\n *\n * ```json\n * { \"keywords[0]\": \"a\", \"keywords[1]\": \"b\" }\n * ```\n *\n * This was confirmed by capturing the raw CAPI SSE stream: the\n * `tool_calls[].function.arguments` JSON itself contains the `name[index]`\n * keys, so the runtime parses valid-but-wrong JSON. Schema validation then\n * fails (`keywords: must have required properties keywords` and\n * `root: must not have additional properties`) and the model retries forever,\n * because it keeps re-emitting the same flattened shape. This is most visible\n * with the workflow `structured_output` tool but affects any Gemini tool call\n * whose schema contains an array or nested object.\n *\n * What it does\n * ------------\n * Reconstructs flattened keys (`name[i]`, `name[i].sub`, `parent.child`) back\n * into the intended nested arrays/objects, before tool-argument validation\n * runs. Bracket-indexed keys (`name[<digit>]`) are always reconstructed. A\n * purely dotted key (`parent.child`, with no array anywhere) is ambiguous —\n * a legitimate argument key can itself contain a dot — so it is only split when\n * the optional tool `schema` marks its head segment as an object/array\n * container property. When Gemini omits a required empty array entirely (there\n * are no `name[0]` keys to send), the schema is also used to synthesize `[]` for\n * missing required top-level array properties so normal validation can proceed.\n * The transform is gated to GitHub Copilot Gemini models, so it never touches\n * well-formed arguments from any other provider/model.\n */\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction schemaTypeIncludes(schema: JsonRecord, type: string): boolean {\n if (schema.type === type) return true;\n return Array.isArray(schema.type) && schema.type.includes(type);\n}\n\nfunction isArraySchema(schema: unknown): boolean {\n if (!isPlainObject(schema)) return false;\n if (schemaTypeIncludes(schema, \"array\")) return true;\n if (\"items\" in schema && !schemaTypeIncludes(schema, \"object\")) return true;\n const union = schema.anyOf ?? schema.oneOf;\n return Array.isArray(union) && union.some((branch) => isArraySchema(branch));\n}\n\nfunction requiredArrayPropertyNames(schema: unknown): readonly string[] {\n if (!isPlainObject(schema)) return [];\n const required = schema.required;\n const properties = schema.properties;\n if (!Array.isArray(required) || !isPlainObject(properties)) return [];\n return required.filter((name): name is string => (\n typeof name === \"string\" &&\n Object.hasOwn(properties, name) &&\n isArraySchema(properties[name])\n ));\n}\n\nfunction fillMissingRequiredArrayProperties(args: JsonRecord, schema: unknown): JsonRecord {\n const missing = requiredArrayPropertyNames(schema).filter((name) => !Object.hasOwn(args, name));\n if (missing.length === 0) return args;\n const next: JsonRecord = { ...args };\n for (const name of missing) next[name] = [];\n return next;\n}\n\n/**\n * Reconstruct flattened Gemini tool-call arguments into proper nested\n * arrays/objects. Returns the original reference unchanged when there is nothing\n * to reconstruct. Bracket-indexed keys are always reconstructed; purely dotted\n * keys are reconstructed only when the optional `schema` marks their head\n * segment as an object/array container property. Reconstruction (and its\n * prototype-pollution guard) is delegated to the shared canonical helper.\n */\nexport function unflattenGeminiToolArguments(args: unknown, schema?: unknown): unknown {\n if (!isPlainObject(args)) return args;\n const reconstructed = unflattenArgumentsWithSchema(args, schema);\n return isPlainObject(reconstructed)\n ? fillMissingRequiredArrayProperties(reconstructed, schema)\n : reconstructed;\n}\n\n/**\n * If `model` is a GitHub Copilot Gemini model, normalize flattened tool-call\n * arguments; otherwise return them unchanged. Used to gate\n * {@link unflattenGeminiToolArguments} by model at tool-call time. The optional\n * `schema` is the tool's parameter schema, used to disambiguate dotted keys.\n */\nexport function normalizeToolArgumentsForModel(\n args: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\"> | undefined,\n schema?: unknown,\n): unknown {\n if (!model || !isCopilotGeminiModel(model)) return args;\n return unflattenGeminiToolArguments(args, schema);\n}\n\n/** Map each tool name in an OpenAI chat-completions payload to its parameter schema. */\nfunction toolParameterSchemas(tools: unknown): Map<string, unknown> {\n const schemas = new Map<string, unknown>();\n if (!Array.isArray(tools)) return schemas;\n for (const tool of tools) {\n if (!isPlainObject(tool)) continue;\n // OpenAI chat-completions tool shape: { type: \"function\", function: { name, parameters } }.\n const fn = tool.function;\n if (isPlainObject(fn) && typeof fn.name === \"string\") {\n schemas.set(fn.name, fn.parameters);\n continue;\n }\n // Defensive: flat tool shape { name, parameters }.\n if (typeof tool.name === \"string\") schemas.set(tool.name, tool.parameters);\n }\n return schemas;\n}\n\n/**\n * Reconstruct flattened GitHub Copilot Gemini tool-call arguments on the\n * **outbound replay payload**, so prior assistant tool calls are sent back to\n * CAPI in the nested array/object shape Gemini originally produced.\n *\n * Why this exists\n * ---------------\n * {@link normalizeToolArgumentsForModel} only unflattens at tool *execution*\n * time; the persisted assistant message keeps the raw flattened arguments CAPI\n * delivered (for example `{ \"edits[0].newText\": \"...\" }`). When that message is\n * replayed on the next turn, CAPI parses those literal keys straight into the\n * Gemini `FunctionCall.Args`, producing a function call that does not match the\n * tool's declared schema (nor the structure Gemini signed). Gemini then ends\n * the turn with `MALFORMED_FUNCTION_CALL` / `UNEXPECTED_TOOL_CALL` / `OTHER`,\n * which CAPI surfaces as a bare `finish_reason: \"error\"` — so multi-turn tool\n * use dies one turn after any array/object tool call (such as `edit`).\n *\n * This rewrites each replayed assistant `tool_calls[].function.arguments` JSON\n * into the reconstructed nested shape (reusing {@link unflattenGeminiToolArguments}\n * with the tool's own parameter schema, looked up from the payload's `tools`),\n * fixing both new and already-persisted sessions. Gated to GitHub Copilot Gemini\n * models, fail-open on non-JSON arguments, and a no-op for well-formed args.\n */\nexport function normalizeCopilotGeminiReplayToolArguments(\n payload: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\">,\n): unknown {\n if (!isCopilotGeminiModel(model)) return payload;\n if (!isPlainObject(payload)) return payload;\n const messages = payload.messages;\n if (!Array.isArray(messages)) return payload;\n\n const schemas = toolParameterSchemas(payload.tools);\n let mutated = false;\n\n const nextMessages = messages.map((message) => {\n if (!isPlainObject(message) || message.role !== \"assistant\") return message;\n const toolCalls = message.tool_calls;\n if (!Array.isArray(toolCalls) || toolCalls.length === 0) return message;\n\n let messageMutated = false;\n const nextToolCalls = toolCalls.map((toolCall) => {\n if (!isPlainObject(toolCall)) return toolCall;\n const fn = toolCall.function;\n if (!isPlainObject(fn) || typeof fn.arguments !== \"string\") return toolCall;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fn.arguments);\n } catch {\n return toolCall; // fail open: never corrupt a replayed argument string\n }\n if (!isPlainObject(parsed)) return toolCall;\n\n const schema = typeof fn.name === \"string\" ? schemas.get(fn.name) : undefined;\n const reconstructed = unflattenGeminiToolArguments(parsed, schema);\n if (reconstructed === parsed) return toolCall;\n\n messageMutated = true;\n return { ...toolCall, function: { ...fn, arguments: JSON.stringify(reconstructed) } };\n });\n\n if (!messageMutated) return message;\n mutated = true;\n return { ...message, tool_calls: nextToolCalls };\n });\n\n if (!mutated) return payload;\n return { ...payload, messages: nextMessages };\n}\n"]}
1
+ {"version":3,"file":"copilot-gemini-tool-arguments.js","sourceRoot":"","sources":["../../src/core/copilot-gemini-tool-arguments.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AA2C7E,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAkB,EAAE,IAAY;IAC1D,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IACtC,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,aAAa,CAAC,MAAe;IACpC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IACzC,IAAI,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IACrD,IAAI,OAAO,IAAI,MAAM,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,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QAAQ;gBAAE,OAAO,QAAQ,CAAC;YAE5E,IAAI,MAAe,CAAC;YACpB,IAAI,CAAC;gBACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC;YACpC,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,QAAQ,CAAC,CAAC,sDAAsD;YACzE,CAAC;YACD,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;gBAAE,OAAO,QAAQ,CAAC;YAE5C,MAAM,MAAM,GAAG,OAAO,EAAE,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAC9E,MAAM,aAAa,GAAG,4BAA4B,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YACnE,IAAI,aAAa,KAAK,MAAM;gBAAE,OAAO,QAAQ,CAAC;YAE9C,cAAc,GAAG,IAAI,CAAC;YACtB,OAAO,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,EAAE,EAAE,CAAC;QACxF,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,cAAc;YAAE,OAAO,OAAO,CAAC;QACpC,OAAO,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC;IACnD,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC;IAC7B,OAAO,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;AAChD,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { isCopilotGeminiModel } from \"./copilot-gemini-payload-sanitizer.ts\";\nimport { unflattenArgumentsWithSchema } from \"./flattened-tool-arguments.ts\";\n\n/**\n * Normalizes GitHub Copilot Gemini tool-call arguments.\n *\n * Why this exists\n * ---------------\n * `github-copilot` Gemini models are served through Copilot's CAPI gateway,\n * which proxies to Google's GenAI API. When a function/tool argument is an\n * array (or a nested object/array), Gemini serializes it on the wire as\n * **flattened, indexed keys** instead of a real JSON array/object. For example\n * a tool called with `{ keywords: [\"a\", \"b\"] }` arrives as:\n *\n * ```json\n * { \"keywords[0]\": \"a\", \"keywords[1]\": \"b\" }\n * ```\n *\n * This was confirmed by capturing the raw CAPI SSE stream: the\n * `tool_calls[].function.arguments` JSON itself contains the `name[index]`\n * keys, so the runtime parses valid-but-wrong JSON. Schema validation then\n * fails (`keywords: must have required properties keywords` and\n * `root: must not have additional properties`) and the model retries forever,\n * because it keeps re-emitting the same flattened shape. This is most visible\n * with the workflow `structured_output` tool but affects any Gemini tool call\n * whose schema contains an array or nested object.\n *\n * What it does\n * ------------\n * Reconstructs flattened keys (`name[i]`, `name[i].sub`, `parent.child`) back\n * into the intended nested arrays/objects, before tool-argument validation\n * runs. Bracket-indexed keys (`name[<digit>]`) are always reconstructed. A\n * purely dotted key (`parent.child`, with no array anywhere) is ambiguous —\n * a legitimate argument key can itself contain a dot — so it is only split when\n * the optional tool `schema` marks its head segment as an object/array\n * container property. When Gemini omits a required empty array entirely (there\n * are no `name[0]` keys to send), the schema is also used to synthesize `[]` for\n * missing required top-level array properties so normal validation can proceed.\n * The transform is gated to GitHub Copilot Gemini models, so it never touches\n * well-formed arguments from any other provider/model.\n */\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction schemaTypeIncludes(schema: JsonRecord, type: string): boolean {\n if (schema.type === type) return true;\n return Array.isArray(schema.type) && schema.type.includes(type);\n}\n\nfunction isArraySchema(schema: unknown): boolean {\n if (!isPlainObject(schema)) return false;\n if (schemaTypeIncludes(schema, \"array\")) return true;\n if (\"items\" in schema && !schemaTypeIncludes(schema, \"object\")) return true;\n const union = schema.anyOf ?? schema.oneOf;\n return Array.isArray(union) && union.some((branch) => isArraySchema(branch));\n}\n\nfunction requiredArrayPropertyNames(schema: unknown): readonly string[] {\n if (!isPlainObject(schema)) return [];\n const required = schema.required;\n const properties = schema.properties;\n if (!Array.isArray(required) || !isPlainObject(properties)) return [];\n return required.filter((name): name is string => (\n typeof name === \"string\" &&\n Object.hasOwn(properties, name) &&\n isArraySchema(properties[name])\n ));\n}\n\nfunction fillMissingRequiredArrayProperties(args: JsonRecord, schema: unknown): JsonRecord {\n const missing = requiredArrayPropertyNames(schema).filter((name) => !Object.hasOwn(args, name));\n if (missing.length === 0) return args;\n const next: JsonRecord = { ...args };\n for (const name of missing) next[name] = [];\n return next;\n}\n\n/**\n * Reconstruct flattened Gemini tool-call arguments into proper nested\n * arrays/objects. Returns the original reference unchanged when there is nothing\n * to reconstruct. Bracket-indexed keys are always reconstructed; purely dotted\n * keys are reconstructed only when the optional `schema` marks their head\n * segment as an object/array container property. Reconstruction (and its\n * prototype-pollution guard) is delegated to the shared canonical helper.\n */\nexport function unflattenGeminiToolArguments(args: unknown, schema?: unknown): unknown {\n if (!isPlainObject(args)) return args;\n const reconstructed = unflattenArgumentsWithSchema(args, schema);\n return isPlainObject(reconstructed)\n ? fillMissingRequiredArrayProperties(reconstructed, schema)\n : reconstructed;\n}\n\n/**\n * If `model` is a GitHub Copilot Gemini model, normalize flattened tool-call\n * arguments; otherwise return them unchanged. Used to gate\n * {@link unflattenGeminiToolArguments} by model at tool-call time. The optional\n * `schema` is the tool's parameter schema, used to disambiguate dotted keys.\n */\nexport function normalizeToolArgumentsForModel(\n args: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\"> | undefined,\n schema?: unknown,\n): unknown {\n if (!model || !isCopilotGeminiModel(model)) return args;\n return unflattenGeminiToolArguments(args, schema);\n}\n\n/** Map each tool name in an OpenAI chat-completions payload to its parameter schema. */\nfunction toolParameterSchemas(tools: unknown): Map<string, unknown> {\n const schemas = new Map<string, unknown>();\n if (!Array.isArray(tools)) return schemas;\n for (const tool of tools) {\n if (!isPlainObject(tool)) continue;\n // OpenAI chat-completions tool shape: { type: \"function\", function: { name, parameters } }.\n const fn = tool.function;\n if (isPlainObject(fn) && typeof fn.name === \"string\") {\n schemas.set(fn.name, fn.parameters);\n continue;\n }\n // Defensive: flat tool shape { name, parameters }.\n if (typeof tool.name === \"string\") schemas.set(tool.name, tool.parameters);\n }\n return schemas;\n}\n\n/**\n * Reconstruct flattened GitHub Copilot Gemini tool-call arguments on the\n * **outbound replay payload**, so prior assistant tool calls are sent back to\n * CAPI in the nested array/object shape Gemini originally produced.\n *\n * Why this exists\n * ---------------\n * {@link normalizeToolArgumentsForModel} only unflattens at tool *execution*\n * time; the persisted assistant message keeps the raw flattened arguments CAPI\n * delivered (for example `{ \"edits[0].newText\": \"...\" }`). When that message is\n * replayed on the next turn, CAPI parses those literal keys straight into the\n * Gemini `FunctionCall.Args`, producing a function call that does not match the\n * tool's declared schema (nor the structure Gemini signed). Gemini then ends\n * the turn with `MALFORMED_FUNCTION_CALL` / `UNEXPECTED_TOOL_CALL` / `OTHER`,\n * which CAPI surfaces as a bare `finish_reason: \"error\"` — so multi-turn tool\n * use dies one turn after any array/object tool call (such as `edit`).\n *\n * This rewrites each replayed assistant `tool_calls[].function.arguments` JSON\n * into the reconstructed nested shape (reusing {@link unflattenGeminiToolArguments}\n * with the tool's own parameter schema, looked up from the payload's `tools`),\n * fixing both new and already-persisted sessions. Gated to GitHub Copilot Gemini\n * models, fail-open on non-JSON arguments, and a no-op for well-formed args.\n */\nexport function normalizeCopilotGeminiReplayToolArguments(\n payload: unknown,\n model: Pick<Model<Api>, \"provider\" | \"api\" | \"id\">,\n): unknown {\n if (!isCopilotGeminiModel(model)) return payload;\n if (!isPlainObject(payload)) return payload;\n const messages = payload.messages;\n if (!Array.isArray(messages)) return payload;\n\n const schemas = toolParameterSchemas(payload.tools);\n let mutated = false;\n\n const nextMessages = messages.map((message) => {\n if (!isPlainObject(message) || message.role !== \"assistant\") return message;\n const toolCalls = message.tool_calls;\n if (!Array.isArray(toolCalls) || toolCalls.length === 0) return message;\n\n let messageMutated = false;\n const nextToolCalls = toolCalls.map((toolCall) => {\n if (!isPlainObject(toolCall)) return toolCall;\n const fn = toolCall.function;\n if (!isPlainObject(fn) || typeof fn.arguments !== \"string\") return toolCall;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fn.arguments);\n } catch {\n return toolCall; // fail open: never corrupt a replayed argument string\n }\n if (!isPlainObject(parsed)) return toolCall;\n\n const schema = typeof fn.name === \"string\" ? schemas.get(fn.name) : undefined;\n const reconstructed = unflattenGeminiToolArguments(parsed, schema);\n if (reconstructed === parsed) return toolCall;\n\n messageMutated = true;\n return { ...toolCall, function: { ...fn, arguments: JSON.stringify(reconstructed) } };\n });\n\n if (!messageMutated) return message;\n mutated = true;\n return { ...message, tool_calls: nextToolCalls };\n });\n\n if (!mutated) return payload;\n return { ...payload, messages: nextMessages };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-renderer.d.ts","sourceRoot":"","sources":["../../../src/core/export-html/tool-renderer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AACpE,OAAO,KAAK,EAAE,cAAc,EAAqB,MAAM,wBAAwB,CAAC;AAGhF,MAAM,WAAW,oBAAoB;IACpC,kDAAkD;IAClD,iBAAiB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,cAAc,GAAG,SAAS,CAAC;IAChE,wBAAwB;IACxB,KAAK,EAAE,KAAK,CAAC;IACb,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,kDAAkD;IAClD,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,gBAAgB;IAChC,oFAAoF;IACpF,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;IACpF,yGAAyG;IACzG,YAAY,CACX,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,EAChF,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,GACd;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACzD;AAsBD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB,CAkHnF","sourcesContent":["/**\n * Tool HTML renderer for custom tools in HTML export.\n *\n * Renders custom tool calls and results to HTML by invoking their TUI renderers\n * and converting the ANSI output to HTML.\n */\n\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderContext } from \"../extensions/types.ts\";\nimport { ansiLinesToHtml } from \"./ansi-to-html.ts\";\n\nexport interface ToolHtmlRendererDeps {\n\t/** Function to look up tool definition by name */\n\tgetToolDefinition: (name: string) => ToolDefinition | undefined;\n\t/** Theme for styling */\n\ttheme: Theme;\n\t/** Working directory for render context */\n\tcwd: string;\n\t/** Terminal width for rendering (default: 100) */\n\twidth?: number;\n}\n\nexport interface ToolHtmlRenderer {\n\t/** Render a tool call to HTML. Returns undefined if tool has no custom renderer. */\n\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined;\n\t/** Render a tool result to collapsed/expanded HTML. Returns undefined if tool has no custom renderer. */\n\trenderResult(\n\t\ttoolCallId: string,\n\t\ttoolName: string,\n\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\tdetails: unknown,\n\t\tisError: boolean,\n\t): { collapsed?: string; expanded?: string } | undefined;\n}\n\n/**\n * Create a tool HTML renderer.\n *\n * The renderer looks up tool definitions and invokes their renderCall/renderResult\n * methods, converting the resulting TUI Component output (ANSI) to HTML.\n */\nconst ANSI_ESCAPE_REGEX = /\\x1b\\[[\\d;]*m/g;\n\nfunction isBlankRenderedLine(line: string): boolean {\n\treturn line.replace(ANSI_ESCAPE_REGEX, \"\").trim().length === 0;\n}\n\nfunction trimRenderedResultLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && isBlankRenderedLine(lines[start])) start++;\n\twhile (end > start && isBlankRenderedLine(lines[end - 1])) end--;\n\treturn lines.slice(start, end);\n}\n\nexport function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRenderer {\n\tconst { getToolDefinition, theme, cwd, width = 100 } = deps;\n\n\tconst renderedCallComponents = new Map<string, Component>();\n\tconst renderedResultComponents = new Map<string, Component>();\n\tconst renderedStates = new Map<string, Record<string, unknown>>();\n\tconst renderedArgs = new Map<string, unknown>();\n\n\tconst getState = (toolCallId: string): Record<string, unknown> => {\n\t\tlet state = renderedStates.get(toolCallId);\n\t\tif (!state) {\n\t\t\tstate = {};\n\t\t\trenderedStates.set(toolCallId, state);\n\t\t}\n\t\treturn state;\n\t};\n\n\tconst createRenderContext = (\n\t\ttoolCallId: string,\n\t\tlastComponent: Component | undefined,\n\t\texpanded: boolean,\n\t\tisPartial: boolean,\n\t\tisError: boolean,\n\t): ToolRenderContext => {\n\t\treturn {\n\t\t\targs: renderedArgs.get(toolCallId),\n\t\t\ttoolCallId,\n\t\t\tinvalidate: () => {},\n\t\t\tlastComponent,\n\t\t\tstate: getState(toolCallId),\n\t\t\tcwd,\n\t\t\texecutionStarted: true,\n\t\t\targsComplete: true,\n\t\t\tisPartial,\n\t\t\texpanded,\n\t\t\tshowImages: false,\n\t\t\tisError,\n\t\t};\n\t};\n\n\treturn {\n\t\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined {\n\t\t\ttry {\n\t\t\t\trenderedArgs.set(toolCallId, args);\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderCall) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst component = toolDef.renderCall(\n\t\t\t\t\targs,\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedCallComponents.get(toolCallId), false, true, false),\n\t\t\t\t);\n\t\t\t\trenderedCallComponents.set(toolCallId, component);\n\t\t\t\tconst lines = component.render(width);\n\t\t\t\treturn ansiLinesToHtml(lines);\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\trenderResult(\n\t\t\ttoolCallId: string,\n\t\t\ttoolName: string,\n\t\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\t\tdetails: unknown,\n\t\t\tisError: boolean,\n\t\t): { collapsed?: string; expanded?: string } | undefined {\n\t\t\ttry {\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderResult) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Build AgentToolResult from content array\n\t\t\t\t// Cast content since session storage uses generic object types\n\t\t\t\tconst agentToolResult = {\n\t\t\t\t\tcontent: result as (TextContent | ImageContent)[],\n\t\t\t\t\tdetails,\n\t\t\t\t\tisError,\n\t\t\t\t};\n\n\t\t\t\t// Render collapsed\n\t\t\t\tconst collapsedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: false, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), false, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, collapsedComponent);\n\t\t\t\tconst collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width)));\n\n\t\t\t\t// Render expanded\n\t\t\t\tconst expandedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: true, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), true, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, expandedComponent);\n\t\t\t\tconst expanded = ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width)));\n\n\t\t\t\treturn {\n\t\t\t\t\t...(collapsed && collapsed !== expanded ? { collapsed } : {}),\n\t\t\t\t\texpanded,\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"tool-renderer.d.ts","sourceRoot":"","sources":["../../../src/core/export-html/tool-renderer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AACpE,OAAO,KAAK,EAAE,cAAc,EAAqB,MAAM,wBAAwB,CAAC;AAGhF,MAAM,WAAW,oBAAoB;IACpC,kDAAkD;IAClD,iBAAiB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,cAAc,GAAG,SAAS,CAAC;IAChE,wBAAwB;IACxB,KAAK,EAAE,KAAK,CAAC;IACb,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,kDAAkD;IAClD,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,gBAAgB;IAChC,oFAAoF;IACpF,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;IACpF,yGAAyG;IACzG,YAAY,CACX,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,EAChF,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,GACd;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACzD;AAsBD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB,CAkHnF","sourcesContent":["/**\n * Tool HTML renderer for custom tools in HTML export.\n *\n * Renders custom tool calls and results to HTML by invoking their TUI renderers\n * and converting the ANSI output to HTML.\n */\n\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderContext } from \"../extensions/types.ts\";\nimport { ansiLinesToHtml } from \"./ansi-to-html.ts\";\n\nexport interface ToolHtmlRendererDeps {\n\t/** Function to look up tool definition by name */\n\tgetToolDefinition: (name: string) => ToolDefinition | undefined;\n\t/** Theme for styling */\n\ttheme: Theme;\n\t/** Working directory for render context */\n\tcwd: string;\n\t/** Terminal width for rendering (default: 100) */\n\twidth?: number;\n}\n\nexport interface ToolHtmlRenderer {\n\t/** Render a tool call to HTML. Returns undefined if tool has no custom renderer. */\n\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined;\n\t/** Render a tool result to collapsed/expanded HTML. Returns undefined if tool has no custom renderer. */\n\trenderResult(\n\t\ttoolCallId: string,\n\t\ttoolName: string,\n\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\tdetails: unknown,\n\t\tisError: boolean,\n\t): { collapsed?: string; expanded?: string } | undefined;\n}\n\n/**\n * Create a tool HTML renderer.\n *\n * The renderer looks up tool definitions and invokes their renderCall/renderResult\n * methods, converting the resulting TUI Component output (ANSI) to HTML.\n */\nconst ANSI_ESCAPE_REGEX = /\\x1b\\[[\\d;]*m/g;\n\nfunction isBlankRenderedLine(line: string): boolean {\n\treturn line.replace(ANSI_ESCAPE_REGEX, \"\").trim().length === 0;\n}\n\nfunction trimRenderedResultLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && isBlankRenderedLine(lines[start])) start++;\n\twhile (end > start && isBlankRenderedLine(lines[end - 1])) end--;\n\treturn lines.slice(start, end);\n}\n\nexport function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRenderer {\n\tconst { getToolDefinition, theme, cwd, width = 100 } = deps;\n\n\tconst renderedCallComponents = new Map<string, Component>();\n\tconst renderedResultComponents = new Map<string, Component>();\n\tconst renderedStates = new Map<string, Record<string, unknown>>();\n\tconst renderedArgs = new Map<string, unknown>();\n\n\tconst getState = (toolCallId: string): Record<string, unknown> => {\n\t\tlet state = renderedStates.get(toolCallId);\n\t\tif (!state) {\n\t\t\tstate = {};\n\t\t\trenderedStates.set(toolCallId, state);\n\t\t}\n\t\treturn state;\n\t};\n\n\tconst createRenderContext = (\n\t\ttoolCallId: string,\n\t\tlastComponent: Component | undefined,\n\t\texpanded: boolean,\n\t\tisPartial: boolean,\n\t\tisError: boolean,\n\t): ToolRenderContext => {\n\t\treturn {\n\t\t\targs: renderedArgs.get(toolCallId),\n\t\t\ttoolCallId,\n\t\t\tinvalidate: () => {},\n\t\t\tlastComponent,\n\t\t\tstate: getState(toolCallId),\n\t\t\tcwd,\n\t\t\texecutionStarted: true,\n\t\t\targsComplete: true,\n\t\t\tisPartial,\n\t\t\texpanded,\n\t\t\tshowImages: false,\n\t\t\tisError,\n\t\t};\n\t};\n\n\treturn {\n\t\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined {\n\t\t\ttry {\n\t\t\t\trenderedArgs.set(toolCallId, args);\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderCall) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst component = toolDef.renderCall(\n\t\t\t\t\targs,\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedCallComponents.get(toolCallId), false, true, false),\n\t\t\t\t);\n\t\t\t\trenderedCallComponents.set(toolCallId, component);\n\t\t\t\tconst lines = component.render(width);\n\t\t\t\treturn ansiLinesToHtml(lines);\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\trenderResult(\n\t\t\ttoolCallId: string,\n\t\t\ttoolName: string,\n\t\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\t\tdetails: unknown,\n\t\t\tisError: boolean,\n\t\t): { collapsed?: string; expanded?: string } | undefined {\n\t\t\ttry {\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderResult) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Build AgentToolResult from content array\n\t\t\t\t// Cast content since session storage uses generic object types\n\t\t\t\tconst agentToolResult = {\n\t\t\t\t\tcontent: result as (TextContent | ImageContent)[],\n\t\t\t\t\tdetails,\n\t\t\t\t\tisError,\n\t\t\t\t};\n\n\t\t\t\t// Render collapsed\n\t\t\t\tconst collapsedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: false, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), false, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, collapsedComponent);\n\t\t\t\tconst collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width)));\n\n\t\t\t\t// Render expanded\n\t\t\t\tconst expandedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: true, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), true, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, expandedComponent);\n\t\t\t\tconst expanded = ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width)));\n\n\t\t\t\treturn {\n\t\t\t\t\t...(collapsed && collapsed !== expanded ? { collapsed } : {}),\n\t\t\t\t\texpanded,\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-renderer.js","sourceRoot":"","sources":["../../../src/core/export-html/tool-renderer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AA0BpD;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAE3C,SAAS,mBAAmB,CAAC,IAAY;IACxC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAe;IAC/C,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;IACvB,OAAO,KAAK,GAAG,GAAG,IAAI,mBAAmB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAAE,KAAK,EAAE,CAAC;IACjE,OAAO,GAAG,GAAG,KAAK,IAAI,mBAAmB,CAAC,KAAK,C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,EACL,mBAAmB,CAAC,UAAU,EAAE,wBAAwB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,CAChG,CAAC;gBACF,wBAAwB,CAAC,GAAG,CAAC,UAAU,EAAE,kBAAkB,CAAC,CAAC;gBAC7D,MAAM,SAAS,GAAG,eAAe,CAAC,uBAAuB,CAAC,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE7F,kBAAkB;gBAClB,MAAM,iBAAiB,GAAG,OAAO,CAAC,YAAY,CAC7C,eAAe,EACf,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,EACpC,KAAK,EACL,mBAAmB,CAAC,UAAU,EAAE,wBAAwB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAC/F,CAAC;gBACF,wBAAwB,CAAC,GAAG,CAAC,UAAU,EAAE,iBAAiB,CAAC,CAAC;gBAC5D,MAAM,QAAQ,GAAG,eAAe,CAAC,uBAAuB,CAAC,iBAAiB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE3F,OAAO;oBACN,GAAG,CAAC,SAAS,IAAI,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC7D,QAAQ;iBACR,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACR,yFAAyF;gBACzF,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Tool HTML renderer for custom tools in HTML export.\n *\n * Renders custom tool calls and results to HTML by invoking their TUI renderers\n * and converting the ANSI output to HTML.\n */\n\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderContext } from \"../extensions/types.ts\";\nimport { ansiLinesToHtml } from \"./ansi-to-html.ts\";\n\nexport interface ToolHtmlRendererDeps {\n\t/** Function to look up tool definition by name */\n\tgetToolDefinition: (name: string) => ToolDefinition | undefined;\n\t/** Theme for styling */\n\ttheme: Theme;\n\t/** Working directory for render context */\n\tcwd: string;\n\t/** Terminal width for rendering (default: 100) */\n\twidth?: number;\n}\n\nexport interface ToolHtmlRenderer {\n\t/** Render a tool call to HTML. Returns undefined if tool has no custom renderer. */\n\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined;\n\t/** Render a tool result to collapsed/expanded HTML. Returns undefined if tool has no custom renderer. */\n\trenderResult(\n\t\ttoolCallId: string,\n\t\ttoolName: string,\n\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\tdetails: unknown,\n\t\tisError: boolean,\n\t): { collapsed?: string; expanded?: string } | undefined;\n}\n\n/**\n * Create a tool HTML renderer.\n *\n * The renderer looks up tool definitions and invokes their renderCall/renderResult\n * methods, converting the resulting TUI Component output (ANSI) to HTML.\n */\nconst ANSI_ESCAPE_REGEX = /\\x1b\\[[\\d;]*m/g;\n\nfunction isBlankRenderedLine(line: string): boolean {\n\treturn line.replace(ANSI_ESCAPE_REGEX, \"\").trim().length === 0;\n}\n\nfunction trimRenderedResultLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && isBlankRenderedLine(lines[start])) start++;\n\twhile (end > start && isBlankRenderedLine(lines[end - 1])) end--;\n\treturn lines.slice(start, end);\n}\n\nexport function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRenderer {\n\tconst { getToolDefinition, theme, cwd, width = 100 } = deps;\n\n\tconst renderedCallComponents = new Map<string, Component>();\n\tconst renderedResultComponents = new Map<string, Component>();\n\tconst renderedStates = new Map<string, Record<string, unknown>>();\n\tconst renderedArgs = new Map<string, unknown>();\n\n\tconst getState = (toolCallId: string): Record<string, unknown> => {\n\t\tlet state = renderedStates.get(toolCallId);\n\t\tif (!state) {\n\t\t\tstate = {};\n\t\t\trenderedStates.set(toolCallId, state);\n\t\t}\n\t\treturn state;\n\t};\n\n\tconst createRenderContext = (\n\t\ttoolCallId: string,\n\t\tlastComponent: Component | undefined,\n\t\texpanded: boolean,\n\t\tisPartial: boolean,\n\t\tisError: boolean,\n\t): ToolRenderContext => {\n\t\treturn {\n\t\t\targs: renderedArgs.get(toolCallId),\n\t\t\ttoolCallId,\n\t\t\tinvalidate: () => {},\n\t\t\tlastComponent,\n\t\t\tstate: getState(toolCallId),\n\t\t\tcwd,\n\t\t\texecutionStarted: true,\n\t\t\targsComplete: true,\n\t\t\tisPartial,\n\t\t\texpanded,\n\t\t\tshowImages: false,\n\t\t\tisError,\n\t\t};\n\t};\n\n\treturn {\n\t\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined {\n\t\t\ttry {\n\t\t\t\trenderedArgs.set(toolCallId, args);\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderCall) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst component = toolDef.renderCall(\n\t\t\t\t\targs,\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedCallComponents.get(toolCallId), false, true, false),\n\t\t\t\t);\n\t\t\t\trenderedCallComponents.set(toolCallId, component);\n\t\t\t\tconst lines = component.render(width);\n\t\t\t\treturn ansiLinesToHtml(lines);\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\trenderResult(\n\t\t\ttoolCallId: string,\n\t\t\ttoolName: string,\n\t\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\t\tdetails: unknown,\n\t\t\tisError: boolean,\n\t\t): { collapsed?: string; expanded?: string } | undefined {\n\t\t\ttry {\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderResult) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Build AgentToolResult from content array\n\t\t\t\t// Cast content since session storage uses generic object types\n\t\t\t\tconst agentToolResult = {\n\t\t\t\t\tcontent: result as (TextContent | ImageContent)[],\n\t\t\t\t\tdetails,\n\t\t\t\t\tisError,\n\t\t\t\t};\n\n\t\t\t\t// Render collapsed\n\t\t\t\tconst collapsedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: false, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), false, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, collapsedComponent);\n\t\t\t\tconst collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width)));\n\n\t\t\t\t// Render expanded\n\t\t\t\tconst expandedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: true, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), true, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, expandedComponent);\n\t\t\t\tconst expanded = ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width)));\n\n\t\t\t\treturn {\n\t\t\t\t\t...(collapsed && collapsed !== expanded ? { collapsed } : {}),\n\t\t\t\t\texpanded,\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"tool-renderer.js","sourceRoot":"","sources":["../../../src/core/export-html/tool-renderer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAAE,eAAe,EAAE,MAAM,mB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AC,CAAC,CAAC,CAAC;gBAE3F,OAAO;oBACN,GAAG,CAAC,SAAS,IAAI,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC7D,QAAQ;iBACR,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACR,yFAAyF;gBACzF,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Tool HTML renderer for custom tools in HTML export.\n *\n * Renders custom tool calls and results to HTML by invoking their TUI renderers\n * and converting the ANSI output to HTML.\n */\n\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderContext } from \"../extensions/types.ts\";\nimport { ansiLinesToHtml } from \"./ansi-to-html.ts\";\n\nexport interface ToolHtmlRendererDeps {\n\t/** Function to look up tool definition by name */\n\tgetToolDefinition: (name: string) => ToolDefinition | undefined;\n\t/** Theme for styling */\n\ttheme: Theme;\n\t/** Working directory for render context */\n\tcwd: string;\n\t/** Terminal width for rendering (default: 100) */\n\twidth?: number;\n}\n\nexport interface ToolHtmlRenderer {\n\t/** Render a tool call to HTML. Returns undefined if tool has no custom renderer. */\n\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined;\n\t/** Render a tool result to collapsed/expanded HTML. Returns undefined if tool has no custom renderer. */\n\trenderResult(\n\t\ttoolCallId: string,\n\t\ttoolName: string,\n\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\tdetails: unknown,\n\t\tisError: boolean,\n\t): { collapsed?: string; expanded?: string } | undefined;\n}\n\n/**\n * Create a tool HTML renderer.\n *\n * The renderer looks up tool definitions and invokes their renderCall/renderResult\n * methods, converting the resulting TUI Component output (ANSI) to HTML.\n */\nconst ANSI_ESCAPE_REGEX = /\\x1b\\[[\\d;]*m/g;\n\nfunction isBlankRenderedLine(line: string): boolean {\n\treturn line.replace(ANSI_ESCAPE_REGEX, \"\").trim().length === 0;\n}\n\nfunction trimRenderedResultLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && isBlankRenderedLine(lines[start])) start++;\n\twhile (end > start && isBlankRenderedLine(lines[end - 1])) end--;\n\treturn lines.slice(start, end);\n}\n\nexport function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRenderer {\n\tconst { getToolDefinition, theme, cwd, width = 100 } = deps;\n\n\tconst renderedCallComponents = new Map<string, Component>();\n\tconst renderedResultComponents = new Map<string, Component>();\n\tconst renderedStates = new Map<string, Record<string, unknown>>();\n\tconst renderedArgs = new Map<string, unknown>();\n\n\tconst getState = (toolCallId: string): Record<string, unknown> => {\n\t\tlet state = renderedStates.get(toolCallId);\n\t\tif (!state) {\n\t\t\tstate = {};\n\t\t\trenderedStates.set(toolCallId, state);\n\t\t}\n\t\treturn state;\n\t};\n\n\tconst createRenderContext = (\n\t\ttoolCallId: string,\n\t\tlastComponent: Component | undefined,\n\t\texpanded: boolean,\n\t\tisPartial: boolean,\n\t\tisError: boolean,\n\t): ToolRenderContext => {\n\t\treturn {\n\t\t\targs: renderedArgs.get(toolCallId),\n\t\t\ttoolCallId,\n\t\t\tinvalidate: () => {},\n\t\t\tlastComponent,\n\t\t\tstate: getState(toolCallId),\n\t\t\tcwd,\n\t\t\texecutionStarted: true,\n\t\t\targsComplete: true,\n\t\t\tisPartial,\n\t\t\texpanded,\n\t\t\tshowImages: false,\n\t\t\tisError,\n\t\t};\n\t};\n\n\treturn {\n\t\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined {\n\t\t\ttry {\n\t\t\t\trenderedArgs.set(toolCallId, args);\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderCall) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst component = toolDef.renderCall(\n\t\t\t\t\targs,\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedCallComponents.get(toolCallId), false, true, false),\n\t\t\t\t);\n\t\t\t\trenderedCallComponents.set(toolCallId, component);\n\t\t\t\tconst lines = component.render(width);\n\t\t\t\treturn ansiLinesToHtml(lines);\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\trenderResult(\n\t\t\ttoolCallId: string,\n\t\t\ttoolName: string,\n\t\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\t\tdetails: unknown,\n\t\t\tisError: boolean,\n\t\t): { collapsed?: string; expanded?: string } | undefined {\n\t\t\ttry {\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderResult) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Build AgentToolResult from content array\n\t\t\t\t// Cast content since session storage uses generic object types\n\t\t\t\tconst agentToolResult = {\n\t\t\t\t\tcontent: result as (TextContent | ImageContent)[],\n\t\t\t\t\tdetails,\n\t\t\t\t\tisError,\n\t\t\t\t};\n\n\t\t\t\t// Render collapsed\n\t\t\t\tconst collapsedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: false, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), false, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, collapsedComponent);\n\t\t\t\tconst collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width)));\n\n\t\t\t\t// Render expanded\n\t\t\t\tconst expandedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: true, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), true, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, expandedComponent);\n\t\t\t\tconst expanded = ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width)));\n\n\t\t\t\treturn {\n\t\t\t\t\t...(collapsed && collapsed !== expanded ? { collapsed } : {}),\n\t\t\t\t\texpanded,\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
2
- import type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from "@earendil-works/pi-ai";
2
+ import type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from "@earendil-works/pi-ai/compat";
3
3
  import type { BuildSystemPromptOptions } from "../system-prompt.ts";
4
4
  import type { ExtensionMode } from "./context-types.ts";
5
5
  import type { ExtensionUIContext } from "./ui-types.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"agent-events.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAqB,EAAE,YAAY,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAChH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAMxD,uDAAuD;AACvD,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,YAAY,EAAE,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U,CAAA;CAAE,GACtB;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,YAAY,EAAE,CAAA;CAAE,GAC9D;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,CAAC","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
1
+ {"version":3,"file":"agent-events.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,GAAG,EAAE,qBAAqB,EAAE,YAAY,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACvH,OAAO,KAAK,EAAE,wBAAwB,EA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ACb,8BAA8B;IAC9B,MAAM,CAAC,EAAE,YAAY,EAAE,CAAC;IACxB,gCAAgC;IAChC,MAAM,EAAE,WAAW,CAAC;IACpB,8FAA8F;IAC9F,iBAAiB,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;CACzC;AAED,sCAAsC;AACtC,MAAM,MAAM,gBAAgB,GACzB;IAAE,MAAM,EAAE,UAAU,CAAA;CAAE,GACtB;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,YAAY,EAAE,CAAA;CAAE,GAC9D;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,CAAC","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai/compat\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-events.js","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
1
+ {"version":3,"file":"agent-events.js","sourceRoot":"","sources":["../../../src/core/extensions/agent-events.ts"],"names":[],"mappings":"","sourcesContent":["import type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessageEvent, ImageContent, Model, ToolResultMessage } from \"@earendil-works/pi-ai/compat\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { ExtensionMode } from \"./context-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tpartialResult: unknown;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: unknown;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<Api>;\n\tpreviousModel: Model<Api> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// Project Trust Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be queued when streaming. Undefined means immediate/normal handling. */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
- import type { Api, ImageContent, Model, TextContent } from "@earendil-works/pi-ai";
2
+ import type { Api, ImageContent, Model, TextContent } from "@earendil-works/pi-ai/compat";
3
3
  import type { KeyId } from "@earendil-works/pi-tui";
4
4
  import type { TSchema } from "typebox";
5
5
  import type { EventBus } from "../event-bus.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"api-types.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/api-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,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AM,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI,CAAC;IAE7D;;;;;;;;;;;;OAYG;IACH,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvC,oDAAoD;IACpD,MAAM,EAAE,QAAQ,CAAC;CACjB","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ResolvedResource } from \"../package-manager.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"../resource-loader.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentStartEvent,\n\tBeforeAgentStartEvent,\n\tBeforeProviderRequestEvent,\n\tContextEvent,\n\tInputEvent,\n\tInputEventResult,\n\tMessageEndEvent,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tProjectTrustHandler,\n\tThinkingLevelSelectEvent,\n\tToolExecutionEndEvent,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUserBashEvent,\n} from \"./agent-events.ts\";\nimport type { RegisteredCommand } from \"./command-types.ts\";\nimport type { ExtensionContext } from \"./context-types.ts\";\nimport type {\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEventResult,\n\tContextEventResult,\n\tMessageEndEventResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tToolCallEventResult,\n\tToolResultEventResult,\n\tUserBashEventResult,\n} from \"./event-results.ts\";\nimport type { MessageRenderer, SendMessageOptions } from \"./message-types.ts\";\nimport type { ProviderConfig } from \"./provider-types.ts\";\nimport type {\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeForkEvent,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeTreeEvent,\n\tSessionCompactEvent,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n\tSessionTreeEvent,\n} from \"./session-events.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./tool-types.ts\";\nimport type { ToolCallEvent, ToolResultEvent } from \"./tool-events.ts\";\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent>): void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t/** Return package-provided workflow files discovered for this session. */\n\tgetWorkflowResources(): ResolvedResource[];\n\n\t/**\n\t * Re-read package/settings workflow resources and return the updated snapshot when supported by the host.\n\t * Does not reload extensions, skills, prompts, themes, or context files.\n\t */\n\trefreshWorkflowResources?: () => Promise<ResolvedResource[]>;\n\n\t/**\n\t * Return the resource-loader options that child Atomic sessions should inherit without sharing this loader instance.\n\t */\n\tgetResourceLoaderInheritanceSnapshot?: () => DefaultResourceLoaderInheritanceSnapshot;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model<Api>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n"]}
1
+ {"version":3,"file":"api-types.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/api-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC1F,OAAO,KAAK,EAAE,KAAK,E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AAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAE9C,kCAAkC;IAClC,gBAAgB,IAAI,aAAa,CAAC;IAElC,0DAA0D;IAC1D,gBAAgB,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;IAM7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmDG;IACH,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI,CAAC;IAE7D;;;;;;;;;;;;OAYG;IACH,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvC,oDAAoD;IACpD,MAAM,EAAE,QAAQ,CAAC;CACjB","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ResolvedResource } from \"../package-manager.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"../resource-loader.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentStartEvent,\n\tBeforeAgentStartEvent,\n\tBeforeProviderRequestEvent,\n\tContextEvent,\n\tInputEvent,\n\tInputEventResult,\n\tMessageEndEvent,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tProjectTrustHandler,\n\tThinkingLevelSelectEvent,\n\tToolExecutionEndEvent,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUserBashEvent,\n} from \"./agent-events.ts\";\nimport type { RegisteredCommand } from \"./command-types.ts\";\nimport type { ExtensionContext } from \"./context-types.ts\";\nimport type {\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEventResult,\n\tContextEventResult,\n\tMessageEndEventResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tToolCallEventResult,\n\tToolResultEventResult,\n\tUserBashEventResult,\n} from \"./event-results.ts\";\nimport type { MessageRenderer, SendMessageOptions } from \"./message-types.ts\";\nimport type { ProviderConfig } from \"./provider-types.ts\";\nimport type {\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeForkEvent,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeTreeEvent,\n\tSessionCompactEvent,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n\tSessionTreeEvent,\n} from \"./session-events.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./tool-types.ts\";\nimport type { ToolCallEvent, ToolResultEvent } from \"./tool-events.ts\";\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent>): void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t/** Return package-provided workflow files discovered for this session. */\n\tgetWorkflowResources(): ResolvedResource[];\n\n\t/**\n\t * Re-read package/settings workflow resources and return the updated snapshot when supported by the host.\n\t * Does not reload extensions, skills, prompts, themes, or context files.\n\t */\n\trefreshWorkflowResources?: () => Promise<ResolvedResource[]>;\n\n\t/**\n\t * Return the resource-loader options that child Atomic sessions should inherit without sharing this loader instance.\n\t */\n\tgetResourceLoaderInheritanceSnapshot?: () => DefaultResourceLoaderInheritanceSnapshot;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model<Api>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"api-types.js","sourceRoot":"","sources":["../../../src/core/extensions/api-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ResolvedResource } from \"../package-manager.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"../resource-loader.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentStartEvent,\n\tBeforeAgentStartEvent,\n\tBeforeProviderRequestEvent,\n\tContextEvent,\n\tInputEvent,\n\tInputEventResult,\n\tMessageEndEvent,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tProjectTrustHandler,\n\tThinkingLevelSelectEvent,\n\tToolExecutionEndEvent,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUserBashEvent,\n} from \"./agent-events.ts\";\nimport type { RegisteredCommand } from \"./command-types.ts\";\nimport type { ExtensionContext } from \"./context-types.ts\";\nimport type {\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEventResult,\n\tContextEventResult,\n\tMessageEndEventResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tToolCallEventResult,\n\tToolResultEventResult,\n\tUserBashEventResult,\n} from \"./event-results.ts\";\nimport type { MessageRenderer, SendMessageOptions } from \"./message-types.ts\";\nimport type { ProviderConfig } from \"./provider-types.ts\";\nimport type {\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeForkEvent,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeTreeEvent,\n\tSessionCompactEvent,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n\tSessionTreeEvent,\n} from \"./session-events.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./tool-types.ts\";\nimport type { ToolCallEvent, ToolResultEvent } from \"./tool-events.ts\";\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent>): void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t/** Return package-provided workflow files discovered for this session. */\n\tgetWorkflowResources(): ResolvedResource[];\n\n\t/**\n\t * Re-read package/settings workflow resources and return the updated snapshot when supported by the host.\n\t * Does not reload extensions, skills, prompts, themes, or context files.\n\t */\n\trefreshWorkflowResources?: () => Promise<ResolvedResource[]>;\n\n\t/**\n\t * Return the resource-loader options that child Atomic sessions should inherit without sharing this loader instance.\n\t */\n\tgetResourceLoaderInheritanceSnapshot?: () => DefaultResourceLoaderInheritanceSnapshot;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model<Api>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n"]}
1
+ {"version":3,"file":"api-types.js","sourceRoot":"","sources":["../../../src/core/extensions/api-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport type { TSchema } from \"typebox\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ResolvedResource } from \"../package-manager.ts\";\nimport type { DefaultResourceLoaderInheritanceSnapshot } from \"../resource-loader.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentStartEvent,\n\tBeforeAgentStartEvent,\n\tBeforeProviderRequestEvent,\n\tContextEvent,\n\tInputEvent,\n\tInputEventResult,\n\tMessageEndEvent,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tProjectTrustHandler,\n\tThinkingLevelSelectEvent,\n\tToolExecutionEndEvent,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUserBashEvent,\n} from \"./agent-events.ts\";\nimport type { RegisteredCommand } from \"./command-types.ts\";\nimport type { ExtensionContext } from \"./context-types.ts\";\nimport type {\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEventResult,\n\tContextEventResult,\n\tMessageEndEventResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tToolCallEventResult,\n\tToolResultEventResult,\n\tUserBashEventResult,\n} from \"./event-results.ts\";\nimport type { MessageRenderer, SendMessageOptions } from \"./message-types.ts\";\nimport type { ProviderConfig } from \"./provider-types.ts\";\nimport type {\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeForkEvent,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeTreeEvent,\n\tSessionCompactEvent,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n\tSessionTreeEvent,\n} from \"./session-events.ts\";\nimport type { ToolDefinition, ToolInfo } from \"./tool-types.ts\";\nimport type { ToolCallEvent, ToolResultEvent } from \"./tool-events.ts\";\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"resources_discover\", handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>): void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent>): void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = unknown>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t/** Return package-provided workflow files discovered for this session. */\n\tgetWorkflowResources(): ResolvedResource[];\n\n\t/**\n\t * Re-read package/settings workflow resources and return the updated snapshot when supported by the host.\n\t * Does not reload extensions, skills, prompts, themes, or context files.\n\t */\n\trefreshWorkflowResources?: () => Promise<ResolvedResource[]>;\n\n\t/**\n\t * Return the resource-loader options that child Atomic sessions should inherit without sharing this loader instance.\n\t */\n\tgetResourceLoaderInheritanceSnapshot?: () => DefaultResourceLoaderInheritanceSnapshot;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model<Api>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { Api, ImageContent, Model, TextContent } from "@earendil-works/pi-ai";
1
+ import type { Api, ImageContent, Model, TextContent } from "@earendil-works/pi-ai/compat";
2
2
  import type { ContextCompactionResult } from "../compaction/index.ts";
3
3
  import type { CustomMessage } from "../messages.ts";
4
4
  import type { ModelRegistry } from "../model-registry.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"context-types.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/context-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACpF,OAAO,KAAK,EAA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SAAS,GAAG,SAAS,GAAG,SAAS,CAAC,EACjF,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB,eAAe,CACd,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,GAAG,UAAU,CAAA;KAAE,GAC5C,OAAO,CAAC,IAAI,CAAC,CAAC;CACjB","sourcesContent":["import type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport type { ContextCompactionResult } from \"../compaction/index.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ReadonlySessionManager, SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { SendMessageOptions } from \"./message-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\t/** Fraction of compactable context to keep. 0.3 is aggressive, 0.7 is light. */\n\tcompression_ratio?: number;\n\t/** Number of recent context-eligible messages to keep uncompressed. */\n\tpreserve_recent?: number;\n\t/** Focus query for relevance-based pruning. Defaults to auto-detected session context. */\n\tquery?: string;\n\tonComplete?: (result: ContextCompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\nexport interface WorkflowStageOrchestrationContext {\n\treadonly kind: \"workflow-stage\";\n\treadonly workflowRunId: string;\n\treadonly workflowStageId: string;\n\treadonly workflowStageName: string;\n\treadonly constraints: {\n\t\treadonly disableWorkflowTool: true;\n\t\treadonly maxSubagentDepth: number;\n\t};\n}\n\n// Union alias kept for forward-compatible orchestration context variants.\nexport type OrchestrationContext = WorkflowStageOrchestrationContext;\n\n/**\n * Context passed to extension event handlers.\n */\nexport type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** Session-scoped orchestration policy for child runtimes such as workflow stages. */\n\treadonly orchestrationContext?: OrchestrationContext;\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model<Api> | undefined;\n\t/** Session-scoped internal resource router (e.g. artifact:// resolver). */\n\treadonly internalResourceRouter?: import(\"../tools/resource-selectors.ts\").InternalResourceRouter;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown pi and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, and themes. */\n\treload(): Promise<void>;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"context-types.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/context-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC1F,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,EAAE,aAAa,E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CAAC;CACxB;AAED;;;;GAIG;AACH,MAAM,WAAW,sBAAuB,SAAQ,uBAAuB;IACtE,WAAW,CAAC,CAAC,GAAG,OAAO,EACtB,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,YAAY,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,CAAC,EACjF,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB,eAAe,CACd,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,GAAG,UAAU,CAAA;KAAE,GAC5C,OAAO,CAAC,IAAI,CAAC,CAAC;CACjB","sourcesContent":["import type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { ContextCompactionResult } from \"../compaction/index.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ReadonlySessionManager, SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { SendMessageOptions } from \"./message-types.ts\";\nimport type { ExtensionUIContext } from \"./ui-types.ts\";\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\t/** Fraction of compactable context to keep. 0.3 is aggressive, 0.7 is light. */\n\tcompression_ratio?: number;\n\t/** Number of recent context-eligible messages to keep uncompressed. */\n\tpreserve_recent?: number;\n\t/** Focus query for relevance-based pruning. Defaults to auto-detected session context. */\n\tquery?: string;\n\tonComplete?: (result: ContextCompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\nexport interface WorkflowStageOrchestrationContext {\n\treadonly kind: \"workflow-stage\";\n\treadonly workflowRunId: string;\n\treadonly workflowStageId: string;\n\treadonly workflowStageName: string;\n\treadonly constraints: {\n\t\treadonly disableWorkflowTool: true;\n\t\treadonly maxSubagentDepth: number;\n\t};\n}\n\n// Union alias kept for forward-compatible orchestration context variants.\nexport type OrchestrationContext = WorkflowStageOrchestrationContext;\n\n/**\n * Context passed to extension event handlers.\n */\nexport type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** Session-scoped orchestration policy for child runtimes such as workflow stages. */\n\treadonly orchestrationContext?: OrchestrationContext;\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model<Api> | undefined;\n\t/** Session-scoped internal resource router (e.g. artifact:// resolver). */\n\treadonly internalResourceRouter?: import(\"../tools/resource-selectors.ts\").InternalResourceRouter;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown pi and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, and themes. */\n\treload(): Promise<void>;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void>;\n}\n"]}