@bastani/atomic 0.9.5-alpha.9 → 0.9.5

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 (377) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +2 -2
  3. package/dist/builtin/cursor/CHANGELOG.md +12 -0
  4. package/dist/builtin/cursor/package.json +3 -3
  5. package/dist/builtin/cursor/src/model-mapper.ts +6 -3
  6. package/dist/builtin/intercom/CHANGELOG.md +37 -0
  7. package/dist/builtin/intercom/README.md +4 -2
  8. package/dist/builtin/intercom/broker/broker.ts +6 -114
  9. package/dist/builtin/intercom/broker/client.ts +29 -54
  10. package/dist/builtin/intercom/broker/delivered-message-cache.ts +44 -0
  11. package/dist/builtin/intercom/broker/pending-send-registry.ts +142 -0
  12. package/dist/builtin/intercom/broker/send-handler.ts +106 -0
  13. package/dist/builtin/intercom/broker/send-signature.ts +37 -0
  14. package/dist/builtin/intercom/foreground-detach-handoff.ts +136 -0
  15. package/dist/builtin/intercom/index-heavy.ts +49 -53
  16. package/dist/builtin/intercom/index.ts +278 -262
  17. package/dist/builtin/intercom/lazy-heavy-proxy.ts +114 -0
  18. package/dist/builtin/intercom/lazy-subagent-ack.ts +20 -0
  19. package/dist/builtin/intercom/lazy-tool-execution.ts +39 -0
  20. package/dist/builtin/intercom/lifecycle-lease.ts +51 -0
  21. package/dist/builtin/intercom/lifecycle.ts +37 -20
  22. package/dist/builtin/intercom/package.json +3 -6
  23. package/dist/builtin/intercom/reply-routing.ts +17 -0
  24. package/dist/builtin/intercom/subagent-relay.ts +58 -12
  25. package/dist/builtin/intercom/types.ts +3 -3
  26. package/dist/builtin/mcp/CHANGELOG.md +27 -0
  27. package/dist/builtin/mcp/OAUTH.md +1 -0
  28. package/dist/builtin/mcp/README.md +4 -0
  29. package/dist/builtin/mcp/apps-cancellation.ts +32 -0
  30. package/dist/builtin/mcp/call-tool-result.ts +9 -0
  31. package/dist/builtin/mcp/caller-wait.ts +50 -0
  32. package/dist/builtin/mcp/command-registration.ts +82 -0
  33. package/dist/builtin/mcp/direct-tool-executor.ts +279 -0
  34. package/dist/builtin/mcp/direct-tools.ts +6 -239
  35. package/dist/builtin/mcp/host-html-template.ts +4 -2
  36. package/dist/builtin/mcp/index.ts +258 -250
  37. package/dist/builtin/mcp/init.ts +96 -87
  38. package/dist/builtin/mcp/mcp-auth-flow.ts +247 -237
  39. package/dist/builtin/mcp/mcp-callback-server.ts +89 -68
  40. package/dist/builtin/mcp/mcp-oauth-provider.ts +23 -1
  41. package/dist/builtin/mcp/metadata-hydration.ts +21 -6
  42. package/dist/builtin/mcp/package.json +3 -3
  43. package/dist/builtin/mcp/proxy-auth.ts +4 -4
  44. package/dist/builtin/mcp/proxy-call.ts +111 -40
  45. package/dist/builtin/mcp/proxy-connect.ts +35 -15
  46. package/dist/builtin/mcp/proxy-info-modes.ts +49 -19
  47. package/dist/builtin/mcp/proxy-modes.ts +3 -3
  48. package/dist/builtin/mcp/session-cleanup-barrier.ts +43 -0
  49. package/dist/builtin/mcp/state-lease.ts +12 -0
  50. package/dist/builtin/mcp/ui-server.ts +8 -8
  51. package/dist/builtin/mcp/ui-session.ts +9 -18
  52. package/dist/builtin/subagents/CHANGELOG.md +66 -0
  53. package/dist/builtin/subagents/README.md +30 -29
  54. package/dist/builtin/subagents/agents/code-simplifier.md +2 -2
  55. package/dist/builtin/subagents/agents/codebase-analyzer.md +2 -2
  56. package/dist/builtin/subagents/agents/codebase-locator.md +2 -2
  57. package/dist/builtin/subagents/agents/codebase-online-researcher.md +2 -2
  58. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -2
  59. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +2 -2
  60. package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -2
  61. package/dist/builtin/subagents/agents/debugger.md +2 -2
  62. package/dist/builtin/subagents/agents/worker.md +2 -2
  63. package/dist/builtin/subagents/package.json +5 -5
  64. package/dist/builtin/subagents/prompts/review-loop.md +1 -1
  65. package/dist/builtin/subagents/skills/subagent/SKILL.md +37 -36
  66. package/dist/builtin/subagents/src/extension/api-lifecycle.ts +64 -0
  67. package/dist/builtin/subagents/src/extension/fanout-child.ts +44 -51
  68. package/dist/builtin/subagents/src/extension/index.ts +287 -307
  69. package/dist/builtin/subagents/src/extension/prompt-guidance.ts +7 -10
  70. package/dist/builtin/subagents/src/extension/schemas.ts +22 -5
  71. package/dist/builtin/subagents/src/extension/tool-description.ts +29 -0
  72. package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +13 -2
  73. package/dist/builtin/subagents/src/intercom/result-intercom.ts +4 -4
  74. package/dist/builtin/subagents/src/runs/background/async-event-journal.ts +106 -0
  75. package/dist/builtin/subagents/src/runs/background/async-execution-common.ts +3 -2
  76. package/dist/builtin/subagents/src/runs/background/async-execution-single.ts +13 -2
  77. package/dist/builtin/subagents/src/runs/background/async-execution-types.ts +3 -0
  78. package/dist/builtin/subagents/src/runs/background/async-job-tracker.ts +1 -1
  79. package/dist/builtin/subagents/src/runs/background/completion-claims.ts +189 -0
  80. package/dist/builtin/subagents/src/runs/background/completion-dedupe.ts +44 -7
  81. package/dist/builtin/subagents/src/runs/background/completion-notification.ts +34 -0
  82. package/dist/builtin/subagents/src/runs/background/notify.ts +72 -22
  83. package/dist/builtin/subagents/src/runs/background/result-delivery-processor.ts +232 -0
  84. package/dist/builtin/subagents/src/runs/background/result-file-claims.ts +151 -0
  85. package/dist/builtin/subagents/src/runs/background/result-quarantine.ts +72 -0
  86. package/dist/builtin/subagents/src/runs/background/result-retry-scheduler.ts +48 -0
  87. package/dist/builtin/subagents/src/runs/background/result-status.ts +81 -0
  88. package/dist/builtin/subagents/src/runs/background/result-watcher-data.ts +59 -0
  89. package/dist/builtin/subagents/src/runs/background/result-watcher.ts +172 -238
  90. package/dist/builtin/subagents/src/runs/background/run-id-resolver.ts +3 -2
  91. package/dist/builtin/subagents/src/runs/background/stale-run-reconciler.ts +73 -14
  92. package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +17 -13
  93. package/dist/builtin/subagents/src/runs/background/top-level-async.ts +1 -2
  94. package/dist/builtin/subagents/src/runs/foreground/chain-execution-dynamic-step.ts +1 -0
  95. package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-runner.ts +1 -0
  96. package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-step.ts +1 -0
  97. package/dist/builtin/subagents/src/runs/foreground/chain-execution-sequential-step.ts +7 -9
  98. package/dist/builtin/subagents/src/runs/foreground/chain-execution-types.ts +3 -13
  99. package/dist/builtin/subagents/src/runs/foreground/chain-execution.ts +2 -15
  100. package/dist/builtin/subagents/src/runs/foreground/execution-attempt-finalize.ts +2 -2
  101. package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +53 -44
  102. package/dist/builtin/subagents/src/runs/foreground/execution-detach-reservations.ts +48 -0
  103. package/dist/builtin/subagents/src/runs/foreground/execution-detach-route.ts +17 -0
  104. package/dist/builtin/subagents/src/runs/foreground/execution-run-sync.ts +39 -26
  105. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +3 -1
  106. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-chain.ts +3 -51
  107. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +6 -11
  108. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-input.ts +11 -2
  109. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +2 -0
  110. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +5 -112
  111. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-resume.ts +2 -0
  112. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +68 -118
  113. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +79 -7
  114. package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +2 -2
  115. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +3 -0
  116. package/dist/builtin/subagents/src/runs/shared/pi-args.ts +2 -2
  117. package/dist/builtin/subagents/src/runs/shared/pi-spawn.ts +27 -11
  118. package/dist/builtin/subagents/src/shared/artifacts.ts +22 -11
  119. package/dist/builtin/subagents/src/shared/event-jsonl-writer.ts +294 -0
  120. package/dist/builtin/subagents/src/shared/exclusive-file-publication.ts +44 -0
  121. package/dist/builtin/subagents/src/shared/jsonl-writer.ts +1 -0
  122. package/dist/builtin/subagents/src/shared/model-info.ts +2 -2
  123. package/dist/builtin/subagents/src/shared/settings.ts +20 -10
  124. package/dist/builtin/subagents/src/shared/types-async.ts +3 -1
  125. package/dist/builtin/subagents/src/shared/types-config.ts +2 -0
  126. package/dist/builtin/subagents/src/shared/types-runtime.ts +3 -2
  127. package/dist/builtin/subagents/src/slash/slash-commands.ts +9 -12
  128. package/dist/builtin/subagents/src/slash/slash-live-state.ts +63 -32
  129. package/dist/builtin/subagents/src/tui/render-result.ts +7 -0
  130. package/dist/builtin/subagents/src/tui/render-stable-output.ts +1 -0
  131. package/dist/builtin/subagents/src/tui/render-widget.ts +128 -89
  132. package/dist/builtin/web-access/CHANGELOG.md +28 -0
  133. package/dist/builtin/web-access/README.md +4 -0
  134. package/dist/builtin/web-access/content-tools.ts +8 -3
  135. package/dist/builtin/web-access/index-heavy.ts +1 -1
  136. package/dist/builtin/web-access/index.ts +190 -46
  137. package/dist/builtin/web-access/lifecycle-lease.ts +38 -0
  138. package/dist/builtin/web-access/package.json +2 -2
  139. package/dist/builtin/web-access/result-renderers.ts +1 -1
  140. package/dist/builtin/web-access/summary-review.ts +1 -1
  141. package/dist/builtin/web-access/web-search-activity.ts +1 -1
  142. package/dist/builtin/web-access/web-search-return.ts +7 -0
  143. package/dist/builtin/web-access/web-search-summary.ts +1 -1
  144. package/dist/builtin/web-access/web-search-tool.ts +4 -2
  145. package/dist/builtin/workflows/CHANGELOG.md +68 -0
  146. package/dist/builtin/workflows/README.md +4 -4
  147. package/dist/builtin/workflows/builtin/deep-research-codebase-utils.ts +27 -4
  148. package/dist/builtin/workflows/builtin/goal-runner.ts +47 -26
  149. package/dist/builtin/workflows/builtin/open-claude-design-runner.ts +10 -0
  150. package/dist/builtin/workflows/builtin/ralph-core.ts +9 -9
  151. package/dist/builtin/workflows/builtin/ralph-models.ts +71 -36
  152. package/dist/builtin/workflows/builtin/ralph-runner.ts +20 -31
  153. package/dist/builtin/workflows/package.json +2 -2
  154. package/dist/builtin/workflows/src/durable/stage-primitive.ts +2 -1
  155. package/dist/builtin/workflows/src/engine/primitives/task.ts +2 -1
  156. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +17 -22
  157. package/dist/builtin/workflows/src/extension/workflow-schema.ts +15 -2
  158. package/dist/builtin/workflows/src/runs/foreground/executor-hil.ts +1 -2
  159. package/dist/builtin/workflows/src/runs/shared/model-fallback-candidates.ts +1 -1
  160. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +2 -2
  161. package/dist/builtin/workflows/src/shared/authoring-contract-stage.ts +2 -2
  162. package/dist/builtin/workflows/src/shared/resume-continuation.ts +2 -0
  163. package/dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts +1 -23
  164. package/dist/builtin/workflows/src/tui/stage-chat-view-footer-status.ts +54 -9
  165. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +5 -2
  166. package/dist/cli/args.d.ts.map +1 -1
  167. package/dist/cli/args.js +2 -2
  168. package/dist/cli/args.js.map +1 -1
  169. package/dist/core/agent-session-events.d.ts.map +1 -1
  170. package/dist/core/agent-session-events.js +2 -1
  171. package/dist/core/agent-session-events.js.map +1 -1
  172. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  173. package/dist/core/agent-session-message-queue.js +1 -1
  174. package/dist/core/agent-session-message-queue.js.map +1 -1
  175. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  176. package/dist/core/agent-session-prompt.js +1 -1
  177. package/dist/core/agent-session-prompt.js.map +1 -1
  178. package/dist/core/agent-session-retry.d.ts.map +1 -1
  179. package/dist/core/agent-session-retry.js +1 -1
  180. package/dist/core/agent-session-retry.js.map +1 -1
  181. package/dist/core/agent-session-services.d.ts.map +1 -1
  182. package/dist/core/agent-session-services.js +3 -2
  183. package/dist/core/agent-session-services.js.map +1 -1
  184. package/dist/core/agent-session-types.d.ts.map +1 -1
  185. package/dist/core/agent-session-types.js +1 -1
  186. package/dist/core/agent-session-types.js.map +1 -1
  187. package/dist/core/anthropic-thinking-guard.d.ts +5 -5
  188. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  189. package/dist/core/anthropic-thinking-guard.js +42 -32
  190. package/dist/core/anthropic-thinking-guard.js.map +1 -1
  191. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  192. package/dist/core/atomic-guide-command.js +15 -15
  193. package/dist/core/atomic-guide-command.js.map +1 -1
  194. package/dist/core/auth-storage.d.ts.map +1 -1
  195. package/dist/core/auth-storage.js +14 -9
  196. package/dist/core/auth-storage.js.map +1 -1
  197. package/dist/core/compaction/compaction.d.ts +2 -0
  198. package/dist/core/compaction/compaction.d.ts.map +1 -1
  199. package/dist/core/compaction/compaction.js +79 -46
  200. package/dist/core/compaction/compaction.js.map +1 -1
  201. package/dist/core/compaction/context-assistant-turns.d.ts +42 -0
  202. package/dist/core/compaction/context-assistant-turns.d.ts.map +1 -0
  203. package/dist/core/compaction/context-assistant-turns.js +87 -0
  204. package/dist/core/compaction/context-assistant-turns.js.map +1 -0
  205. package/dist/core/compaction/context-compaction-critical.d.ts +1 -1
  206. package/dist/core/compaction/context-compaction-critical.d.ts.map +1 -1
  207. package/dist/core/compaction/context-compaction-critical.js +2 -2
  208. package/dist/core/compaction/context-compaction-critical.js.map +1 -1
  209. package/dist/core/compaction/context-compaction-eviction-alternates.d.ts +18 -0
  210. package/dist/core/compaction/context-compaction-eviction-alternates.d.ts.map +1 -0
  211. package/dist/core/compaction/context-compaction-eviction-alternates.js +186 -0
  212. package/dist/core/compaction/context-compaction-eviction-alternates.js.map +1 -0
  213. package/dist/core/compaction/context-compaction-eviction.d.ts +10 -2
  214. package/dist/core/compaction/context-compaction-eviction.d.ts.map +1 -1
  215. package/dist/core/compaction/context-compaction-eviction.js +196 -146
  216. package/dist/core/compaction/context-compaction-eviction.js.map +1 -1
  217. package/dist/core/compaction/context-compaction-prompt.d.ts.map +1 -1
  218. package/dist/core/compaction/context-compaction-prompt.js +1 -1
  219. package/dist/core/compaction/context-compaction-prompt.js.map +1 -1
  220. package/dist/core/compaction/context-compaction-types.d.ts +2 -0
  221. package/dist/core/compaction/context-compaction-types.d.ts.map +1 -1
  222. package/dist/core/compaction/context-compaction-types.js.map +1 -1
  223. package/dist/core/compaction/context-deletion-application.d.ts +5 -4
  224. package/dist/core/compaction/context-deletion-application.d.ts.map +1 -1
  225. package/dist/core/compaction/context-deletion-application.js +17 -15
  226. package/dist/core/compaction/context-deletion-application.js.map +1 -1
  227. package/dist/core/compaction/context-deletion-store.d.ts.map +1 -1
  228. package/dist/core/compaction/context-deletion-store.js +1 -1
  229. package/dist/core/compaction/context-deletion-store.js.map +1 -1
  230. package/dist/core/compaction/context-deletion-targets.d.ts +2 -1
  231. package/dist/core/compaction/context-deletion-targets.d.ts.map +1 -1
  232. package/dist/core/compaction/context-deletion-targets.js +36 -31
  233. package/dist/core/compaction/context-deletion-targets.js.map +1 -1
  234. package/dist/core/compaction/context-deletion-tool-helpers.d.ts.map +1 -1
  235. package/dist/core/compaction/context-deletion-tool-helpers.js +116 -43
  236. package/dist/core/compaction/context-deletion-tool-helpers.js.map +1 -1
  237. package/dist/core/compaction/context-transcript-analysis.d.ts +1 -2
  238. package/dist/core/compaction/context-transcript-analysis.d.ts.map +1 -1
  239. package/dist/core/compaction/context-transcript-analysis.js +33 -37
  240. package/dist/core/compaction/context-transcript-analysis.js.map +1 -1
  241. package/dist/core/copilot-model-synthesis.d.ts.map +1 -1
  242. package/dist/core/copilot-model-synthesis.js +3 -1
  243. package/dist/core/copilot-model-synthesis.js.map +1 -1
  244. package/dist/core/extensions/provider-types.d.ts +2 -7
  245. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  246. package/dist/core/extensions/provider-types.js.map +1 -1
  247. package/dist/core/messages.d.ts +9 -0
  248. package/dist/core/messages.d.ts.map +1 -1
  249. package/dist/core/messages.js +100 -18
  250. package/dist/core/messages.js.map +1 -1
  251. package/dist/core/model-registry-builtins.d.ts.map +1 -1
  252. package/dist/core/model-registry-builtins.js +5 -0
  253. package/dist/core/model-registry-builtins.js.map +1 -1
  254. package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
  255. package/dist/core/model-registry-custom-loader.js +49 -8
  256. package/dist/core/model-registry-custom-loader.js.map +1 -1
  257. package/dist/core/model-registry-dynamic.d.ts.map +1 -1
  258. package/dist/core/model-registry-dynamic.js +11 -5
  259. package/dist/core/model-registry-dynamic.js.map +1 -1
  260. package/dist/core/model-registry-loader.d.ts.map +1 -1
  261. package/dist/core/model-registry-loader.js +8 -0
  262. package/dist/core/model-registry-loader.js.map +1 -1
  263. package/dist/core/model-registry-schemas.d.ts +93 -8
  264. package/dist/core/model-registry-schemas.d.ts.map +1 -1
  265. package/dist/core/model-registry-schemas.js +24 -12
  266. package/dist/core/model-registry-schemas.js.map +1 -1
  267. package/dist/core/model-registry-types.d.ts +7 -6
  268. package/dist/core/model-registry-types.d.ts.map +1 -1
  269. package/dist/core/model-registry-types.js.map +1 -1
  270. package/dist/core/model-registry.d.ts +5 -0
  271. package/dist/core/model-registry.d.ts.map +1 -1
  272. package/dist/core/model-registry.js +23 -0
  273. package/dist/core/model-registry.js.map +1 -1
  274. package/dist/core/model-resolver-cli.d.ts.map +1 -1
  275. package/dist/core/model-resolver-cli.js +33 -5
  276. package/dist/core/model-resolver-cli.js.map +1 -1
  277. package/dist/core/model-resolver-initial.d.ts +6 -1
  278. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  279. package/dist/core/model-resolver-initial.js +12 -7
  280. package/dist/core/model-resolver-initial.js.map +1 -1
  281. package/dist/core/model-resolver.d.ts +1 -1
  282. package/dist/core/model-resolver.d.ts.map +1 -1
  283. package/dist/core/model-resolver.js +1 -1
  284. package/dist/core/model-resolver.js.map +1 -1
  285. package/dist/core/resource-loader-context-files.d.ts +1 -0
  286. package/dist/core/resource-loader-context-files.d.ts.map +1 -1
  287. package/dist/core/resource-loader-context-files.js +13 -10
  288. package/dist/core/resource-loader-context-files.js.map +1 -1
  289. package/dist/core/sdk.d.ts.map +1 -1
  290. package/dist/core/sdk.js +2 -2
  291. package/dist/core/sdk.js.map +1 -1
  292. package/dist/core/session-entry-normalization.d.ts +7 -0
  293. package/dist/core/session-entry-normalization.d.ts.map +1 -0
  294. package/dist/core/session-entry-normalization.js +14 -0
  295. package/dist/core/session-entry-normalization.js.map +1 -0
  296. package/dist/core/session-manager-core.d.ts.map +1 -1
  297. package/dist/core/session-manager-core.js +1 -0
  298. package/dist/core/session-manager-core.js.map +1 -1
  299. package/dist/core/session-manager-history.d.ts +2 -2
  300. package/dist/core/session-manager-history.d.ts.map +1 -1
  301. package/dist/core/session-manager-history.js +127 -108
  302. package/dist/core/session-manager-history.js.map +1 -1
  303. package/dist/core/settings-manager-basic-accessors.d.ts +2 -2
  304. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  305. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  306. package/dist/core/settings-types.d.ts +1 -1
  307. package/dist/core/settings-types.d.ts.map +1 -1
  308. package/dist/core/settings-types.js.map +1 -1
  309. package/dist/core/tools/bash.d.ts.map +1 -1
  310. package/dist/core/tools/bash.js +11 -8
  311. package/dist/core/tools/bash.js.map +1 -1
  312. package/dist/main-session.d.ts.map +1 -1
  313. package/dist/main-session.js +1 -0
  314. package/dist/main-session.js.map +1 -1
  315. package/dist/modes/interactive/components/settings-selector-options.d.ts.map +1 -1
  316. package/dist/modes/interactive/components/settings-selector-options.js +3 -1
  317. package/dist/modes/interactive/components/settings-selector-options.js.map +1 -1
  318. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  319. package/dist/modes/interactive/components/thinking-selector.js +2 -1
  320. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  321. package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
  322. package/dist/modes/interactive/interactive-agent-events.js +2 -1
  323. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  324. package/dist/modes/interactive/interactive-child-ordering.d.ts +7 -0
  325. package/dist/modes/interactive/interactive-child-ordering.d.ts.map +1 -0
  326. package/dist/modes/interactive/interactive-child-ordering.js +26 -0
  327. package/dist/modes/interactive/interactive-child-ordering.js.map +1 -0
  328. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  329. package/dist/modes/interactive/interactive-deferred-startup.js +2 -2
  330. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  331. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  332. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  333. package/dist/modes/interactive/interactive-mode-deps.js +1 -1
  334. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  335. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  336. package/dist/modes/interactive/interactive-model-routing.js +8 -3
  337. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  338. package/dist/modes/interactive/theme/theme-class.d.ts +1 -1
  339. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  340. package/dist/modes/interactive/theme/theme-class.js +2 -0
  341. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  342. package/dist/utils/clipboard-image.d.ts.map +1 -1
  343. package/dist/utils/clipboard-image.js +3 -0
  344. package/dist/utils/clipboard-image.js.map +1 -1
  345. package/docs/changelog.mdx +19 -0
  346. package/docs/compaction.md +55 -48
  347. package/docs/custom-provider.md +18 -5
  348. package/docs/extensions.md +7 -3
  349. package/docs/models.md +69 -10
  350. package/docs/providers.md +1 -1
  351. package/docs/quickstart.md +11 -7
  352. package/docs/rpc.md +2 -2
  353. package/docs/sdk.md +1 -1
  354. package/docs/settings.md +3 -3
  355. package/docs/subagents.md +36 -5
  356. package/docs/tools.md +1 -1
  357. package/docs/usage.md +4 -2
  358. package/docs/workflows.md +26 -43
  359. package/examples/extensions/preset.ts +2 -2
  360. package/examples/extensions/subagent/README.md +2 -2
  361. package/examples/extensions/subagent/index.ts +1 -2
  362. package/examples/extensions/subagent/schemas.ts +4 -1
  363. package/examples/sdk/12-full-control.ts +1 -1
  364. package/npm-shrinkwrap.json +48 -51
  365. package/package.json +7 -7
  366. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-behavior.ts +0 -75
  367. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-component.ts +0 -202
  368. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-edit.ts +0 -97
  369. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-editor.ts +0 -160
  370. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-frame.ts +0 -72
  371. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-render-modes.ts +0 -161
  372. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-render-selectors.ts +0 -203
  373. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-selectors.ts +0 -234
  374. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-state.ts +0 -103
  375. package/dist/builtin/subagents/src/runs/foreground/chain-clarify-types.ts +0 -29
  376. package/dist/builtin/subagents/src/runs/foreground/chain-clarify.ts +0 -9
  377. package/dist/builtin/subagents/src/runs/foreground/chain-execution-clarify.ts +0 -117
@@ -1 +1 @@
1
- {"version":3,"file":"context-transcript-analysis.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAOlE,OAAO,EAGN,KAAK,YAAY,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,EAGN,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,EAChC,MAAM,+BAA+B,CAAC;AA0BvC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CASvE;AA6BD,wBAAgB,qCAAqC,CAAC,KAAK,EAAE,0BAA0B,GAAG,OAAO,CAMhG;AAmFD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAEhE;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAEjE;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAErE;AAED,wBAAgB,gCAAgC,CAAC,WAAW,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAU7F;AAiBD,wBAAgB,wBAAwB,CACvC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,GAAE,2BAAgC,GACvC,4BAA4B,GAAG,SAAS,CA4D1C","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport {\n\tisAssistantThinkingBlockType,\n\tmessageHasAssistantThinkingContentBlock,\n} from \"../thinking-blocks.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { ESTIMATED_IMAGE_TOKENS, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn Boolean(message.excludeFromContext);\n\t\tcase \"custom\":\n\t\t\treturn (message as { excludeFromContext?: boolean }).excludeFromContext === true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return JSON.stringify(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? JSON.stringify(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn JSON.stringify(record);\n}\n\nexport function assistantEntryHasThinkingContentBlock(entry: CompactableTranscriptEntry): boolean {\n\treturn (\n\t\tentry.role === \"assistant\" &&\n\t\t(entry.contentBlocks.some((block) => isAssistantThinkingBlockType(block.type)) ||\n\t\t\tmessageHasAssistantThinkingContentBlock(entry.message))\n\t);\n}\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.max(1, Math.ceil(text.length / 4));\n}\n\nfunction estimateContentBlockTokens(block: unknown, text: string): number {\n\tif (block && typeof block === \"object\" && (block as { type?: unknown }).type === \"image\") {\n\t\treturn ESTIMATED_IMAGE_TOKENS;\n\t}\n\treturn estimateTextTokens(text);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, text),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nexport function hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nexport function hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nexport function hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = pathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tif (pathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(pathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(pathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(pathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: pathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"context-transcript-analysis.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAIlE,OAAO,EAGN,KAAK,YAAY,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,EAIN,KAAK,4BAA4B,EACjC,KAAK,2BAA2B,EAChC,MAAM,+BAA+B,CAAC;AA0BvC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAEvE;AAkHD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAEhE;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAEjE;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAErE;AAED,wBAAgB,gCAAgC,CAAC,WAAW,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAW7F;AAiBD,wBAAgB,wBAAwB,CACvC,WAAW,EAAE,YAAY,EAAE,EAC3B,QAAQ,EAAE,kBAAkB,EAC5B,OAAO,GAAE,2BAAgC,GACvC,4BAA4B,GAAG,SAAS,CA6D1C","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage, messageIsLlmVisible, userLikeContentBlockIsLlmVisible } from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { estimateContentBlockTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\treturn !messageIsLlmVisible(message);\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction safelySerialize(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\tif (typeof serialized === \"string\") return serialized;\n\t} catch {\n\t\t// Preserve a finite diagnostic projection for cyclic future payloads.\n\t}\n\treturn \"[unserializable content]\";\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return safelySerialize(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? safelySerialize(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn safelySerialize(record);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\tconst llmVisible =\n\t\t\t\tmessage.role === \"user\" || message.role === \"custom\"\n\t\t\t\t\t? userLikeContentBlockIsLlmVisible(block)\n\t\t\t\t\t: true;\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, llmVisible),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\tllmVisible,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nexport function hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nexport function hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nexport function hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tconst derivedPathEntries = normalizeDerivedSessionEntries(pathEntries);\n\tfor (let index = derivedPathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = derivedPathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tconst derivedPathEntries = normalizeDerivedSessionEntries(pathEntries);\n\tif (derivedPathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(derivedPathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(derivedPathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(derivedPathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: derivedPathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { createBranchSummaryMessage, createCustomMessage } from "../messages.js";
2
- import { isAssistantThinkingBlockType, messageHasAssistantThinkingContentBlock, } from "../thinking-blocks.js";
1
+ import { createBranchSummaryMessage, createCustomMessage, messageIsLlmVisible, userLikeContentBlockIsLlmVisible } from "../messages.js";
2
+ import { normalizeDerivedSessionEntries } from "../session-entry-normalization.js";
3
3
  import { buildContextDeletionFilteredPath, buildEffectiveContextDeletionFilters, } from "../session-manager.js";
4
- import { ESTIMATED_IMAGE_TOKENS, estimateTokens } from "./compaction.js";
4
+ import { estimateContentBlockTokens, estimateTokens } from "./compaction.js";
5
5
  import { CONTEXT_COMPACTION_AUTO_QUERY, } from "./context-compaction-types.js";
6
6
  import { normalizeContextCompactionParameters, normalizeContextCompactionQuery, } from "./context-compaction-strategy.js";
7
7
  function getMessageFromEntry(entry) {
@@ -11,20 +11,13 @@ function getMessageFromEntry(entry) {
11
11
  if (entry.type === "custom_message") {
12
12
  return createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp, entry.excludeFromContext);
13
13
  }
14
- if (entry.type === "branch_summary") {
14
+ if (entry.type === "branch_summary" && typeof entry.summary === "string") {
15
15
  return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);
16
16
  }
17
17
  return undefined;
18
18
  }
19
19
  export function isExcludedFromLlmContext(message) {
20
- switch (message.role) {
21
- case "bashExecution":
22
- return Boolean(message.excludeFromContext);
23
- case "custom":
24
- return message.excludeFromContext === true;
25
- default:
26
- return false;
27
- }
20
+ return !messageIsLlmVisible(message);
28
21
  }
29
22
  function getContextEligibleMessageFromEntry(entry) {
30
23
  const message = getMessageFromEntry(entry);
@@ -32,11 +25,22 @@ function getContextEligibleMessageFromEntry(entry) {
32
25
  return undefined;
33
26
  return message;
34
27
  }
28
+ function safelySerialize(value) {
29
+ try {
30
+ const serialized = JSON.stringify(value);
31
+ if (typeof serialized === "string")
32
+ return serialized;
33
+ }
34
+ catch {
35
+ // Preserve a finite diagnostic projection for cyclic future payloads.
36
+ }
37
+ return "[unserializable content]";
38
+ }
35
39
  function textFromUnknownContent(content) {
36
40
  if (typeof content === "string")
37
41
  return content;
38
42
  if (!Array.isArray(content))
39
- return JSON.stringify(content);
43
+ return safelySerialize(content);
40
44
  return content.map((block) => textFromContentBlock(block)).join("\n");
41
45
  }
42
46
  function textFromContentBlock(block) {
@@ -50,26 +54,12 @@ function textFromContentBlock(block) {
50
54
  if (record.type === "toolCall") {
51
55
  const name = typeof record.name === "string" ? record.name : "tool";
52
56
  const id = typeof record.id === "string" ? record.id : "unknown";
53
- const args = "arguments" in record ? JSON.stringify(record.arguments) : "";
57
+ const args = "arguments" in record ? safelySerialize(record.arguments) : "";
54
58
  return `toolCall ${id} ${name} ${args}`.trim();
55
59
  }
56
60
  if (record.type === "image")
57
61
  return "[image]";
58
- return JSON.stringify(record);
59
- }
60
- export function assistantEntryHasThinkingContentBlock(entry) {
61
- return (entry.role === "assistant" &&
62
- (entry.contentBlocks.some((block) => isAssistantThinkingBlockType(block.type)) ||
63
- messageHasAssistantThinkingContentBlock(entry.message)));
64
- }
65
- function estimateTextTokens(text) {
66
- return Math.max(1, Math.ceil(text.length / 4));
67
- }
68
- function estimateContentBlockTokens(block, text) {
69
- if (block && typeof block === "object" && block.type === "image") {
70
- return ESTIMATED_IMAGE_TOKENS;
71
- }
72
- return estimateTextTokens(text);
62
+ return safelySerialize(record);
73
63
  }
74
64
  function getToolCallIdFromBlock(block) {
75
65
  if (!block || typeof block !== "object")
@@ -98,13 +88,17 @@ function contentBlocksForEntry(entryId, message, protectedEntry, existingDeleted
98
88
  ? (block.type)
99
89
  : "unknown";
100
90
  const text = textFromContentBlock(block);
91
+ const llmVisible = message.role === "user" || message.role === "custom"
92
+ ? userLikeContentBlockIsLlmVisible(block)
93
+ : true;
101
94
  return {
102
95
  entryId,
103
96
  blockIndex,
104
97
  type,
105
98
  text,
106
- tokenEstimate: estimateContentBlockTokens(block, text),
99
+ tokenEstimate: estimateContentBlockTokens(block, llmVisible),
107
100
  protected: protectedEntry,
101
+ llmVisible,
108
102
  toolCallId: getToolCallIdFromBlock(block),
109
103
  };
110
104
  })
@@ -145,8 +139,9 @@ export function hasFailedBashExecution(message) {
145
139
  return message.role === "bashExecution" && typeof message.exitCode === "number" && message.exitCode !== 0;
146
140
  }
147
141
  export function autoDetectContextCompactionQuery(pathEntries) {
148
- for (let index = pathEntries.length - 1; index >= 0; index--) {
149
- const entry = pathEntries[index];
142
+ const derivedPathEntries = normalizeDerivedSessionEntries(pathEntries);
143
+ for (let index = derivedPathEntries.length - 1; index >= 0; index--) {
144
+ const entry = derivedPathEntries[index];
150
145
  if (entry.type === "context_compaction")
151
146
  continue;
152
147
  const message = getContextEligibleMessageFromEntry(entry);
@@ -176,12 +171,13 @@ function isProtectedEntry(entry, message, recentEntryIds) {
176
171
  return false;
177
172
  }
178
173
  export function prepareContextCompaction(pathEntries, settings, options = {}) {
179
- if (pathEntries.length === 0)
174
+ const derivedPathEntries = normalizeDerivedSessionEntries(pathEntries);
175
+ if (derivedPathEntries.length === 0)
180
176
  return undefined;
181
- const effectiveDeletionFilters = buildEffectiveContextDeletionFilters(pathEntries);
182
- const filteredPathEntries = buildContextDeletionFilteredPath(pathEntries, effectiveDeletionFilters);
177
+ const effectiveDeletionFilters = buildEffectiveContextDeletionFilters(derivedPathEntries);
178
+ const filteredPathEntries = buildContextDeletionFilteredPath(derivedPathEntries, effectiveDeletionFilters);
183
179
  const parameters = normalizeContextCompactionParameters({ ...settings, ...options }, autoDetectContextCompactionQuery(filteredPathEntries));
184
- const rawEntryById = new Map(pathEntries.map((entry) => [entry.id, entry]));
180
+ const rawEntryById = new Map(derivedPathEntries.map((entry) => [entry.id, entry]));
185
181
  const messageEntryIds = filteredPathEntries
186
182
  .filter((entry) => entry.type !== "context_compaction" && getContextEligibleMessageFromEntry(entry) !== undefined)
187
183
  .map((entry) => entry.id);
@@ -218,7 +214,7 @@ export function prepareContextCompaction(pathEntries, settings, options = {}) {
218
214
  if (entries.length < 2)
219
215
  return undefined;
220
216
  return {
221
- branchEntries: pathEntries,
217
+ branchEntries: derivedPathEntries,
222
218
  parameters,
223
219
  transcript: {
224
220
  entries,
@@ -1 +1 @@
1
- {"version":3,"file":"context-transcript-analysis.js","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACjF,OAAO,EACN,4BAA4B,EAC5B,uCAAuC,GACvC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACN,gCAAgC,EAChC,oCAAoC,GAEpC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EACN,6BAA6B,GAK7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,oCAAoC,EACpC,+BAA+B,GAC/B,MAAM,kCAAkC,CAAC;AAE1C,SAAS,mBAAmB,CAAC,KAAmB;IAC/C,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC,OAAO,CAAC;IACtB,CAAC;IACD,I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age } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport {\n\tisAssistantThinkingBlockType,\n\tmessageHasAssistantThinkingContentBlock,\n} from \"../thinking-blocks.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { ESTIMATED_IMAGE_TOKENS, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn Boolean(message.excludeFromContext);\n\t\tcase \"custom\":\n\t\t\treturn (message as { excludeFromContext?: boolean }).excludeFromContext === true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return JSON.stringify(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? JSON.stringify(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn JSON.stringify(record);\n}\n\nexport function assistantEntryHasThinkingContentBlock(entry: CompactableTranscriptEntry): boolean {\n\treturn (\n\t\tentry.role === \"assistant\" &&\n\t\t(entry.contentBlocks.some((block) => isAssistantThinkingBlockType(block.type)) ||\n\t\t\tmessageHasAssistantThinkingContentBlock(entry.message))\n\t);\n}\n\nfunction estimateTextTokens(text: string): number {\n\treturn Math.max(1, Math.ceil(text.length / 4));\n}\n\nfunction estimateContentBlockTokens(block: unknown, text: string): number {\n\tif (block && typeof block === \"object\" && (block as { type?: unknown }).type === \"image\") {\n\t\treturn ESTIMATED_IMAGE_TOKENS;\n\t}\n\treturn estimateTextTokens(text);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, text),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nexport function hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nexport function hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nexport function hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tfor (let index = pathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = pathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tif (pathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(pathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(pathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(pathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: pathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"context-transcript-analysis.js","sourceRoot":"","sources":["../../../src/core/compaction/context-transcript-analysis.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,gCAAgC,EAAE,MAAM,gBAAgB,CAAC;AACxI,OAAO,EAAE,8BAA8B,EAAE,MAAM,mCAAmC,CAAC;AACnF,OAAO,EACN,gCAAgC,EAChC,oCAAoC,GAEpC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,0BAA0B,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC7E,OAAO,EACN,6BAA6B,GAK7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACN,oCAAoC,EACpC,+BAA+B,GAC/B,MAAM,kCAAkC,CAAC;AAE1C,SAAS,mBAAmB,CAAC,KAAmB;IAC/C,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC,OAAO,CAAC;IACtB,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB,EAAE,CAAC;QACrC,OAAO,mBAAmB,CACzB,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,SAAS,EACf,KAAK,CAAC,kBAAkB,CACxB,CAAC;IACH,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC1E,OAAO,0BAA0B,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACjF,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CA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AC;SAC3C,CAAC,CAAC;IACJ,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzC,OAAO;QACN,aAAa,EAAE,kBAAkB;QACjC,UAAU;QACV,UAAU,EAAE;YACX,OAAO;YACP,iBAAiB,EAAE,CAAC,GAAG,iBAAiB,CAAC;YACzC,YAAY,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC;YAC9E,QAAQ;YACR,UAAU;SACV;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { createBranchSummaryMessage, createCustomMessage, messageIsLlmVisible, userLikeContentBlockIsLlmVisible } from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport {\n\tbuildContextDeletionFilteredPath,\n\tbuildEffectiveContextDeletionFilters,\n\ttype SessionEntry,\n} from \"../session-manager.ts\";\nimport type { CompactionSettings } from \"./compaction.ts\";\nimport { estimateContentBlockTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCONTEXT_COMPACTION_AUTO_QUERY,\n\ttype CompactableContentBlock,\n\ttype CompactableTranscriptEntry,\n\ttype ContextCompactionPreparation,\n\ttype ContextCompactionRunOptions,\n} from \"./context-compaction-types.ts\";\nimport {\n\tnormalizeContextCompactionParameters,\n\tnormalizeContextCompactionQuery,\n} from \"./context-compaction-strategy.ts\";\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") {\n\t\treturn entry.message;\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nexport function isExcludedFromLlmContext(message: AgentMessage): boolean {\n\treturn !messageIsLlmVisible(message);\n}\n\nfunction getContextEligibleMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tconst message = getMessageFromEntry(entry);\n\tif (!message || isExcludedFromLlmContext(message)) return undefined;\n\treturn message;\n}\n\nfunction safelySerialize(value: unknown): string {\n\ttry {\n\t\tconst serialized = JSON.stringify(value);\n\t\tif (typeof serialized === \"string\") return serialized;\n\t} catch {\n\t\t// Preserve a finite diagnostic projection for cyclic future payloads.\n\t}\n\treturn \"[unserializable content]\";\n}\n\nfunction textFromUnknownContent(content: unknown): string {\n\tif (typeof content === \"string\") return content;\n\tif (!Array.isArray(content)) return safelySerialize(content);\n\treturn content.map((block) => textFromContentBlock(block)).join(\"\\n\");\n}\n\nfunction textFromContentBlock(block: unknown): string {\n\tif (!block || typeof block !== \"object\") return String(block);\n\tconst record = block as Record<string, unknown>;\n\tif (record.type === \"text\" && typeof record.text === \"string\") return record.text;\n\tif (record.type === \"thinking\" && typeof record.thinking === \"string\") return record.thinking;\n\tif (record.type === \"toolCall\") {\n\t\tconst name = typeof record.name === \"string\" ? record.name : \"tool\";\n\t\tconst id = typeof record.id === \"string\" ? record.id : \"unknown\";\n\t\tconst args = \"arguments\" in record ? safelySerialize(record.arguments) : \"\";\n\t\treturn `toolCall ${id} ${name} ${args}`.trim();\n\t}\n\tif (record.type === \"image\") return \"[image]\";\n\treturn safelySerialize(record);\n}\n\nfunction getToolCallIdFromBlock(block: unknown): string | undefined {\n\tif (!block || typeof block !== \"object\") return undefined;\n\tconst record = block as Record<string, unknown>;\n\tif (record.type !== \"toolCall\") return undefined;\n\treturn typeof record.id === \"string\" ? record.id : undefined;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst callId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof callId === \"string\" ? callId : undefined;\n}\n\nfunction contentBlocksForEntry(\n\tentryId: string,\n\tmessage: AgentMessage,\n\tprotectedEntry: boolean,\n\texistingDeletedBlocks: ReadonlySet<number> | undefined,\n): CompactableContentBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\tif (!Array.isArray(content)) return [];\n\treturn content\n\t\t.map((block, blockIndex): CompactableContentBlock | undefined => {\n\t\t\tif (existingDeletedBlocks?.has(blockIndex)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst type =\n\t\t\t\tblock && typeof block === \"object\" && typeof (block as { type?: unknown }).type === \"string\"\n\t\t\t\t\t? ((block as { type: string }).type)\n\t\t\t\t\t: \"unknown\";\n\t\t\tconst text = textFromContentBlock(block);\n\t\t\tconst llmVisible =\n\t\t\t\tmessage.role === \"user\" || message.role === \"custom\"\n\t\t\t\t\t? userLikeContentBlockIsLlmVisible(block)\n\t\t\t\t\t: true;\n\t\t\treturn {\n\t\t\t\tentryId,\n\t\t\t\tblockIndex,\n\t\t\t\ttype,\n\t\t\t\ttext,\n\t\t\t\ttokenEstimate: estimateContentBlockTokens(block, llmVisible),\n\t\t\t\tprotected: protectedEntry,\n\t\t\t\tllmVisible,\n\t\t\t\ttoolCallId: getToolCallIdFromBlock(block),\n\t\t\t};\n\t\t})\n\t\t.filter((block): block is CompactableContentBlock => block !== undefined);\n}\n\nfunction messageText(message: AgentMessage): string {\n\tswitch (message.role) {\n\t\tcase \"bashExecution\":\n\t\t\treturn `Ran ${message.command}\\n${message.output}`;\n\t\tcase \"branchSummary\":\n\t\t\treturn message.summary;\n\t\tcase \"custom\":\n\t\tcase \"toolResult\":\n\t\tcase \"user\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"assistant\":\n\t\t\treturn textFromUnknownContent(message.content);\n\t\tcase \"compactionSummary\":\n\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage union\n\t\t\t// after summary compaction was removed; surface its archival summary text.\n\t\t\treturn message.summary;\n\t\tdefault: {\n\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here instead\n\t\t\t// of silently degrading to an empty string.\n\t\t\tconst _exhaustiveCheck: never = message;\n\t\t\tvoid _exhaustiveCheck;\n\t\t\treturn \"\";\n\t\t}\n\t}\n}\n\nexport function hasAssistantError(message: AgentMessage): boolean {\n\treturn message.role === \"assistant\" && (message as AssistantMessage).stopReason === \"error\";\n}\n\nexport function hasToolResultError(message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && (message as { isError?: unknown }).isError === true;\n}\n\nexport function hasFailedBashExecution(message: AgentMessage): boolean {\n\treturn message.role === \"bashExecution\" && typeof message.exitCode === \"number\" && message.exitCode !== 0;\n}\n\nexport function autoDetectContextCompactionQuery(pathEntries: readonly SessionEntry[]): string {\n\tconst derivedPathEntries = normalizeDerivedSessionEntries(pathEntries);\n\tfor (let index = derivedPathEntries.length - 1; index >= 0; index--) {\n\t\tconst entry = derivedPathEntries[index];\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text.length > 0) return normalizeContextCompactionQuery(text, CONTEXT_COMPACTION_AUTO_QUERY);\n\t}\n\treturn CONTEXT_COMPACTION_AUTO_QUERY;\n}\n\nfunction isProtectedEntry(\n\tentry: SessionEntry,\n\tmessage: AgentMessage,\n\trecentEntryIds: ReadonlySet<string>,\n): boolean {\n\tif (recentEntryIds.has(entry.id)) return true;\n\tif (message.role === \"user\") return true;\n\tif (message.role === \"custom\") return true;\n\tif (message.role === \"branchSummary\") return true;\n\tif (hasAssistantError(message) || hasToolResultError(message)) return true;\n\tif (hasFailedBashExecution(message)) return true;\n\tif (entry.type === \"branch_summary\") return true;\n\treturn false;\n}\n\nexport function prepareContextCompaction(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: ContextCompactionRunOptions = {},\n): ContextCompactionPreparation | undefined {\n\tconst derivedPathEntries = normalizeDerivedSessionEntries(pathEntries);\n\tif (derivedPathEntries.length === 0) return undefined;\n\n\tconst effectiveDeletionFilters = buildEffectiveContextDeletionFilters(derivedPathEntries);\n\tconst filteredPathEntries = buildContextDeletionFilteredPath(derivedPathEntries, effectiveDeletionFilters);\n\tconst parameters = normalizeContextCompactionParameters(\n\t\t{ ...settings, ...options },\n\t\tautoDetectContextCompactionQuery(filteredPathEntries),\n\t);\n\tconst rawEntryById = new Map(derivedPathEntries.map((entry) => [entry.id, entry]));\n\tconst messageEntryIds = filteredPathEntries\n\t\t.filter((entry) => entry.type !== \"context_compaction\" && getContextEligibleMessageFromEntry(entry) !== undefined)\n\t\t.map((entry) => entry.id);\n\tconst recentEntryIds = new Set(parameters.preserve_recent > 0 ? messageEntryIds.slice(-parameters.preserve_recent) : []);\n\tconst protectedEntryIds = new Set<string>();\n\tconst entries: CompactableTranscriptEntry[] = [];\n\n\tfor (const entry of filteredPathEntries) {\n\t\tif (entry.type === \"context_compaction\") continue;\n\t\tconst message = getContextEligibleMessageFromEntry(entry);\n\t\tif (!message) continue;\n\t\tconst rawEntry = rawEntryById.get(entry.id) ?? entry;\n\t\tconst protectedEntry = isProtectedEntry(entry, message, recentEntryIds);\n\t\tif (protectedEntry) protectedEntryIds.add(entry.id);\n\t\tconst rawMessage = getContextEligibleMessageFromEntry(rawEntry) ?? message;\n\t\tconst contentBlocks = contentBlocksForEntry(\n\t\t\tentry.id,\n\t\t\trawMessage,\n\t\t\tprotectedEntry,\n\t\t\teffectiveDeletionFilters.deletedContentBlocks.get(entry.id),\n\t\t);\n\t\tconst toolCallIds = contentBlocks.map((block) => block.toolCallId).filter((id): id is string => id !== undefined);\n\t\tconst text = contentBlocks.length > 0 ? contentBlocks.map((block) => block.text).join(\"\\n\") : messageText(message);\n\t\tentries.push({\n\t\t\tentryId: entry.id,\n\t\t\tentryType: entry.type,\n\t\t\trole: message.role,\n\t\t\ttext,\n\t\t\ttokenEstimate: estimateTokens(message),\n\t\t\tprotected: protectedEntry,\n\t\t\tcontentBlocks,\n\t\t\tmessage,\n\t\t\ttoolCallIds,\n\t\t\ttoolResultFor: getToolResultCallId(message),\n\t\t});\n\t}\n\n\tif (entries.length < 2) return undefined;\n\n\treturn {\n\t\tbranchEntries: derivedPathEntries,\n\t\tparameters,\n\t\ttranscript: {\n\t\t\tentries,\n\t\t\tprotectedEntryIds: [...protectedEntryIds],\n\t\t\ttokensBefore: entries.reduce((total, entry) => total + entry.tokenEstimate, 0),\n\t\t\tsettings,\n\t\t\tparameters,\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-model-synthesis.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-synthesis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAyD,KAAK,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAa7H,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,mBAAmB,EAAE,GAAG,EAAE,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,kBAAkB,CAAC,GAAG,SAAS,CAkB3H;AAqBD,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,oBAAoB,CAM7F;AAED,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,EACjD,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,EAChC,QAAQ,EAAE,oBAAoB,GAC5B,KAAK,CAAC,GAAG,CAAC,EAAE,CA4Bd","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { COPILOT_CATALOG_HEADERS, DEFAULT_COPILOT_API_BASE_URL, type CopilotModelContext } from \"./copilot-model-catalog.ts\";\nimport { withContextWindowOptions } from \"./context-window.ts\";\n\nconst GITHUB_COPILOT_PROVIDER = \"github-copilot\";\nconst ENDPOINT_API_PREFERENCE = [\n\t[\"/v1/messages\", \"anthropic-messages\"],\n\t[\"/responses\", \"openai-responses\"],\n\t[\"/chat/completions\", \"openai-completions\"],\n] as const satisfies readonly (readonly [string, Api])[];\n\nconst ZERO_COST: Model<Api>[\"cost\"] = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\nconst ADAPTIVE_THINKING_LEVEL_MAP: Model<Api>[\"thinkingLevelMap\"] = { minimal: \"low\", xhigh: \"max\" };\n\nexport interface CopilotModelTemplate {\n\tbaseUrl: string;\n\theaders?: Record<string, string>;\n}\n\nexport function copilotThinkingLevelMapFor(entry: CopilotModelContext, api: Api): Model<Api>[\"thinkingLevelMap\"] | undefined {\n\tconst advertised = entry.supports?.reasoningEffortLevels;\n\tif (!advertised || advertised.length === 0) {\n\t\treturn entry.supports?.adaptiveThinking ? ADAPTIVE_THINKING_LEVEL_MAP : undefined;\n\t}\n\n\tconst levels = new Set(advertised);\n\tconst map: Model<Api>[\"thinkingLevelMap\"] = {\n\t\tminimal: levels.has(\"minimal\") ? \"minimal\" : null,\n\t\tlow: levels.has(\"low\") ? \"low\" : null,\n\t\tmedium: levels.has(\"medium\") ? \"medium\" : null,\n\t\thigh: levels.has(\"high\") ? \"high\" : null,\n\t};\n\tif (levels.has(\"none\")) map.off = \"none\";\n\telse if (api !== \"anthropic-messages\" || !entry.supports?.adaptiveThinking) map.off = null;\n\tif (levels.has(\"xhigh\")) map.xhigh = \"xhigh\";\n\telse if (levels.has(\"max\") && entry.supports?.adaptiveThinking) map.xhigh = \"max\";\n\treturn map;\n}\n\nfunction mapCopilotApi(entry: CopilotModelContext): Api | undefined {\n\tconst endpoints = new Set(entry.supportedEndpoints ?? []);\n\treturn ENDPOINT_API_PREFERENCE.find(([endpoint]) => endpoints.has(endpoint))?.[1];\n}\n\nfunction hasReasoning(entry: CopilotModelContext): boolean {\n\treturn Boolean(\n\t\tentry.supports?.reasoningEffort || entry.supports?.adaptiveThinking || entry.supports?.minThinkingBudget || entry.supports?.maxThinkingBudget,\n\t);\n}\n\nfunction canSynthesizeCopilotModel(id: string, entry: CopilotModelContext): boolean {\n\tif (id.includes(\"/\")) return false;\n\tif (entry.modelPickerEnabled !== true) return false;\n\tif (entry.type !== \"chat\") return false;\n\tif (entry.policyState?.toLowerCase() === \"disabled\") return false;\n\treturn mapCopilotApi(entry) !== undefined;\n}\n\nexport function copilotTemplateFromModels(models: readonly Model<Api>[]): CopilotModelTemplate {\n\tconst sibling = models.find((model) => model.provider === GITHUB_COPILOT_PROVIDER);\n\treturn {\n\t\tbaseUrl: sibling?.baseUrl ?? DEFAULT_COPILOT_API_BASE_URL,\n\t\theaders: sibling?.headers ?? COPILOT_CATALOG_HEADERS,\n\t};\n}\n\nexport function synthesizeCopilotCatalogModels(\n\tcatalog: ReadonlyMap<string, CopilotModelContext>,\n\texistingIds: ReadonlySet<string>,\n\ttemplate: CopilotModelTemplate,\n): Model<Api>[] {\n\tconst synthesized: Model<Api>[] = [];\n\tfor (const [id, entry] of catalog) {\n\t\tif (existingIds.has(id) || !canSynthesizeCopilotModel(id, entry)) continue;\n\t\tconst api = mapCopilotApi(entry);\n\t\tif (!api) continue;\n\t\tlet model: Model<Api> = {\n\t\t\tid,\n\t\t\tname: entry.displayName ?? id,\n\t\t\tapi,\n\t\t\tprovider: GITHUB_COPILOT_PROVIDER,\n\t\t\tbaseUrl: template.baseUrl,\n\t\t\theaders: template.headers,\n\t\t\treasoning: hasReasoning(entry),\n\t\t\tthinkingLevelMap: copilotThinkingLevelMapFor(entry, api),\n\t\t\tcompat: entry.supports?.adaptiveThinking ? ({ forceAdaptiveThinking: true } as Model<Api>[\"compat\"]) : undefined,\n\t\t\tinput: entry.supports?.vision ? [\"text\", \"image\"] : [\"text\"],\n\t\t\tcost: ZERO_COST,\n\t\t\tmaxInputTokens: entry.maxInputTokens,\n\t\t\tcontextWindow: entry.contextWindow,\n\t\t\tmaxTokens: entry.maxTokens ?? entry.limits?.maxOutputTokens ?? entry.maxInputTokens ?? entry.contextWindow,\n\t\t};\n\t\tif (entry.contextWindowOptions && entry.contextWindowOptions.length > 1) {\n\t\t\tmodel = withContextWindowOptions(model, entry.contextWindowOptions);\n\t\t}\n\t\tsynthesized.push(model);\n\t}\n\treturn synthesized;\n}\n"]}
1
+ {"version":3,"file":"copilot-model-synthesis.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-synthesis.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAyD,KAAK,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAa7H,MAAM,WAAW,oBAAoB;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,mBAAmB,EAAE,GAAG,EAAE,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,kBAAkB,CAAC,GAAG,SAAS,CAmB3H;AAqBD,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,oBAAoB,CAM7F;AAED,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,EACjD,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,EAChC,QAAQ,EAAE,oBAAoB,GAC5B,KAAK,CAAC,GAAG,CAAC,EAAE,CA4Bd","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { COPILOT_CATALOG_HEADERS, DEFAULT_COPILOT_API_BASE_URL, type CopilotModelContext } from \"./copilot-model-catalog.ts\";\nimport { withContextWindowOptions } from \"./context-window.ts\";\n\nconst GITHUB_COPILOT_PROVIDER = \"github-copilot\";\nconst ENDPOINT_API_PREFERENCE = [\n\t[\"/v1/messages\", \"anthropic-messages\"],\n\t[\"/responses\", \"openai-responses\"],\n\t[\"/chat/completions\", \"openai-completions\"],\n] as const satisfies readonly (readonly [string, Api])[];\n\nconst ZERO_COST: Model<Api>[\"cost\"] = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\nconst ADAPTIVE_THINKING_LEVEL_MAP: Model<Api>[\"thinkingLevelMap\"] = { minimal: \"low\", xhigh: \"max\", max: \"max\" };\n\nexport interface CopilotModelTemplate {\n\tbaseUrl: string;\n\theaders?: Record<string, string>;\n}\n\nexport function copilotThinkingLevelMapFor(entry: CopilotModelContext, api: Api): Model<Api>[\"thinkingLevelMap\"] | undefined {\n\tconst advertised = entry.supports?.reasoningEffortLevels;\n\tif (!advertised || advertised.length === 0) {\n\t\treturn entry.supports?.adaptiveThinking ? ADAPTIVE_THINKING_LEVEL_MAP : undefined;\n\t}\n\n\tconst levels = new Set(advertised);\n\tconst map: Model<Api>[\"thinkingLevelMap\"] = {\n\t\tminimal: levels.has(\"minimal\") ? \"minimal\" : null,\n\t\tlow: levels.has(\"low\") ? \"low\" : null,\n\t\tmedium: levels.has(\"medium\") ? \"medium\" : null,\n\t\thigh: levels.has(\"high\") ? \"high\" : null,\n\t};\n\tif (levels.has(\"none\")) map.off = \"none\";\n\telse if (api !== \"anthropic-messages\" || !entry.supports?.adaptiveThinking) map.off = null;\n\tif (levels.has(\"xhigh\")) map.xhigh = \"xhigh\";\n\telse if (levels.has(\"max\") && entry.supports?.adaptiveThinking) map.xhigh = \"max\";\n\tif (levels.has(\"max\")) map.max = \"max\";\n\treturn map;\n}\n\nfunction mapCopilotApi(entry: CopilotModelContext): Api | undefined {\n\tconst endpoints = new Set(entry.supportedEndpoints ?? []);\n\treturn ENDPOINT_API_PREFERENCE.find(([endpoint]) => endpoints.has(endpoint))?.[1];\n}\n\nfunction hasReasoning(entry: CopilotModelContext): boolean {\n\treturn Boolean(\n\t\tentry.supports?.reasoningEffort || entry.supports?.adaptiveThinking || entry.supports?.minThinkingBudget || entry.supports?.maxThinkingBudget,\n\t);\n}\n\nfunction canSynthesizeCopilotModel(id: string, entry: CopilotModelContext): boolean {\n\tif (id.includes(\"/\")) return false;\n\tif (entry.modelPickerEnabled !== true) return false;\n\tif (entry.type !== \"chat\") return false;\n\tif (entry.policyState?.toLowerCase() === \"disabled\") return false;\n\treturn mapCopilotApi(entry) !== undefined;\n}\n\nexport function copilotTemplateFromModels(models: readonly Model<Api>[]): CopilotModelTemplate {\n\tconst sibling = models.find((model) => model.provider === GITHUB_COPILOT_PROVIDER);\n\treturn {\n\t\tbaseUrl: sibling?.baseUrl ?? DEFAULT_COPILOT_API_BASE_URL,\n\t\theaders: sibling?.headers ?? COPILOT_CATALOG_HEADERS,\n\t};\n}\n\nexport function synthesizeCopilotCatalogModels(\n\tcatalog: ReadonlyMap<string, CopilotModelContext>,\n\texistingIds: ReadonlySet<string>,\n\ttemplate: CopilotModelTemplate,\n): Model<Api>[] {\n\tconst synthesized: Model<Api>[] = [];\n\tfor (const [id, entry] of catalog) {\n\t\tif (existingIds.has(id) || !canSynthesizeCopilotModel(id, entry)) continue;\n\t\tconst api = mapCopilotApi(entry);\n\t\tif (!api) continue;\n\t\tlet model: Model<Api> = {\n\t\t\tid,\n\t\t\tname: entry.displayName ?? id,\n\t\t\tapi,\n\t\t\tprovider: GITHUB_COPILOT_PROVIDER,\n\t\t\tbaseUrl: template.baseUrl,\n\t\t\theaders: template.headers,\n\t\t\treasoning: hasReasoning(entry),\n\t\t\tthinkingLevelMap: copilotThinkingLevelMapFor(entry, api),\n\t\t\tcompat: entry.supports?.adaptiveThinking ? ({ forceAdaptiveThinking: true } as Model<Api>[\"compat\"]) : undefined,\n\t\t\tinput: entry.supports?.vision ? [\"text\", \"image\"] : [\"text\"],\n\t\t\tcost: ZERO_COST,\n\t\t\tmaxInputTokens: entry.maxInputTokens,\n\t\t\tcontextWindow: entry.contextWindow,\n\t\t\tmaxTokens: entry.maxTokens ?? entry.limits?.maxOutputTokens ?? entry.maxInputTokens ?? entry.contextWindow,\n\t\t};\n\t\tif (entry.contextWindowOptions && entry.contextWindowOptions.length > 1) {\n\t\t\tmodel = withContextWindowOptions(model, entry.contextWindowOptions);\n\t\t}\n\t\tsynthesized.push(model);\n\t}\n\treturn synthesized;\n}\n"]}
@@ -7,7 +7,7 @@ const ENDPOINT_API_PREFERENCE = [
7
7
  ["/chat/completions", "openai-completions"],
8
8
  ];
9
9
  const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
10
- const ADAPTIVE_THINKING_LEVEL_MAP = { minimal: "low", xhigh: "max" };
10
+ const ADAPTIVE_THINKING_LEVEL_MAP = { minimal: "low", xhigh: "max", max: "max" };
11
11
  export function copilotThinkingLevelMapFor(entry, api) {
12
12
  const advertised = entry.supports?.reasoningEffortLevels;
13
13
  if (!advertised || advertised.length === 0) {
@@ -28,6 +28,8 @@ export function copilotThinkingLevelMapFor(entry, api) {
28
28
  map.xhigh = "xhigh";
29
29
  else if (levels.has("max") && entry.supports?.adaptiveThinking)
30
30
  map.xhigh = "max";
31
+ if (levels.has("max"))
32
+ map.max = "max";
31
33
  return map;
32
34
  }
33
35
  function mapCopilotApi(entry) {
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-model-synthesis.js","sourceRoot":"","sources":["../../src/core/copilot-model-synthesis.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAA4B,MAAM,4BAA4B,CAAC;AAC7H,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,MAAM,uBAAuB,GAAG,gBAAgB,CAAC;AACjD,M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KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YAC5D,IAAI,EAAE,SAAS;YACf,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,SAAS,EAAE,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,MAAM,EAAE,eAAe,IAAI,KAAK,CAAC,cAAc,IAAI,KAAK,CAAC,aAAa;SAC1G,CAAC;QACF,IAAI,KAAK,CAAC,oBAAoB,IAAI,KAAK,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzE,KAAK,GAAG,wBAAwB,CAAC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,CAAC;QACrE,CAAC;QACD,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { COPILOT_CATALOG_HEADERS, DEFAULT_COPILOT_API_BASE_URL, type CopilotModelContext } from \"./copilot-model-catalog.ts\";\nimport { withContextWindowOptions } from \"./context-window.ts\";\n\nconst GITHUB_COPILOT_PROVIDER = \"github-copilot\";\nconst ENDPOINT_API_PREFERENCE = [\n\t[\"/v1/messages\", \"anthropic-messages\"],\n\t[\"/responses\", \"openai-responses\"],\n\t[\"/chat/completions\", \"openai-completions\"],\n] as const satisfies readonly (readonly [string, Api])[];\n\nconst ZERO_COST: Model<Api>[\"cost\"] = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\nconst ADAPTIVE_THINKING_LEVEL_MAP: Model<Api>[\"thinkingLevelMap\"] = { minimal: \"low\", xhigh: \"max\" };\n\nexport interface CopilotModelTemplate {\n\tbaseUrl: string;\n\theaders?: Record<string, string>;\n}\n\nexport function copilotThinkingLevelMapFor(entry: CopilotModelContext, api: Api): Model<Api>[\"thinkingLevelMap\"] | undefined {\n\tconst advertised = entry.supports?.reasoningEffortLevels;\n\tif (!advertised || advertised.length === 0) {\n\t\treturn entry.supports?.adaptiveThinking ? ADAPTIVE_THINKING_LEVEL_MAP : undefined;\n\t}\n\n\tconst levels = new Set(advertised);\n\tconst map: Model<Api>[\"thinkingLevelMap\"] = {\n\t\tminimal: levels.has(\"minimal\") ? \"minimal\" : null,\n\t\tlow: levels.has(\"low\") ? \"low\" : null,\n\t\tmedium: levels.has(\"medium\") ? \"medium\" : null,\n\t\thigh: levels.has(\"high\") ? \"high\" : null,\n\t};\n\tif (levels.has(\"none\")) map.off = \"none\";\n\telse if (api !== \"anthropic-messages\" || !entry.supports?.adaptiveThinking) map.off = null;\n\tif (levels.has(\"xhigh\")) map.xhigh = \"xhigh\";\n\telse if (levels.has(\"max\") && entry.supports?.adaptiveThinking) map.xhigh = \"max\";\n\treturn map;\n}\n\nfunction mapCopilotApi(entry: CopilotModelContext): Api | undefined {\n\tconst endpoints = new Set(entry.supportedEndpoints ?? []);\n\treturn ENDPOINT_API_PREFERENCE.find(([endpoint]) => endpoints.has(endpoint))?.[1];\n}\n\nfunction hasReasoning(entry: CopilotModelContext): boolean {\n\treturn Boolean(\n\t\tentry.supports?.reasoningEffort || entry.supports?.adaptiveThinking || entry.supports?.minThinkingBudget || entry.supports?.maxThinkingBudget,\n\t);\n}\n\nfunction canSynthesizeCopilotModel(id: string, entry: CopilotModelContext): boolean {\n\tif (id.includes(\"/\")) return false;\n\tif (entry.modelPickerEnabled !== true) return false;\n\tif (entry.type !== \"chat\") return false;\n\tif (entry.policyState?.toLowerCase() === \"disabled\") return false;\n\treturn mapCopilotApi(entry) !== undefined;\n}\n\nexport function copilotTemplateFromModels(models: readonly Model<Api>[]): CopilotModelTemplate {\n\tconst sibling = models.find((model) => model.provider === GITHUB_COPILOT_PROVIDER);\n\treturn {\n\t\tbaseUrl: sibling?.baseUrl ?? DEFAULT_COPILOT_API_BASE_URL,\n\t\theaders: sibling?.headers ?? COPILOT_CATALOG_HEADERS,\n\t};\n}\n\nexport function synthesizeCopilotCatalogModels(\n\tcatalog: ReadonlyMap<string, CopilotModelContext>,\n\texistingIds: ReadonlySet<string>,\n\ttemplate: CopilotModelTemplate,\n): Model<Api>[] {\n\tconst synthesized: Model<Api>[] = [];\n\tfor (const [id, entry] of catalog) {\n\t\tif (existingIds.has(id) || !canSynthesizeCopilotModel(id, entry)) continue;\n\t\tconst api = mapCopilotApi(entry);\n\t\tif (!api) continue;\n\t\tlet model: Model<Api> = {\n\t\t\tid,\n\t\t\tname: entry.displayName ?? id,\n\t\t\tapi,\n\t\t\tprovider: GITHUB_COPILOT_PROVIDER,\n\t\t\tbaseUrl: template.baseUrl,\n\t\t\theaders: template.headers,\n\t\t\treasoning: hasReasoning(entry),\n\t\t\tthinkingLevelMap: copilotThinkingLevelMapFor(entry, api),\n\t\t\tcompat: entry.supports?.adaptiveThinking ? ({ forceAdaptiveThinking: true } as Model<Api>[\"compat\"]) : undefined,\n\t\t\tinput: entry.supports?.vision ? [\"text\", \"image\"] : [\"text\"],\n\t\t\tcost: ZERO_COST,\n\t\t\tmaxInputTokens: entry.maxInputTokens,\n\t\t\tcontextWindow: entry.contextWindow,\n\t\t\tmaxTokens: entry.maxTokens ?? entry.limits?.maxOutputTokens ?? entry.maxInputTokens ?? entry.contextWindow,\n\t\t};\n\t\tif (entry.contextWindowOptions && entry.contextWindowOptions.length > 1) {\n\t\t\tmodel = withContextWindowOptions(model, entry.contextWindowOptions);\n\t\t}\n\t\tsynthesized.push(model);\n\t}\n\treturn synthesized;\n}\n"]}
1
+ {"version":3,"file":"copilot-model-synthesis.js","sourceRoot":"","sources":["../../src/core/copilot-model-synthesis.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAA4B,MAAM,4BAA4B,CAAC;AAC7H,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,MAAM,uBA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;YACxD,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAE,EAAE,qBAAqB,EAAE,IAAI,EAA2B,CAAC,CAAC,CAAC,SAAS;YAChH,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YAC5D,IAAI,EAAE,SAAS;YACf,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,aAAa,EAAE,KAAK,CAAC,aAAa;YAClC,SAAS,EAAE,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,MAAM,EAAE,eAAe,IAAI,KAAK,CAAC,cAAc,IAAI,KAAK,CAAC,aAAa;SAC1G,CAAC;QACF,IAAI,KAAK,CAAC,oBAAoB,IAAI,KAAK,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzE,KAAK,GAAG,wBAAwB,CAAC,KAAK,EAAE,KAAK,CAAC,oBAAoB,CAAC,CAAC;QACrE,CAAC;QACD,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai/compat\";\nimport { COPILOT_CATALOG_HEADERS, DEFAULT_COPILOT_API_BASE_URL, type CopilotModelContext } from \"./copilot-model-catalog.ts\";\nimport { withContextWindowOptions } from \"./context-window.ts\";\n\nconst GITHUB_COPILOT_PROVIDER = \"github-copilot\";\nconst ENDPOINT_API_PREFERENCE = [\n\t[\"/v1/messages\", \"anthropic-messages\"],\n\t[\"/responses\", \"openai-responses\"],\n\t[\"/chat/completions\", \"openai-completions\"],\n] as const satisfies readonly (readonly [string, Api])[];\n\nconst ZERO_COST: Model<Api>[\"cost\"] = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\nconst ADAPTIVE_THINKING_LEVEL_MAP: Model<Api>[\"thinkingLevelMap\"] = { minimal: \"low\", xhigh: \"max\", max: \"max\" };\n\nexport interface CopilotModelTemplate {\n\tbaseUrl: string;\n\theaders?: Record<string, string>;\n}\n\nexport function copilotThinkingLevelMapFor(entry: CopilotModelContext, api: Api): Model<Api>[\"thinkingLevelMap\"] | undefined {\n\tconst advertised = entry.supports?.reasoningEffortLevels;\n\tif (!advertised || advertised.length === 0) {\n\t\treturn entry.supports?.adaptiveThinking ? ADAPTIVE_THINKING_LEVEL_MAP : undefined;\n\t}\n\n\tconst levels = new Set(advertised);\n\tconst map: Model<Api>[\"thinkingLevelMap\"] = {\n\t\tminimal: levels.has(\"minimal\") ? \"minimal\" : null,\n\t\tlow: levels.has(\"low\") ? \"low\" : null,\n\t\tmedium: levels.has(\"medium\") ? \"medium\" : null,\n\t\thigh: levels.has(\"high\") ? \"high\" : null,\n\t};\n\tif (levels.has(\"none\")) map.off = \"none\";\n\telse if (api !== \"anthropic-messages\" || !entry.supports?.adaptiveThinking) map.off = null;\n\tif (levels.has(\"xhigh\")) map.xhigh = \"xhigh\";\n\telse if (levels.has(\"max\") && entry.supports?.adaptiveThinking) map.xhigh = \"max\";\n\tif (levels.has(\"max\")) map.max = \"max\";\n\treturn map;\n}\n\nfunction mapCopilotApi(entry: CopilotModelContext): Api | undefined {\n\tconst endpoints = new Set(entry.supportedEndpoints ?? []);\n\treturn ENDPOINT_API_PREFERENCE.find(([endpoint]) => endpoints.has(endpoint))?.[1];\n}\n\nfunction hasReasoning(entry: CopilotModelContext): boolean {\n\treturn Boolean(\n\t\tentry.supports?.reasoningEffort || entry.supports?.adaptiveThinking || entry.supports?.minThinkingBudget || entry.supports?.maxThinkingBudget,\n\t);\n}\n\nfunction canSynthesizeCopilotModel(id: string, entry: CopilotModelContext): boolean {\n\tif (id.includes(\"/\")) return false;\n\tif (entry.modelPickerEnabled !== true) return false;\n\tif (entry.type !== \"chat\") return false;\n\tif (entry.policyState?.toLowerCase() === \"disabled\") return false;\n\treturn mapCopilotApi(entry) !== undefined;\n}\n\nexport function copilotTemplateFromModels(models: readonly Model<Api>[]): CopilotModelTemplate {\n\tconst sibling = models.find((model) => model.provider === GITHUB_COPILOT_PROVIDER);\n\treturn {\n\t\tbaseUrl: sibling?.baseUrl ?? DEFAULT_COPILOT_API_BASE_URL,\n\t\theaders: sibling?.headers ?? COPILOT_CATALOG_HEADERS,\n\t};\n}\n\nexport function synthesizeCopilotCatalogModels(\n\tcatalog: ReadonlyMap<string, CopilotModelContext>,\n\texistingIds: ReadonlySet<string>,\n\ttemplate: CopilotModelTemplate,\n): Model<Api>[] {\n\tconst synthesized: Model<Api>[] = [];\n\tfor (const [id, entry] of catalog) {\n\t\tif (existingIds.has(id) || !canSynthesizeCopilotModel(id, entry)) continue;\n\t\tconst api = mapCopilotApi(entry);\n\t\tif (!api) continue;\n\t\tlet model: Model<Api> = {\n\t\t\tid,\n\t\t\tname: entry.displayName ?? id,\n\t\t\tapi,\n\t\t\tprovider: GITHUB_COPILOT_PROVIDER,\n\t\t\tbaseUrl: template.baseUrl,\n\t\t\theaders: template.headers,\n\t\t\treasoning: hasReasoning(entry),\n\t\t\tthinkingLevelMap: copilotThinkingLevelMapFor(entry, api),\n\t\t\tcompat: entry.supports?.adaptiveThinking ? ({ forceAdaptiveThinking: true } as Model<Api>[\"compat\"]) : undefined,\n\t\t\tinput: entry.supports?.vision ? [\"text\", \"image\"] : [\"text\"],\n\t\t\tcost: ZERO_COST,\n\t\t\tmaxInputTokens: entry.maxInputTokens,\n\t\t\tcontextWindow: entry.contextWindow,\n\t\t\tmaxTokens: entry.maxTokens ?? entry.limits?.maxOutputTokens ?? entry.maxInputTokens ?? entry.contextWindow,\n\t\t};\n\t\tif (entry.contextWindowOptions && entry.contextWindowOptions.length > 1) {\n\t\t\tmodel = withContextWindowOptions(model, entry.contextWindowOptions);\n\t\t}\n\t\tsynthesized.push(model);\n\t}\n\treturn synthesized;\n}\n"]}
@@ -48,13 +48,8 @@ export interface ProviderModelConfig {
48
48
  thinkingLevelMap?: Model<Api>["thinkingLevelMap"];
49
49
  /** Supported input types. */
50
50
  input: ("text" | "image")[];
51
- /** Cost per token (for tracking, can be 0). */
52
- cost: {
53
- input: number;
54
- output: number;
55
- cacheRead: number;
56
- cacheWrite: number;
57
- };
51
+ /** Request pricing, including optional request-wide long-context tiers. */
52
+ cost: Model<Api>["cost"];
58
53
  /** Default/effective context window size in tokens. */
59
54
  contextWindow: number;
60
55
  /** Selectable context-window sizes in tokens; omit when the model has only one supported window. */
@@ -1 +1 @@
1
- {"version":3,"file":"provider-types.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/provider-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,2BAA2B,EAC3B,OAAO,EACP,KAAK,EACL,gBAAgB,EAChB,mBAAmB,EACnB,mBAAmB,EACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,0EAA0E;AAC1E,MAAM,WAAW,cAAc;IAC9B,2CAA2C;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mGAAmG;IACnG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,0EAA0E;IAC1E,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,qDAAqD;IACrD,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,mBAAmB,KAAK,2BAA2B,CAAC;IACnH,6CAA6C;IAC7C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,4EAA4E;IAC5E,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,uFAAuF;IACvF,MAAM,CAAC,EAAE,mBAAmB,EAAE,CAAC;IAC/B,+FAA+F;IAC/F,KAAK,CAAC,E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;IAClB,qCAAqC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,qCAAqC;IACrC,MAAM,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC;CAC9B;AAED,oFAAoF;AACpF,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tSimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\nimport type { ExtensionAPI } from \"./api-types.ts\";\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key or environment variable name. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Optional: modify models for this provider (e.g., update baseUrl based on credentials). */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Cost per token (for tracking, can be 0). */\n\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t/** Default/effective context window size in tokens. */\n\tcontextWindow: number;\n\t/** Selectable context-window sizes in tokens; omit when the model has only one supported window. */\n\tcontextWindowOptions?: readonly number[];\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;\n"]}
1
+ {"version":3,"file":"provider-types.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/provider-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,2BAA2B,EAC3B,OAAO,EACP,KAAK,EACL,gBAAgB,EAChB,mBAAmB,EACnB,mBAAmB,EACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,0EAA0E;AAC1E,MAAM,WAAW,cAAc;IAC9B,2CAA2C;IAC3C,IAAI,CA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CAAC,EAAE,MAAM,CAAC;IACjB,oDAAoD;IACpD,SAAS,EAAE,OAAO,CAAC;IACnB,iGAAiG;IACjG,gBAAgB,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,kBAAkB,CAAC,CAAC;IAClD,6BAA6B;IAC7B,KAAK,EAAE,CAAC,MAAM,GAAG,OAAO,CAAC,EAAE,CAAC;IAC5B,2EAA2E;IAC3E,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;IACzB,uDAAuD;IACvD,aAAa,EAAE,MAAM,CAAC;IACtB,oGAAoG;IACpG,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,6BAA6B;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,qCAAqC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,qCAAqC;IACrC,MAAM,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC;CAC9B;AAED,oFAAoF;AACpF,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tSimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\nimport type { ExtensionAPI } from \"./api-types.ts\";\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key or environment variable name. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Optional: modify models for this provider (e.g., update baseUrl based on credentials). */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Request pricing, including optional request-wide long-context tiers. */\n\tcost: Model<Api>[\"cost\"];\n\t/** Default/effective context window size in tokens. */\n\tcontextWindow: number;\n\t/** Selectable context-window sizes in tokens; omit when the model has only one supported window. */\n\tcontextWindowOptions?: readonly number[];\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"provider-types.js","sourceRoot":"","sources":["../../../src/core/extensions/provider-types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tSimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\nimport type { ExtensionAPI } from \"./api-types.ts\";\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key or environment variable name. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Optional: modify models for this provider (e.g., update baseUrl based on credentials). */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Cost per token (for tracking, can be 0). */\n\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t/** Default/effective context window size in tokens. */\n\tcontextWindow: number;\n\t/** Selectable context-window sizes in tokens; omit when the model has only one supported window. */\n\tcontextWindowOptions?: readonly number[];\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;\n"]}
1
+ {"version":3,"file":"provider-types.js","sourceRoot":"","sources":["../../../src/core/extensions/provider-types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tApi,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tSimpleStreamOptions,\n} from \"@earendil-works/pi-ai/compat\";\nimport type { ExtensionAPI } from \"./api-types.ts\";\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key or environment variable name. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Optional: modify models for this provider (e.g., update baseUrl based on credentials). */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Request pricing, including optional request-wide long-context tiers. */\n\tcost: Model<Api>[\"cost\"];\n\t/** Default/effective context window size in tokens. */\n\tcontextWindow: number;\n\t/** Selectable context-window sizes in tokens; omit when the model has only one supported window. */\n\tcontextWindowOptions?: readonly number[];\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;\n"]}
@@ -48,6 +48,15 @@ declare module "@earendil-works/pi-agent-core" {
48
48
  branchSummary: BranchSummaryMessage;
49
49
  }
50
50
  }
51
+ /** Normalize lax JavaScript/legacy message input before it reaches history or providers. */
52
+ export declare function normalizeMessageContent<T extends AgentMessage>(message: T): T;
53
+ export declare function userLikeContentBlockIsLlmVisible(block: unknown): boolean;
54
+ /** Whether user/custom content survives provider conversion as a visible input. */
55
+ export declare function userLikeContentIsLlmVisible(content: unknown, deletedBlockIndexes?: ReadonlySet<number>): boolean;
56
+ /** Whether an Atomic message emits an LLM-visible user-like turn boundary. */
57
+ export declare function messageStartsLlmUserTurn(message: AgentMessage, deletedBlockIndexes?: ReadonlySet<number>): boolean;
58
+ /** Whether an Atomic message survives conversion into provider-visible context. */
59
+ export declare function messageIsLlmVisible(message: AgentMessage, deletedBlockIndexes?: ReadonlySet<number>): boolean;
51
60
  /**
52
61
  * Convert a BashExecutionMessage to user message text for LLM context.
53
62
  */
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEvF,eAAO,MAAM,qBAAqB,iGAGjC,CAAC;AAEF,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,M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AChB,OAAO,EAAE,OAAO,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,EACjB,kBAAkB,CAAC,EAAE,OAAO,GAC1B,aAAa,CAWf;AAoBD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAuBtE;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,EAAE,CAiDhE","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n): CustomMessage {\n\tconst message: CustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent,\n\t\tdisplay,\n\t\tdetails,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\nfunction collectAssistantToolCallIds(message: Message): Set<string> {\n\tconst content = (message as { content?: unknown }).content;\n\tconst ids = new Set<string>();\n\tif (!Array.isArray(content)) return ids;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\") ids.add(candidate.id);\n\t}\n\treturn ids;\n}\n\nfunction getToolResultCallId(message: Message): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\nexport function repairOrphanToolResults(messages: Message[]): Message[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet changed = false;\n\tconst repaired: Message[] = [];\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tallowedToolCallIds = collectAssistantToolCallIds(message);\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId)) {\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\trepaired.push(message);\n\t}\n\treturn changed ? repaired : messages;\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((m): Message | undefined => {\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\t// Skip messages excluded from context (!! prefix)\n\t\t\t\t\tif (m.excludeFromContext) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif ((m as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true) return undefined;\n\t\t\t\t\tconst content = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\":\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\t// Legacy summary-compaction message type retained in the upstream AgentMessage\n\t\t\t\t\t// union. Summary compaction was removed; these archival entries are inert and are\n\t\t\t\t\t// never injected into active LLM context.\n\t\t\t\t\treturn undefined;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: adding a new AgentMessage role must fail the build here\n\t\t\t\t\t// instead of silently mapping to undefined and dropping the message from context.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(converted);\n}\n"]}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEvF,eAAO,MAAM,qBAAqB,iGAGj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OAAO,EAAE,OAAO,EAChB,mBAAmB,GAAE,WAAW,CAAC,MAAM,CAAqB,GAC1D,OAAO,CAIT;AAED,8EAA8E;AAC9E,wBAAgB,wBAAwB,CACvC,OAAO,EAAE,YAAY,EACrB,mBAAmB,GAAE,WAAW,CAAC,MAAM,CAAqB,GAC1D,OAAO,CAkBT;AAED,mFAAmF;AACnF,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,YAAY,EACrB,mBAAmB,GAAE,WAAW,CAAC,MAAM,CAAqB,GAC1D,OAAO,CAGT;AA0BD;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,oBAAoB,GAAG,MAAM,CAgBrE;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,oBAAoB,CAOnH;AAED,wDAAwD;AACxD,wBAAgB,mBAAmB,CAClC,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,EACjB,kBAAkB,CAAC,EAAE,OAAO,GAC1B,aAAa,CAWf;AAoBD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAuBtE;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,EAAE,CA+ChE","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/** Normalize lax JavaScript/legacy message input before it reaches history or providers. */\nexport function normalizeMessageContent<T extends AgentMessage>(message: T): T {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn message.content == null ? ({ ...message, content: [] } as T) : message;\n\t\tdefault:\n\t\t\treturn message;\n\t}\n}\n\nexport function userLikeContentBlockIsLlmVisible(block: unknown): boolean {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; text?: unknown };\n\tif (candidate.type === \"image\") return true;\n\tif (candidate.type === \"text\") return typeof candidate.text === \"string\" && candidate.text.trim().length > 0;\n\t// Future provider-supported blocks must fail visible; only malformed/untyped blocks fail closed.\n\treturn typeof candidate.type === \"string\" && candidate.type.trim().length > 0;\n}\n\n/** Whether user/custom content survives provider conversion as a visible input. */\nexport function userLikeContentIsLlmVisible(\n\tcontent: unknown,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (typeof content === \"string\") return content.trim().length > 0;\n\tif (!Array.isArray(content)) return false;\n\treturn content.some((block, index) => !deletedBlockIndexes.has(index) && userLikeContentBlockIsLlmVisible(block));\n}\n\n/** Whether an Atomic message emits an LLM-visible user-like turn boundary. */\nexport function messageStartsLlmUserTurn(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn userLikeContentIsLlmVisible(message.content, deletedBlockIndexes);\n\t\tcase \"custom\":\n\t\t\treturn (\n\t\t\t\t(message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext !== true &&\n\t\t\t\tuserLikeContentIsLlmVisible(message.content, deletedBlockIndexes)\n\t\t\t);\n\t\tcase \"branchSummary\":\n\t\t\t// Empty summaries are omitted by session reconstruction. Whitespace is\n\t\t\t// visible because the branch-summary wrapper itself is non-whitespace.\n\t\t\treturn typeof message.summary === \"string\" && message.summary.length > 0;\n\t\tcase \"bashExecution\":\n\t\t\treturn message.excludeFromContext !== true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Whether an Atomic message survives conversion into provider-visible context. */\nexport function messageIsLlmVisible(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (message.role === \"assistant\" || message.role === \"toolResult\") return true;\n\treturn messageStartsLlmUserTurn(message, deletedBlockIndexes);\n}\n\n/** Filter invalid user-like blocks only in transient provider-bound content. */\nfunction filterUserLikeContentBlocks(content: unknown[]): unknown[] {\n\treturn content.filter(userLikeContentBlockIsLlmVisible);\n}\n\n/** Normalize raw blocks only in the transient LLM-compatible message returned by convertToLlm. */\nfunction normalizeRawRedactedThinking(message: AgentMessage): AgentMessage {\n\tif (message.role !== \"assistant\" || !Array.isArray(message.content)) return message;\n\tlet changed = false;\n\tconst content = message.content.map((block) => {\n\t\tif (!block || typeof block !== \"object\") return block;\n\t\tconst candidate = block as { type?: unknown; data?: unknown };\n\t\tif (candidate.type !== \"redacted_thinking\" || typeof candidate.data !== \"string\") return block;\n\t\tchanged = true;\n\t\treturn {\n\t\t\ttype: \"thinking\" as const,\n\t\t\tthinking: \"\",\n\t\t\tthinkingSignature: candidate.data,\n\t\t\tredacted: true,\n\t\t};\n\t});\n\treturn changed ? ({ ...message, content } as AgentMessage) : message;\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n): CustomMessage {\n\tconst message: CustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent: content ?? [],\n\t\tdisplay,\n\t\tdetails,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\nfunction collectAssistantToolCallIds(message: Message): Set<string> {\n\tconst content = (message as { content?: unknown }).content;\n\tconst ids = new Set<string>();\n\tif (!Array.isArray(content)) return ids;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\") ids.add(candidate.id);\n\t}\n\treturn ids;\n}\n\nfunction getToolResultCallId(message: Message): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\nexport function repairOrphanToolResults(messages: Message[]): Message[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet changed = false;\n\tconst repaired: Message[] = [];\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tallowedToolCallIds = collectAssistantToolCallIds(message);\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId)) {\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\trepaired.push(message);\n\t}\n\treturn changed ? repaired : messages;\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((rawMessage): Message | undefined => {\n\t\t\tconst m = normalizeRawRedactedThinking(normalizeMessageContent(rawMessage));\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tconst content = typeof m.content === \"string\"\n\t\t\t\t\t\t? [{ type: \"text\" as const, text: m.content }]\n\t\t\t\t\t\t: filterUserLikeContentBlocks(m.content) as Message[\"content\"];\n\t\t\t\t\treturn { role: \"user\", content, timestamp: m.timestamp } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tif (!Array.isArray(m.content)) return m;\n\t\t\t\t\treturn { ...m, content: filterUserLikeContentBlocks(m.content) } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\t// Legacy generated summaries remain archival and never enter active LLM context.\n\t\t\t\t\treturn undefined;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: new AgentMessage roles must define provider conversion explicitly.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(converted);\n}\n"]}