@letta-ai/letta-code 0.30.2 → 0.30.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (813) hide show
  1. package/dist/app-server-client.cjs +9 -136
  2. package/dist/app-server-client.cjs.map +3 -3
  3. package/dist/app-server-client.js +9 -136
  4. package/dist/app-server-client.js.map +3 -3
  5. package/dist/channels-slack.js +96 -1
  6. package/dist/channels-slack.js.map +4 -3
  7. package/dist/gateway-core.js +2190 -0
  8. package/dist/gateway-core.js.map +16 -0
  9. package/dist/mcp-client.js +2 -2
  10. package/dist/mcp-client.js.map +1 -1
  11. package/dist/types/agent/approval-execution.d.ts +92 -0
  12. package/dist/types/agent/approval-execution.d.ts.map +1 -0
  13. package/dist/types/agent/approval-result-normalization.d.ts +20 -0
  14. package/dist/types/agent/approval-result-normalization.d.ts.map +1 -0
  15. package/dist/types/agent/available-models.d.ts +65 -0
  16. package/dist/types/agent/available-models.d.ts.map +1 -0
  17. package/dist/types/agent/client-skills.d.ts +55 -0
  18. package/dist/types/agent/client-skills.d.ts.map +1 -0
  19. package/dist/types/agent/context.d.ts +50 -0
  20. package/dist/types/agent/context.d.ts.map +1 -0
  21. package/dist/types/agent/memory-filesystem.d.ts +149 -0
  22. package/dist/types/agent/memory-filesystem.d.ts.map +1 -0
  23. package/dist/types/agent/memory-git-config-lock.d.ts +27 -0
  24. package/dist/types/agent/memory-git-config-lock.d.ts.map +1 -0
  25. package/dist/types/agent/memory-git-hooks.d.ts +45 -0
  26. package/dist/types/agent/memory-git-hooks.d.ts.map +1 -0
  27. package/dist/types/agent/memory-git-signing.d.ts +14 -0
  28. package/dist/types/agent/memory-git-signing.d.ts.map +1 -0
  29. package/dist/types/agent/memory-git.d.ts +213 -0
  30. package/dist/types/agent/memory-git.d.ts.map +1 -0
  31. package/dist/types/agent/memory-runtime.d.ts +12 -0
  32. package/dist/types/agent/memory-runtime.d.ts.map +1 -0
  33. package/dist/types/agent/message.d.ts +100 -0
  34. package/dist/types/agent/message.d.ts.map +1 -0
  35. package/dist/types/agent/model-handles.d.ts +17 -0
  36. package/dist/types/agent/model-handles.d.ts.map +1 -0
  37. package/dist/types/agent/model.d.ts +167 -0
  38. package/dist/types/agent/model.d.ts.map +1 -0
  39. package/dist/types/agent/modify.d.ts +142 -0
  40. package/dist/types/agent/modify.d.ts.map +1 -0
  41. package/dist/types/agent/personality-default-files.d.ts +17 -0
  42. package/dist/types/agent/personality-default-files.d.ts.map +1 -0
  43. package/dist/types/agent/skill-sources.d.ts +15 -0
  44. package/dist/types/agent/skill-sources.d.ts.map +1 -0
  45. package/dist/types/agent/skills.d.ts +116 -0
  46. package/dist/types/agent/skills.d.ts.map +1 -0
  47. package/dist/types/agent/subagent-state.d.ts +166 -0
  48. package/dist/types/agent/subagent-state.d.ts.map +1 -0
  49. package/dist/types/agent/subagents/context-budget.d.ts +14 -0
  50. package/dist/types/agent/subagents/context-budget.d.ts.map +1 -0
  51. package/dist/types/agent/subagents/index.d.ts +89 -0
  52. package/dist/types/agent/subagents/index.d.ts.map +1 -0
  53. package/dist/types/agent/subagents/manager.d.ts +47 -0
  54. package/dist/types/agent/subagents/manager.d.ts.map +1 -0
  55. package/dist/types/agent/subagents/sandbox.d.ts +69 -0
  56. package/dist/types/agent/subagents/sandbox.d.ts.map +1 -0
  57. package/dist/types/agent/subagents/subagent-launcher.d.ts +80 -0
  58. package/dist/types/agent/subagents/subagent-launcher.d.ts.map +1 -0
  59. package/dist/types/agent/subagents/subagent-model.d.ts +40 -0
  60. package/dist/types/agent/subagents/subagent-model.d.ts.map +1 -0
  61. package/dist/types/agent/subagents/subagent-stream.d.ts +35 -0
  62. package/dist/types/agent/subagents/subagent-stream.d.ts.map +1 -0
  63. package/dist/types/agent/system-prompt-resolution.d.ts +40 -0
  64. package/dist/types/agent/system-prompt-resolution.d.ts.map +1 -0
  65. package/dist/types/agent/system-prompt-versioning.d.ts +44 -0
  66. package/dist/types/agent/system-prompt-versioning.d.ts.map +1 -0
  67. package/dist/types/agent/turn-recovery-policy.d.ts +126 -0
  68. package/dist/types/agent/turn-recovery-policy.d.ts.map +1 -0
  69. package/dist/types/app-server-client.d.ts +12 -22
  70. package/dist/types/app-server-client.d.ts.map +1 -1
  71. package/dist/types/auth/oauth-refresh.d.ts +5 -0
  72. package/dist/types/auth/oauth-refresh.d.ts.map +1 -0
  73. package/dist/types/auth/oauth.d.ts +73 -0
  74. package/dist/types/auth/oauth.d.ts.map +1 -0
  75. package/dist/types/backend/api/client.d.ts +13 -0
  76. package/dist/types/backend/api/client.d.ts.map +1 -0
  77. package/dist/types/backend/api/conversations.d.ts +28 -0
  78. package/dist/types/backend/api/conversations.d.ts.map +1 -0
  79. package/dist/types/backend/api/generate.d.ts +2 -0
  80. package/dist/types/backend/api/generate.d.ts.map +1 -0
  81. package/dist/types/backend/api/health.d.ts +8 -0
  82. package/dist/types/backend/api/health.d.ts.map +1 -0
  83. package/dist/types/backend/api/http-headers.d.ts +10 -0
  84. package/dist/types/backend/api/http-headers.d.ts.map +1 -0
  85. package/dist/types/backend/api/memfs-git-proxy.d.ts +35 -0
  86. package/dist/types/backend/api/memfs-git-proxy.d.ts.map +1 -0
  87. package/dist/types/backend/api/metadata.d.ts +13 -0
  88. package/dist/types/backend/api/metadata.d.ts.map +1 -0
  89. package/dist/types/backend/api/providers.d.ts +27 -0
  90. package/dist/types/backend/api/providers.d.ts.map +1 -0
  91. package/dist/types/backend/api/request.d.ts +28 -0
  92. package/dist/types/backend/api/request.d.ts.map +1 -0
  93. package/dist/types/backend/backend-mode.d.ts +13 -0
  94. package/dist/types/backend/backend-mode.d.ts.map +1 -0
  95. package/dist/types/backend/backend.d.ts +153 -0
  96. package/dist/types/backend/backend.d.ts.map +1 -0
  97. package/dist/types/backend/dev/context-window-overflow.d.ts +2 -0
  98. package/dist/types/backend/dev/context-window-overflow.d.ts.map +1 -0
  99. package/dist/types/backend/dev/fake-headless-backend.d.ts +80 -0
  100. package/dist/types/backend/dev/fake-headless-backend.d.ts.map +1 -0
  101. package/dist/types/backend/dev/headless-backend.d.ts +3 -0
  102. package/dist/types/backend/dev/headless-backend.d.ts.map +1 -0
  103. package/dist/types/backend/dev/headless-turn-executor.d.ts +28 -0
  104. package/dist/types/backend/dev/headless-turn-executor.d.ts.map +1 -0
  105. package/dist/types/backend/dev/local-provider-errors.d.ts +13 -0
  106. package/dist/types/backend/dev/local-provider-errors.d.ts.map +1 -0
  107. package/dist/types/backend/dev/pi-api-streams.d.ts +10 -0
  108. package/dist/types/backend/dev/pi-api-streams.d.ts.map +1 -0
  109. package/dist/types/backend/dev/pi-image-elision.d.ts +15 -0
  110. package/dist/types/backend/dev/pi-image-elision.d.ts.map +1 -0
  111. package/dist/types/backend/dev/pi-llama-cpp-provider.d.ts +18 -0
  112. package/dist/types/backend/dev/pi-llama-cpp-provider.d.ts.map +1 -0
  113. package/dist/types/backend/dev/pi-lmstudio-provider.d.ts +16 -0
  114. package/dist/types/backend/dev/pi-lmstudio-provider.d.ts.map +1 -0
  115. package/dist/types/backend/dev/pi-local-endpoint-provider.d.ts +77 -0
  116. package/dist/types/backend/dev/pi-local-endpoint-provider.d.ts.map +1 -0
  117. package/dist/types/backend/dev/pi-mod-provider.d.ts +30 -0
  118. package/dist/types/backend/dev/pi-mod-provider.d.ts.map +1 -0
  119. package/dist/types/backend/dev/pi-model-factory.d.ts +53 -0
  120. package/dist/types/backend/dev/pi-model-factory.d.ts.map +1 -0
  121. package/dist/types/backend/dev/pi-models-runtime.d.ts +120 -0
  122. package/dist/types/backend/dev/pi-models-runtime.d.ts.map +1 -0
  123. package/dist/types/backend/dev/pi-oauth.d.ts +17 -0
  124. package/dist/types/backend/dev/pi-oauth.d.ts.map +1 -0
  125. package/dist/types/backend/dev/pi-ollama-provider.d.ts +20 -0
  126. package/dist/types/backend/dev/pi-ollama-provider.d.ts.map +1 -0
  127. package/dist/types/backend/dev/pi-provider-mod-registry.d.ts +25 -0
  128. package/dist/types/backend/dev/pi-provider-mod-registry.d.ts.map +1 -0
  129. package/dist/types/backend/dev/pi-provider-mod-types.d.ts +66 -0
  130. package/dist/types/backend/dev/pi-provider-mod-types.d.ts.map +1 -0
  131. package/dist/types/backend/dev/pi-provider-mod-validation.d.ts +5 -0
  132. package/dist/types/backend/dev/pi-provider-mod-validation.d.ts.map +1 -0
  133. package/dist/types/backend/dev/pi-provider-registry.d.ts +65 -0
  134. package/dist/types/backend/dev/pi-provider-registry.d.ts.map +1 -0
  135. package/dist/types/backend/dev/pi-stream-adapter.d.ts +56 -0
  136. package/dist/types/backend/dev/pi-stream-adapter.d.ts.map +1 -0
  137. package/dist/types/backend/dev/provider-turn-executor.d.ts +98 -0
  138. package/dist/types/backend/dev/provider-turn-executor.d.ts.map +1 -0
  139. package/dist/types/backend/dev/registered-pi-provider-runtime.d.ts +24 -0
  140. package/dist/types/backend/dev/registered-pi-provider-runtime.d.ts.map +1 -0
  141. package/dist/types/backend/index.d.ts +2 -0
  142. package/dist/types/backend/index.d.ts.map +1 -0
  143. package/dist/types/backend/local/compaction.d.ts +56 -0
  144. package/dist/types/backend/local/compaction.d.ts.map +1 -0
  145. package/dist/types/backend/local/local-backend.d.ts +107 -0
  146. package/dist/types/backend/local/local-backend.d.ts.map +1 -0
  147. package/dist/types/backend/local/local-context-estimate.d.ts +13 -0
  148. package/dist/types/backend/local/local-context-estimate.d.ts.map +1 -0
  149. package/dist/types/backend/local/local-conversation-fork.d.ts +3 -0
  150. package/dist/types/backend/local/local-conversation-fork.d.ts.map +1 -0
  151. package/dist/types/backend/local/local-conversation-list.d.ts +8 -0
  152. package/dist/types/backend/local/local-conversation-list.d.ts.map +1 -0
  153. package/dist/types/backend/local/local-executor-factory.d.ts +21 -0
  154. package/dist/types/backend/local/local-executor-factory.d.ts.map +1 -0
  155. package/dist/types/backend/local/local-message-projection.d.ts +28 -0
  156. package/dist/types/backend/local/local-message-projection.d.ts.map +1 -0
  157. package/dist/types/backend/local/local-message.d.ts +58 -0
  158. package/dist/types/backend/local/local-message.d.ts.map +1 -0
  159. package/dist/types/backend/local/local-model-config.d.ts +44 -0
  160. package/dist/types/backend/local/local-model-config.d.ts.map +1 -0
  161. package/dist/types/backend/local/local-model-normalization.d.ts +11 -0
  162. package/dist/types/backend/local/local-model-normalization.d.ts.map +1 -0
  163. package/dist/types/backend/local/local-pi-credential-store.d.ts +19 -0
  164. package/dist/types/backend/local/local-pi-credential-store.d.ts.map +1 -0
  165. package/dist/types/backend/local/local-provider-auth-store.d.ts +85 -0
  166. package/dist/types/backend/local/local-provider-auth-store.d.ts.map +1 -0
  167. package/dist/types/backend/local/local-provider-timeout.d.ts +14 -0
  168. package/dist/types/backend/local/local-provider-timeout.d.ts.map +1 -0
  169. package/dist/types/backend/local/local-store.d.ts +215 -0
  170. package/dist/types/backend/local/local-store.d.ts.map +1 -0
  171. package/dist/types/backend/local/local-stream-chunks.d.ts +8 -0
  172. package/dist/types/backend/local/local-stream-chunks.d.ts.map +1 -0
  173. package/dist/types/backend/local/local-types.d.ts +26 -0
  174. package/dist/types/backend/local/local-types.d.ts.map +1 -0
  175. package/dist/types/backend/local/paths.d.ts +9 -0
  176. package/dist/types/backend/local/paths.d.ts.map +1 -0
  177. package/dist/types/backend/local/system-prompt-compilation.d.ts +23 -0
  178. package/dist/types/backend/local/system-prompt-compilation.d.ts.map +1 -0
  179. package/dist/types/channels/access-control.d.ts +104 -0
  180. package/dist/types/channels/access-control.d.ts.map +1 -0
  181. package/dist/types/channels/accounts.d.ts +17 -0
  182. package/dist/types/channels/accounts.d.ts.map +1 -0
  183. package/dist/types/channels/commands.d.ts +98 -0
  184. package/dist/types/channels/commands.d.ts.map +1 -0
  185. package/dist/types/channels/config.d.ts +18 -0
  186. package/dist/types/channels/config.d.ts.map +1 -0
  187. package/dist/types/channels/credential-store.d.ts +21 -0
  188. package/dist/types/channels/credential-store.d.ts.map +1 -0
  189. package/dist/types/channels/custom/adapter.d.ts +3 -0
  190. package/dist/types/channels/custom/adapter.d.ts.map +1 -0
  191. package/dist/types/channels/custom/plugin.d.ts +10 -0
  192. package/dist/types/channels/custom/plugin.d.ts.map +1 -0
  193. package/dist/types/channels/discord/account-display.d.ts +2 -0
  194. package/dist/types/channels/discord/account-display.d.ts.map +1 -0
  195. package/dist/types/channels/discord/adapter.d.ts +3 -0
  196. package/dist/types/channels/discord/adapter.d.ts.map +1 -0
  197. package/dist/types/channels/discord/bot-policy.d.ts +19 -0
  198. package/dist/types/channels/discord/bot-policy.d.ts.map +1 -0
  199. package/dist/types/channels/discord/channel-gating.d.ts +41 -0
  200. package/dist/types/channels/discord/channel-gating.d.ts.map +1 -0
  201. package/dist/types/channels/discord/error-reply.d.ts +24 -0
  202. package/dist/types/channels/discord/error-reply.d.ts.map +1 -0
  203. package/dist/types/channels/discord/internal-types.d.ts +101 -0
  204. package/dist/types/channels/discord/internal-types.d.ts.map +1 -0
  205. package/dist/types/channels/discord/media.d.ts +47 -0
  206. package/dist/types/channels/discord/media.d.ts.map +1 -0
  207. package/dist/types/channels/discord/message-actions.d.ts +3 -0
  208. package/dist/types/channels/discord/message-actions.d.ts.map +1 -0
  209. package/dist/types/channels/discord/plugin.d.ts +3 -0
  210. package/dist/types/channels/discord/plugin.d.ts.map +1 -0
  211. package/dist/types/channels/discord/runtime.d.ts +28 -0
  212. package/dist/types/channels/discord/runtime.d.ts.map +1 -0
  213. package/dist/types/channels/discord/setup.d.ts +2 -0
  214. package/dist/types/channels/discord/setup.d.ts.map +1 -0
  215. package/dist/types/channels/discord/utils.d.ts +47 -0
  216. package/dist/types/channels/discord/utils.d.ts.map +1 -0
  217. package/dist/types/channels/feedback.d.ts +26 -0
  218. package/dist/types/channels/feedback.d.ts.map +1 -0
  219. package/dist/types/channels/gateway-core.d.ts +69 -0
  220. package/dist/types/channels/gateway-core.d.ts.map +1 -0
  221. package/dist/types/channels/inbound-debounce.d.ts +46 -0
  222. package/dist/types/channels/inbound-debounce.d.ts.map +1 -0
  223. package/dist/types/channels/interactive.d.ts +13 -0
  224. package/dist/types/channels/interactive.d.ts.map +1 -0
  225. package/dist/types/channels/lifecycle-error-report.d.ts +19 -0
  226. package/dist/types/channels/lifecycle-error-report.d.ts.map +1 -0
  227. package/dist/types/channels/message-channel-executor.d.ts +46 -0
  228. package/dist/types/channels/message-channel-executor.d.ts.map +1 -0
  229. package/dist/types/channels/message-channel-formatting.d.ts +6 -0
  230. package/dist/types/channels/message-channel-formatting.d.ts.map +1 -0
  231. package/dist/types/channels/message-channel-tool-definition.d.ts +40 -0
  232. package/dist/types/channels/message-channel-tool-definition.d.ts.map +1 -0
  233. package/dist/types/channels/message-channel-types.d.ts +46 -0
  234. package/dist/types/channels/message-channel-types.d.ts.map +1 -0
  235. package/dist/types/channels/message-tool.d.ts +15 -0
  236. package/dist/types/channels/message-tool.d.ts.map +1 -0
  237. package/dist/types/channels/pairing.d.ts +53 -0
  238. package/dist/types/channels/pairing.d.ts.map +1 -0
  239. package/dist/types/channels/pending-control-requests.d.ts +12 -0
  240. package/dist/types/channels/pending-control-requests.d.ts.map +1 -0
  241. package/dist/types/channels/plugin-registry.d.ts +9 -0
  242. package/dist/types/channels/plugin-registry.d.ts.map +1 -0
  243. package/dist/types/channels/plugin-types.d.ts +6 -2
  244. package/dist/types/channels/plugin-types.d.ts.map +1 -1
  245. package/dist/types/channels/registry-commands.d.ts +52 -0
  246. package/dist/types/channels/registry-commands.d.ts.map +1 -0
  247. package/dist/types/channels/registry-controls.d.ts +33 -0
  248. package/dist/types/channels/registry-controls.d.ts.map +1 -0
  249. package/dist/types/channels/registry-events.d.ts +27 -0
  250. package/dist/types/channels/registry-events.d.ts.map +1 -0
  251. package/dist/types/channels/registry-handlers.d.ts +46 -0
  252. package/dist/types/channels/registry-handlers.d.ts.map +1 -0
  253. package/dist/types/channels/registry-inbound.d.ts +19 -0
  254. package/dist/types/channels/registry-inbound.d.ts.map +1 -0
  255. package/dist/types/channels/registry-presentation.d.ts +20 -0
  256. package/dist/types/channels/registry-presentation.d.ts.map +1 -0
  257. package/dist/types/channels/registry-routes.d.ts +33 -0
  258. package/dist/types/channels/registry-routes.d.ts.map +1 -0
  259. package/dist/types/channels/registry.d.ts +130 -0
  260. package/dist/types/channels/registry.d.ts.map +1 -0
  261. package/dist/types/channels/restore-scope.d.ts +8 -0
  262. package/dist/types/channels/restore-scope.d.ts.map +1 -0
  263. package/dist/types/channels/routing.d.ts +74 -0
  264. package/dist/types/channels/routing.d.ts.map +1 -0
  265. package/dist/types/channels/runtime-deps.d.ts +25 -0
  266. package/dist/types/channels/runtime-deps.d.ts.map +1 -0
  267. package/dist/types/channels/schema-config.d.ts +33 -0
  268. package/dist/types/channels/schema-config.d.ts.map +1 -0
  269. package/dist/types/channels/signal/account-conflicts.d.ts +14 -0
  270. package/dist/types/channels/signal/account-conflicts.d.ts.map +1 -0
  271. package/dist/types/channels/signal/adapter.d.ts +40 -0
  272. package/dist/types/channels/signal/adapter.d.ts.map +1 -0
  273. package/dist/types/channels/signal/client.d.ts +51 -0
  274. package/dist/types/channels/signal/client.d.ts.map +1 -0
  275. package/dist/types/channels/signal/inbound.d.ts +25 -0
  276. package/dist/types/channels/signal/inbound.d.ts.map +1 -0
  277. package/dist/types/channels/signal/internal-types.d.ts +82 -0
  278. package/dist/types/channels/signal/internal-types.d.ts.map +1 -0
  279. package/dist/types/channels/signal/media.d.ts +35 -0
  280. package/dist/types/channels/signal/media.d.ts.map +1 -0
  281. package/dist/types/channels/signal/message-actions.d.ts +3 -0
  282. package/dist/types/channels/signal/message-actions.d.ts.map +1 -0
  283. package/dist/types/channels/signal/plugin.d.ts +3 -0
  284. package/dist/types/channels/signal/plugin.d.ts.map +1 -0
  285. package/dist/types/channels/signal/runtime.d.ts +14 -0
  286. package/dist/types/channels/signal/runtime.d.ts.map +1 -0
  287. package/dist/types/channels/signal/setup-runtime.d.ts +35 -0
  288. package/dist/types/channels/signal/setup-runtime.d.ts.map +1 -0
  289. package/dist/types/channels/signal/setup.d.ts +5 -0
  290. package/dist/types/channels/signal/setup.d.ts.map +1 -0
  291. package/dist/types/channels/signal/target.d.ts +21 -0
  292. package/dist/types/channels/signal/target.d.ts.map +1 -0
  293. package/dist/types/channels/slack/account-display.d.ts +2 -0
  294. package/dist/types/channels/slack/account-display.d.ts.map +1 -0
  295. package/dist/types/channels/slack/adapter.d.ts +12 -0
  296. package/dist/types/channels/slack/adapter.d.ts.map +1 -0
  297. package/dist/types/channels/slack/agent-thread-tracker.d.ts +13 -0
  298. package/dist/types/channels/slack/agent-thread-tracker.d.ts.map +1 -0
  299. package/dist/types/channels/slack/approval-controller.d.ts +14 -0
  300. package/dist/types/channels/slack/approval-controller.d.ts.map +1 -0
  301. package/dist/types/channels/slack/attachment-download.d.ts +20 -0
  302. package/dist/types/channels/slack/attachment-download.d.ts.map +1 -0
  303. package/dist/types/channels/slack/attachment-stream.d.ts +23 -0
  304. package/dist/types/channels/slack/attachment-stream.d.ts.map +1 -0
  305. package/dist/types/channels/slack/attachment-task.d.ts +37 -0
  306. package/dist/types/channels/slack/attachment-task.d.ts.map +1 -0
  307. package/dist/types/channels/slack/attachment-types.d.ts +27 -0
  308. package/dist/types/channels/slack/attachment-types.d.ts.map +1 -0
  309. package/dist/types/channels/slack/bot-policy.d.ts +25 -0
  310. package/dist/types/channels/slack/bot-policy.d.ts.map +1 -0
  311. package/dist/types/channels/slack/file-upload.d.ts +6 -0
  312. package/dist/types/channels/slack/file-upload.d.ts.map +1 -0
  313. package/dist/types/channels/slack/inbound-debounce.d.ts +16 -0
  314. package/dist/types/channels/slack/inbound-debounce.d.ts.map +1 -0
  315. package/dist/types/channels/slack/ingress-controller.d.ts +21 -0
  316. package/dist/types/channels/slack/ingress-controller.d.ts.map +1 -0
  317. package/dist/types/channels/slack/media.d.ts +63 -0
  318. package/dist/types/channels/slack/media.d.ts.map +1 -0
  319. package/dist/types/channels/slack/message-action-contract.d.ts +18 -0
  320. package/dist/types/channels/slack/message-action-contract.d.ts.map +1 -0
  321. package/dist/types/channels/slack/message-actions.d.ts +2 -0
  322. package/dist/types/channels/slack/message-actions.d.ts.map +1 -0
  323. package/dist/types/channels/slack/model-picker-blocks.d.ts +9 -0
  324. package/dist/types/channels/slack/model-picker-blocks.d.ts.map +1 -0
  325. package/dist/types/channels/slack/plugin.d.ts +3 -0
  326. package/dist/types/channels/slack/plugin.d.ts.map +1 -0
  327. package/dist/types/channels/slack/proactive-accounts.d.ts +15 -0
  328. package/dist/types/channels/slack/proactive-accounts.d.ts.map +1 -0
  329. package/dist/types/channels/slack/runtime.d.ts +6 -0
  330. package/dist/types/channels/slack/runtime.d.ts.map +1 -0
  331. package/dist/types/channels/slack/setup.d.ts +2 -0
  332. package/dist/types/channels/slack/setup.d.ts.map +1 -0
  333. package/dist/types/channels/slack/target-resolution.d.ts +52 -0
  334. package/dist/types/channels/slack/target-resolution.d.ts.map +1 -0
  335. package/dist/types/channels/slack/thread-context.d.ts +15 -0
  336. package/dist/types/channels/slack/thread-context.d.ts.map +1 -0
  337. package/dist/types/channels/slack/web-api-client.d.ts +2 -0
  338. package/dist/types/channels/slack/web-api-client.d.ts.map +1 -0
  339. package/dist/types/channels/targets.d.ts +17 -0
  340. package/dist/types/channels/targets.d.ts.map +1 -0
  341. package/dist/types/channels/telegram/account-display.d.ts +9 -0
  342. package/dist/types/channels/telegram/account-display.d.ts.map +1 -0
  343. package/dist/types/channels/telegram/adapter.d.ts +12 -0
  344. package/dist/types/channels/telegram/adapter.d.ts.map +1 -0
  345. package/dist/types/channels/telegram/debounce.d.ts +22 -0
  346. package/dist/types/channels/telegram/debounce.d.ts.map +1 -0
  347. package/dist/types/channels/telegram/internal-types.d.ts +98 -0
  348. package/dist/types/channels/telegram/internal-types.d.ts.map +1 -0
  349. package/dist/types/channels/telegram/media.d.ts +115 -0
  350. package/dist/types/channels/telegram/media.d.ts.map +1 -0
  351. package/dist/types/channels/telegram/message-actions.d.ts +3 -0
  352. package/dist/types/channels/telegram/message-actions.d.ts.map +1 -0
  353. package/dist/types/channels/telegram/plugin.d.ts +3 -0
  354. package/dist/types/channels/telegram/plugin.d.ts.map +1 -0
  355. package/dist/types/channels/telegram/runtime.d.ts +6 -0
  356. package/dist/types/channels/telegram/runtime.d.ts.map +1 -0
  357. package/dist/types/channels/telegram/setup.d.ts +14 -0
  358. package/dist/types/channels/telegram/setup.d.ts.map +1 -0
  359. package/dist/types/channels/telegram/startup-helpers.d.ts +10 -0
  360. package/dist/types/channels/telegram/startup-helpers.d.ts.map +1 -0
  361. package/dist/types/channels/telegram/typing-controller.d.ts +11 -0
  362. package/dist/types/channels/telegram/typing-controller.d.ts.map +1 -0
  363. package/dist/types/channels/telegram/utils.d.ts +43 -0
  364. package/dist/types/channels/telegram/utils.d.ts.map +1 -0
  365. package/dist/types/channels/transcription/index.d.ts +20 -0
  366. package/dist/types/channels/transcription/index.d.ts.map +1 -0
  367. package/dist/types/channels/whatsapp/adapter.d.ts +14 -0
  368. package/dist/types/channels/whatsapp/adapter.d.ts.map +1 -0
  369. package/dist/types/channels/whatsapp/identity.d.ts +29 -0
  370. package/dist/types/channels/whatsapp/identity.d.ts.map +1 -0
  371. package/dist/types/channels/whatsapp/jid.d.ts +40 -0
  372. package/dist/types/channels/whatsapp/jid.d.ts.map +1 -0
  373. package/dist/types/channels/whatsapp/lid-store.d.ts +45 -0
  374. package/dist/types/channels/whatsapp/lid-store.d.ts.map +1 -0
  375. package/dist/types/channels/whatsapp/media.d.ts +24 -0
  376. package/dist/types/channels/whatsapp/media.d.ts.map +1 -0
  377. package/dist/types/channels/whatsapp/message-actions.d.ts +3 -0
  378. package/dist/types/channels/whatsapp/message-actions.d.ts.map +1 -0
  379. package/dist/types/channels/whatsapp/plugin.d.ts +3 -0
  380. package/dist/types/channels/whatsapp/plugin.d.ts.map +1 -0
  381. package/dist/types/channels/whatsapp/runtime.d.ts +25 -0
  382. package/dist/types/channels/whatsapp/runtime.d.ts.map +1 -0
  383. package/dist/types/channels/whatsapp/session.d.ts +51 -0
  384. package/dist/types/channels/whatsapp/session.d.ts.map +1 -0
  385. package/dist/types/channels/whatsapp/setup.d.ts +2 -0
  386. package/dist/types/channels/whatsapp/setup.d.ts.map +1 -0
  387. package/dist/types/channels/whatsapp/state.d.ts +18 -0
  388. package/dist/types/channels/whatsapp/state.d.ts.map +1 -0
  389. package/dist/types/channels/xml.d.ts +32 -0
  390. package/dist/types/channels/xml.d.ts.map +1 -0
  391. package/dist/types/channels-public.d.ts +1 -1
  392. package/dist/types/channels-public.d.ts.map +1 -1
  393. package/dist/types/channels-slack.d.ts +2 -0
  394. package/dist/types/channels-slack.d.ts.map +1 -1
  395. package/dist/types/cli/helpers/accumulator.d.ts +218 -0
  396. package/dist/types/cli/helpers/accumulator.d.ts.map +1 -0
  397. package/dist/types/cli/helpers/app-urls.d.ts +29 -0
  398. package/dist/types/cli/helpers/app-urls.d.ts.map +1 -0
  399. package/dist/types/cli/helpers/chunk-log.d.ts +56 -0
  400. package/dist/types/cli/helpers/chunk-log.d.ts.map +1 -0
  401. package/dist/types/cli/helpers/compaction-utils.d.ts +9 -0
  402. package/dist/types/cli/helpers/compaction-utils.d.ts.map +1 -0
  403. package/dist/types/cli/helpers/context-tracker.d.ts +24 -0
  404. package/dist/types/cli/helpers/context-tracker.d.ts.map +1 -0
  405. package/dist/types/cli/helpers/conversation-title.d.ts +24 -0
  406. package/dist/types/cli/helpers/conversation-title.d.ts.map +1 -0
  407. package/dist/types/cli/helpers/error-context.d.ts +24 -0
  408. package/dist/types/cli/helpers/error-context.d.ts.map +1 -0
  409. package/dist/types/cli/helpers/error-formatter.d.ts +44 -0
  410. package/dist/types/cli/helpers/error-formatter.d.ts.map +1 -0
  411. package/dist/types/cli/helpers/git-context.d.ts +29 -0
  412. package/dist/types/cli/helpers/git-context.d.ts.map +1 -0
  413. package/dist/types/cli/helpers/markdown-split.d.ts +9 -0
  414. package/dist/types/cli/helpers/markdown-split.d.ts.map +1 -0
  415. package/dist/types/cli/helpers/memory-reminder.d.ts +20 -0
  416. package/dist/types/cli/helpers/memory-reminder.d.ts.map +1 -0
  417. package/dist/types/cli/helpers/reasoning-text.d.ts +2 -0
  418. package/dist/types/cli/helpers/reasoning-text.d.ts.map +1 -0
  419. package/dist/types/cli/helpers/session-context.d.ts +25 -0
  420. package/dist/types/cli/helpers/session-context.d.ts.map +1 -0
  421. package/dist/types/cli/helpers/stream-processor.d.ts +36 -0
  422. package/dist/types/cli/helpers/stream-processor.d.ts.map +1 -0
  423. package/dist/types/cli/helpers/stream.d.ts +75 -0
  424. package/dist/types/cli/helpers/stream.d.ts.map +1 -0
  425. package/dist/types/cli/helpers/system-prompt-warning.d.ts +18 -0
  426. package/dist/types/cli/helpers/system-prompt-warning.d.ts.map +1 -0
  427. package/dist/types/cli/helpers/tool-name-mapping.d.ts +84 -0
  428. package/dist/types/cli/helpers/tool-name-mapping.d.ts.map +1 -0
  429. package/dist/types/cli/helpers/unified-exec-output.d.ts +10 -0
  430. package/dist/types/cli/helpers/unified-exec-output.d.ts.map +1 -0
  431. package/dist/types/cli/helpers/zai-errors.d.ts +38 -0
  432. package/dist/types/cli/helpers/zai-errors.d.ts.map +1 -0
  433. package/dist/types/cli/mods/command-runtime.d.ts +13 -0
  434. package/dist/types/cli/mods/command-runtime.d.ts.map +1 -0
  435. package/dist/types/cli/mods/types.d.ts +2 -0
  436. package/dist/types/cli/mods/types.d.ts.map +1 -0
  437. package/dist/types/experiments/manager.d.ts +12 -0
  438. package/dist/types/experiments/manager.d.ts.map +1 -0
  439. package/dist/types/experiments/types.d.ts +14 -0
  440. package/dist/types/experiments/types.d.ts.map +1 -0
  441. package/dist/types/gateway-core.d.ts +8 -0
  442. package/dist/types/gateway-core.d.ts.map +1 -0
  443. package/dist/types/helpers/usable-directory.d.ts +9 -0
  444. package/dist/types/helpers/usable-directory.d.ts.map +1 -0
  445. package/dist/types/hooks/executor.d.ts +23 -0
  446. package/dist/types/hooks/executor.d.ts.map +1 -0
  447. package/dist/types/hooks/index.d.ts +68 -0
  448. package/dist/types/hooks/index.d.ts.map +1 -0
  449. package/dist/types/hooks/loader.d.ts +63 -0
  450. package/dist/types/hooks/loader.d.ts.map +1 -0
  451. package/dist/types/hooks/prompt-executor.d.ts +7 -0
  452. package/dist/types/hooks/prompt-executor.d.ts.map +1 -0
  453. package/dist/types/hooks/types.d.ts +370 -0
  454. package/dist/types/hooks/types.d.ts.map +1 -0
  455. package/dist/types/lsp/client.d.ts +51 -0
  456. package/dist/types/lsp/client.d.ts.map +1 -0
  457. package/dist/types/lsp/manager.d.ts +48 -0
  458. package/dist/types/lsp/manager.d.ts.map +1 -0
  459. package/dist/types/lsp/servers/index.d.ts +10 -0
  460. package/dist/types/lsp/servers/index.d.ts.map +1 -0
  461. package/dist/types/lsp/servers/python.d.ts +11 -0
  462. package/dist/types/lsp/servers/python.d.ts.map +1 -0
  463. package/dist/types/lsp/servers/typescript.d.ts +10 -0
  464. package/dist/types/lsp/servers/typescript.d.ts.map +1 -0
  465. package/dist/types/lsp/types.d.ts +145 -0
  466. package/dist/types/lsp/types.d.ts.map +1 -0
  467. package/dist/types/mods/capabilities.d.ts +9 -0
  468. package/dist/types/mods/capabilities.d.ts.map +1 -0
  469. package/dist/types/mods/context.d.ts +22 -0
  470. package/dist/types/mods/context.d.ts.map +1 -0
  471. package/dist/types/mods/conversation-handle.d.ts +14 -0
  472. package/dist/types/mods/conversation-handle.d.ts.map +1 -0
  473. package/dist/types/mods/conversation-history.d.ts +8 -0
  474. package/dist/types/mods/conversation-history.d.ts.map +1 -0
  475. package/dist/types/mods/deprecated-api.d.ts +7 -0
  476. package/dist/types/mods/deprecated-api.d.ts.map +1 -0
  477. package/dist/types/mods/disable.d.ts +9 -0
  478. package/dist/types/mods/disable.d.ts.map +1 -0
  479. package/dist/types/mods/disabled-mod-adapter.d.ts +19 -0
  480. package/dist/types/mods/disabled-mod-adapter.d.ts.map +1 -0
  481. package/dist/types/mods/event-emitter.d.ts +7 -0
  482. package/dist/types/mods/event-emitter.d.ts.map +1 -0
  483. package/dist/types/mods/file-extensions.d.ts +7 -0
  484. package/dist/types/mods/file-extensions.d.ts.map +1 -0
  485. package/dist/types/mods/mod-adapter.d.ts +32 -0
  486. package/dist/types/mods/mod-adapter.d.ts.map +1 -0
  487. package/dist/types/mods/mod-diagnostics-file.d.ts +13 -0
  488. package/dist/types/mods/mod-diagnostics-file.d.ts.map +1 -0
  489. package/dist/types/mods/mod-diagnostics.d.ts +37 -0
  490. package/dist/types/mods/mod-diagnostics.d.ts.map +1 -0
  491. package/dist/types/mods/mod-engine.d.ts +114 -0
  492. package/dist/types/mods/mod-engine.d.ts.map +1 -0
  493. package/dist/types/mods/mod-sources.d.ts +20 -0
  494. package/dist/types/mods/mod-sources.d.ts.map +1 -0
  495. package/dist/types/mods/package-manifest.d.ts +30 -0
  496. package/dist/types/mods/package-manifest.d.ts.map +1 -0
  497. package/dist/types/mods/package-registry.d.ts +81 -0
  498. package/dist/types/mods/package-registry.d.ts.map +1 -0
  499. package/dist/types/mods/paths.d.ts +7 -0
  500. package/dist/types/mods/paths.d.ts.map +1 -0
  501. package/dist/types/mods/permission-registry.d.ts +19 -0
  502. package/dist/types/mods/permission-registry.d.ts.map +1 -0
  503. package/dist/types/mods/runtime-dependencies.d.ts +3 -0
  504. package/dist/types/mods/runtime-dependencies.d.ts.map +1 -0
  505. package/dist/types/mods/tool-registry.d.ts +17 -0
  506. package/dist/types/mods/tool-registry.d.ts.map +1 -0
  507. package/dist/types/mods/turn-start-cancel.d.ts +4 -0
  508. package/dist/types/mods/turn-start-cancel.d.ts.map +1 -0
  509. package/dist/types/mods/types.d.ts +507 -0
  510. package/dist/types/mods/types.d.ts.map +1 -0
  511. package/dist/types/permissions/analyzer.d.ts +15 -0
  512. package/dist/types/permissions/analyzer.d.ts.map +1 -0
  513. package/dist/types/permissions/canonical.d.ts +5 -0
  514. package/dist/types/permissions/canonical.d.ts.map +1 -0
  515. package/dist/types/permissions/checker.d.ts +50 -0
  516. package/dist/types/permissions/checker.d.ts.map +1 -0
  517. package/dist/types/permissions/cli-permissions-instance.d.ts +12 -0
  518. package/dist/types/permissions/cli-permissions-instance.d.ts.map +1 -0
  519. package/dist/types/permissions/cli.d.ts +59 -0
  520. package/dist/types/permissions/cli.d.ts.map +1 -0
  521. package/dist/types/permissions/cross-agent-guard.d.ts +74 -0
  522. package/dist/types/permissions/cross-agent-guard.d.ts.map +1 -0
  523. package/dist/types/permissions/loader.d.ts +29 -0
  524. package/dist/types/permissions/loader.d.ts.map +1 -0
  525. package/dist/types/permissions/matcher.d.ts +43 -0
  526. package/dist/types/permissions/matcher.d.ts.map +1 -0
  527. package/dist/types/permissions/memory-paths.d.ts +23 -0
  528. package/dist/types/permissions/memory-paths.d.ts.map +1 -0
  529. package/dist/types/permissions/read-only-shell.d.ts +18 -0
  530. package/dist/types/permissions/read-only-shell.d.ts.map +1 -0
  531. package/dist/types/permissions/rule-normalization.d.ts +3 -0
  532. package/dist/types/permissions/rule-normalization.d.ts.map +1 -0
  533. package/dist/types/permissions/sandbox-gate.d.ts +39 -0
  534. package/dist/types/permissions/sandbox-gate.d.ts.map +1 -0
  535. package/dist/types/permissions/session.d.ts +27 -0
  536. package/dist/types/permissions/session.d.ts.map +1 -0
  537. package/dist/types/permissions/shell-analysis.d.ts +43 -0
  538. package/dist/types/permissions/shell-analysis.d.ts.map +1 -0
  539. package/dist/types/permissions/shell-command-normalization.d.ts +4 -0
  540. package/dist/types/permissions/shell-command-normalization.d.ts.map +1 -0
  541. package/dist/types/permissions/types.d.ts +51 -0
  542. package/dist/types/permissions/types.d.ts.map +1 -0
  543. package/dist/types/providers/byok-providers.d.ts +117 -0
  544. package/dist/types/providers/byok-providers.d.ts.map +1 -0
  545. package/dist/types/providers/openai-codex-constants.d.ts +2 -0
  546. package/dist/types/providers/openai-codex-constants.d.ts.map +1 -0
  547. package/dist/types/providers/openai-codex-provider.d.ts +58 -0
  548. package/dist/types/providers/openai-codex-provider.d.ts.map +1 -0
  549. package/dist/types/queue/queue-runtime.d.ts +172 -0
  550. package/dist/types/queue/queue-runtime.d.ts.map +1 -0
  551. package/dist/types/reminders/state.d.ts +45 -0
  552. package/dist/types/reminders/state.d.ts.map +1 -0
  553. package/dist/types/runtime-context.d.ts +42 -0
  554. package/dist/types/runtime-context.d.ts.map +1 -0
  555. package/dist/types/settings-manager.d.ts +438 -0
  556. package/dist/types/settings-manager.d.ts.map +1 -0
  557. package/dist/types/telemetry/error-reporting.d.ts +12 -0
  558. package/dist/types/telemetry/error-reporting.d.ts.map +1 -0
  559. package/dist/types/telemetry/index.d.ts +267 -0
  560. package/dist/types/telemetry/index.d.ts.map +1 -0
  561. package/dist/types/tools/client-tool-serialization.d.ts +14 -0
  562. package/dist/types/tools/client-tool-serialization.d.ts.map +1 -0
  563. package/dist/types/tools/define-tool.d.ts +17 -0
  564. package/dist/types/tools/define-tool.d.ts.map +1 -0
  565. package/dist/types/tools/filter.d.ts +33 -0
  566. package/dist/types/tools/filter.d.ts.map +1 -0
  567. package/dist/types/tools/impl/apply-patch.d.ts +12 -0
  568. package/dist/types/tools/impl/apply-patch.d.ts.map +1 -0
  569. package/dist/types/tools/impl/artifact-files.d.ts +24 -0
  570. package/dist/types/tools/impl/artifact-files.d.ts.map +1 -0
  571. package/dist/types/tools/impl/ask-user-question.d.ts +20 -0
  572. package/dist/types/tools/impl/ask-user-question.d.ts.map +1 -0
  573. package/dist/types/tools/impl/bash-output.d.ts +31 -0
  574. package/dist/types/tools/impl/bash-output.d.ts.map +1 -0
  575. package/dist/types/tools/impl/bash.d.ts +41 -0
  576. package/dist/types/tools/impl/bash.d.ts.map +1 -0
  577. package/dist/types/tools/impl/edit.d.ts +26 -0
  578. package/dist/types/tools/impl/edit.d.ts.map +1 -0
  579. package/dist/types/tools/impl/enter-worktree.d.ts +36 -0
  580. package/dist/types/tools/impl/enter-worktree.d.ts.map +1 -0
  581. package/dist/types/tools/impl/exec-command.d.ts +52 -0
  582. package/dist/types/tools/impl/exec-command.d.ts.map +1 -0
  583. package/dist/types/tools/impl/glob-gemini.d.ts +16 -0
  584. package/dist/types/tools/impl/glob-gemini.d.ts.map +1 -0
  585. package/dist/types/tools/impl/glob.d.ts +12 -0
  586. package/dist/types/tools/impl/glob.d.ts.map +1 -0
  587. package/dist/types/tools/impl/grep-files.d.ts +19 -0
  588. package/dist/types/tools/impl/grep-files.d.ts.map +1 -0
  589. package/dist/types/tools/impl/grep.d.ts +23 -0
  590. package/dist/types/tools/impl/grep.d.ts.map +1 -0
  591. package/dist/types/tools/impl/kill-bash.d.ts +9 -0
  592. package/dist/types/tools/impl/kill-bash.d.ts.map +1 -0
  593. package/dist/types/tools/impl/list-dir-codex.d.ts +21 -0
  594. package/dist/types/tools/impl/list-dir-codex.d.ts.map +1 -0
  595. package/dist/types/tools/impl/list-directory-gemini.d.ts +17 -0
  596. package/dist/types/tools/impl/list-directory-gemini.d.ts.map +1 -0
  597. package/dist/types/tools/impl/ls.d.ts +12 -0
  598. package/dist/types/tools/impl/ls.d.ts.map +1 -0
  599. package/dist/types/tools/impl/memory-apply-patch.d.ts +10 -0
  600. package/dist/types/tools/impl/memory-apply-patch.d.ts.map +1 -0
  601. package/dist/types/tools/impl/memory.d.ts +20 -0
  602. package/dist/types/tools/impl/memory.d.ts.map +1 -0
  603. package/dist/types/tools/impl/message-channel.d.ts +10 -0
  604. package/dist/types/tools/impl/message-channel.d.ts.map +1 -0
  605. package/dist/types/tools/impl/multi-edit.d.ts +21 -0
  606. package/dist/types/tools/impl/multi-edit.d.ts.map +1 -0
  607. package/dist/types/tools/impl/overflow.d.ts +66 -0
  608. package/dist/types/tools/impl/overflow.d.ts.map +1 -0
  609. package/dist/types/tools/impl/process_manager.d.ts +83 -0
  610. package/dist/types/tools/impl/process_manager.d.ts.map +1 -0
  611. package/dist/types/tools/impl/read-file-codex.d.ts +24 -0
  612. package/dist/types/tools/impl/read-file-codex.d.ts.map +1 -0
  613. package/dist/types/tools/impl/read-file-gemini.d.ts +14 -0
  614. package/dist/types/tools/impl/read-file-gemini.d.ts.map +1 -0
  615. package/dist/types/tools/impl/read-lsp.d.ts +13 -0
  616. package/dist/types/tools/impl/read-lsp.d.ts.map +1 -0
  617. package/dist/types/tools/impl/read-many-files-gemini.d.ts +19 -0
  618. package/dist/types/tools/impl/read-many-files-gemini.d.ts.map +1 -0
  619. package/dist/types/tools/impl/read.d.ts +13 -0
  620. package/dist/types/tools/impl/read.d.ts.map +1 -0
  621. package/dist/types/tools/impl/replace-gemini.d.ts +15 -0
  622. package/dist/types/tools/impl/replace-gemini.d.ts.map +1 -0
  623. package/dist/types/tools/impl/ripgrep-manager.d.ts +9 -0
  624. package/dist/types/tools/impl/ripgrep-manager.d.ts.map +1 -0
  625. package/dist/types/tools/impl/run-shell-command-gemini.d.ts +18 -0
  626. package/dist/types/tools/impl/run-shell-command-gemini.d.ts.map +1 -0
  627. package/dist/types/tools/impl/search-file-content-gemini.d.ts +14 -0
  628. package/dist/types/tools/impl/search-file-content-gemini.d.ts.map +1 -0
  629. package/dist/types/tools/impl/shell-command.d.ts +25 -0
  630. package/dist/types/tools/impl/shell-command.d.ts.map +1 -0
  631. package/dist/types/tools/impl/shell-env.d.ts +20 -0
  632. package/dist/types/tools/impl/shell-env.d.ts.map +1 -0
  633. package/dist/types/tools/impl/shell-launchers.d.ts +14 -0
  634. package/dist/types/tools/impl/shell-launchers.d.ts.map +1 -0
  635. package/dist/types/tools/impl/shell-runner.d.ts +24 -0
  636. package/dist/types/tools/impl/shell-runner.d.ts.map +1 -0
  637. package/dist/types/tools/impl/shell-sandbox.d.ts +40 -0
  638. package/dist/types/tools/impl/shell-sandbox.d.ts.map +1 -0
  639. package/dist/types/tools/impl/shell.d.ts +25 -0
  640. package/dist/types/tools/impl/shell.d.ts.map +1 -0
  641. package/dist/types/tools/impl/skill-content-registry.d.ts +26 -0
  642. package/dist/types/tools/impl/skill-content-registry.d.ts.map +1 -0
  643. package/dist/types/tools/impl/skill.d.ts +45 -0
  644. package/dist/types/tools/impl/skill.d.ts.map +1 -0
  645. package/dist/types/tools/impl/task-create.d.ts +10 -0
  646. package/dist/types/tools/impl/task-create.d.ts.map +1 -0
  647. package/dist/types/tools/impl/task-get.d.ts +7 -0
  648. package/dist/types/tools/impl/task-get.d.ts.map +1 -0
  649. package/dist/types/tools/impl/task-list.d.ts +7 -0
  650. package/dist/types/tools/impl/task-list.d.ts.map +1 -0
  651. package/dist/types/tools/impl/task-output.d.ts +18 -0
  652. package/dist/types/tools/impl/task-output.d.ts.map +1 -0
  653. package/dist/types/tools/impl/task-stop.d.ts +9 -0
  654. package/dist/types/tools/impl/task-stop.d.ts.map +1 -0
  655. package/dist/types/tools/impl/task-update.d.ts +15 -0
  656. package/dist/types/tools/impl/task-update.d.ts.map +1 -0
  657. package/dist/types/tools/impl/task.d.ts +131 -0
  658. package/dist/types/tools/impl/task.d.ts.map +1 -0
  659. package/dist/types/tools/impl/tasks/store.d.ts +56 -0
  660. package/dist/types/tools/impl/tasks/store.d.ts.map +1 -0
  661. package/dist/types/tools/impl/todo-write.d.ts +14 -0
  662. package/dist/types/tools/impl/todo-write.d.ts.map +1 -0
  663. package/dist/types/tools/impl/tool-return-clamp.d.ts +21 -0
  664. package/dist/types/tools/impl/tool-return-clamp.d.ts.map +1 -0
  665. package/dist/types/tools/impl/truncation.d.ts +63 -0
  666. package/dist/types/tools/impl/truncation.d.ts.map +1 -0
  667. package/dist/types/tools/impl/update-plan.d.ts +13 -0
  668. package/dist/types/tools/impl/update-plan.d.ts.map +1 -0
  669. package/dist/types/tools/impl/validation.d.ts +15 -0
  670. package/dist/types/tools/impl/validation.d.ts.map +1 -0
  671. package/dist/types/tools/impl/view-image.d.ts +9 -0
  672. package/dist/types/tools/impl/view-image.d.ts.map +1 -0
  673. package/dist/types/tools/impl/write-file-gemini.d.ts +13 -0
  674. package/dist/types/tools/impl/write-file-gemini.d.ts.map +1 -0
  675. package/dist/types/tools/impl/write-todos-gemini.d.ts +16 -0
  676. package/dist/types/tools/impl/write-todos-gemini.d.ts.map +1 -0
  677. package/dist/types/tools/impl/write.d.ts +10 -0
  678. package/dist/types/tools/impl/write.d.ts.map +1 -0
  679. package/dist/types/tools/interactive-policy.d.ts +12 -0
  680. package/dist/types/tools/interactive-policy.d.ts.map +1 -0
  681. package/dist/types/tools/manager.d.ts +355 -0
  682. package/dist/types/tools/manager.d.ts.map +1 -0
  683. package/dist/types/tools/model-facing-tool.d.ts +35 -0
  684. package/dist/types/tools/model-facing-tool.d.ts.map +1 -0
  685. package/dist/types/tools/permission-mode-state.d.ts +7 -0
  686. package/dist/types/tools/permission-mode-state.d.ts.map +1 -0
  687. package/dist/types/tools/secret-substitution.d.ts +17 -0
  688. package/dist/types/tools/secret-substitution.d.ts.map +1 -0
  689. package/dist/types/tools/tool-definitions.d.ts +71 -0
  690. package/dist/types/tools/tool-definitions.d.ts.map +1 -0
  691. package/dist/types/tools/toolset.d.ts +112 -0
  692. package/dist/types/tools/toolset.d.ts.map +1 -0
  693. package/dist/types/types/protocol_v2.d.ts +35 -59
  694. package/dist/types/types/protocol_v2.d.ts.map +1 -1
  695. package/dist/types/types/schedule-protocol.d.ts +59 -0
  696. package/dist/types/types/schedule-protocol.d.ts.map +1 -0
  697. package/dist/types/types/service-protocol.d.ts +24 -0
  698. package/dist/types/types/service-protocol.d.ts.map +1 -0
  699. package/dist/types/updater/auto-update.d.ts +48 -0
  700. package/dist/types/updater/auto-update.d.ts.map +1 -0
  701. package/dist/types/utils/create-relayed-abort-controller.d.ts +16 -0
  702. package/dist/types/utils/create-relayed-abort-controller.d.ts.map +1 -0
  703. package/dist/types/utils/debug.d.ts +36 -0
  704. package/dist/types/utils/debug.d.ts.map +1 -0
  705. package/dist/types/utils/directory-limits.d.ts +35 -0
  706. package/dist/types/utils/directory-limits.d.ts.map +1 -0
  707. package/dist/types/utils/error.d.ts +8 -0
  708. package/dist/types/utils/error.d.ts.map +1 -0
  709. package/dist/types/utils/file-path.d.ts +9 -0
  710. package/dist/types/utils/file-path.d.ts.map +1 -0
  711. package/dist/types/utils/frontmatter.d.ts +23 -0
  712. package/dist/types/utils/frontmatter.d.ts.map +1 -0
  713. package/dist/types/utils/fs.d.ts +27 -0
  714. package/dist/types/utils/fs.d.ts.map +1 -0
  715. package/dist/types/utils/image-resize.d.ts +5 -0
  716. package/dist/types/utils/image-resize.d.ts.map +1 -0
  717. package/dist/types/utils/image-resize.magick.d.ts +8 -0
  718. package/dist/types/utils/image-resize.magick.d.ts.map +1 -0
  719. package/dist/types/utils/image-resize.shared.d.ts +18 -0
  720. package/dist/types/utils/image-resize.shared.d.ts.map +1 -0
  721. package/dist/types/utils/image-resize.sips.d.ts +2 -0
  722. package/dist/types/utils/image-resize.sips.d.ts.map +1 -0
  723. package/dist/types/utils/message-image-normalization.d.ts +25 -0
  724. package/dist/types/utils/message-image-normalization.d.ts.map +1 -0
  725. package/dist/types/utils/message-queue-bridge.d.ts +40 -0
  726. package/dist/types/utils/message-queue-bridge.d.ts.map +1 -0
  727. package/dist/types/utils/openai-endpoint.d.ts +4 -0
  728. package/dist/types/utils/openai-endpoint.d.ts.map +1 -0
  729. package/dist/types/utils/package-manager-spawn.d.ts +8 -0
  730. package/dist/types/utils/package-manager-spawn.d.ts.map +1 -0
  731. package/dist/types/utils/secrets-store.d.ts +83 -0
  732. package/dist/types/utils/secrets-store.d.ts.map +1 -0
  733. package/dist/types/utils/secrets.d.ts +58 -0
  734. package/dist/types/utils/secrets.d.ts.map +1 -0
  735. package/dist/types/utils/shell-context.d.ts +7 -0
  736. package/dist/types/utils/shell-context.d.ts.map +1 -0
  737. package/dist/types/utils/sleep.d.ts +5 -0
  738. package/dist/types/utils/sleep.d.ts.map +1 -0
  739. package/dist/types/utils/stream-abort-relay.d.ts +8 -0
  740. package/dist/types/utils/stream-abort-relay.d.ts.map +1 -0
  741. package/dist/types/utils/subagent-stdout-failure.d.ts +10 -0
  742. package/dist/types/utils/subagent-stdout-failure.d.ts.map +1 -0
  743. package/dist/types/utils/system-prompt-size.d.ts +32 -0
  744. package/dist/types/utils/system-prompt-size.d.ts.map +1 -0
  745. package/dist/types/utils/task-notifications.d.ts +38 -0
  746. package/dist/types/utils/task-notifications.d.ts.map +1 -0
  747. package/dist/types/utils/text-files.d.ts +7 -0
  748. package/dist/types/utils/text-files.d.ts.map +1 -0
  749. package/dist/types/utils/timing.d.ts +53 -0
  750. package/dist/types/utils/timing.d.ts.map +1 -0
  751. package/dist/types/utils/transcript-paths.d.ts +13 -0
  752. package/dist/types/utils/transcript-paths.d.ts.map +1 -0
  753. package/dist/types/utils/tui-perf.d.ts +6 -0
  754. package/dist/types/utils/tui-perf.d.ts.map +1 -0
  755. package/dist/types/utils/type-guards.d.ts +7 -0
  756. package/dist/types/utils/type-guards.d.ts.map +1 -0
  757. package/dist/types/utils/url.d.ts +8 -0
  758. package/dist/types/utils/url.d.ts.map +1 -0
  759. package/dist/types/utils/worktree-lock.d.ts +49 -0
  760. package/dist/types/utils/worktree-lock.d.ts.map +1 -0
  761. package/dist/types/version.d.ts +2 -0
  762. package/dist/types/version.d.ts.map +1 -0
  763. package/dist/types/websocket/listener/background-process-snapshot.d.ts +3 -0
  764. package/dist/types/websocket/listener/background-process-snapshot.d.ts.map +1 -0
  765. package/dist/types/websocket/listener/connection.d.ts +48 -0
  766. package/dist/types/websocket/listener/connection.d.ts.map +1 -0
  767. package/dist/types/websocket/listener/constants.d.ts +22 -0
  768. package/dist/types/websocket/listener/constants.d.ts.map +1 -0
  769. package/dist/types/websocket/listener/cwd-change.d.ts +21 -0
  770. package/dist/types/websocket/listener/cwd-change.d.ts.map +1 -0
  771. package/dist/types/websocket/listener/cwd.d.ts +22 -0
  772. package/dist/types/websocket/listener/cwd.d.ts.map +1 -0
  773. package/dist/types/websocket/listener/device-status-cache.d.ts +10 -0
  774. package/dist/types/websocket/listener/device-status-cache.d.ts.map +1 -0
  775. package/dist/types/websocket/listener/listener-constants.d.ts +9 -0
  776. package/dist/types/websocket/listener/listener-constants.d.ts.map +1 -0
  777. package/dist/types/websocket/listener/memfs-sync.d.ts +24 -0
  778. package/dist/types/websocket/listener/memfs-sync.d.ts.map +1 -0
  779. package/dist/types/websocket/listener/mod-adapter.d.ts +48 -0
  780. package/dist/types/websocket/listener/mod-adapter.d.ts.map +1 -0
  781. package/dist/types/websocket/listener/mod-commands.d.ts +23 -0
  782. package/dist/types/websocket/listener/mod-commands.d.ts.map +1 -0
  783. package/dist/types/websocket/listener/outbound-wire.d.ts +82 -0
  784. package/dist/types/websocket/listener/outbound-wire.d.ts.map +1 -0
  785. package/dist/types/websocket/listener/permission-mode.d.ts +46 -0
  786. package/dist/types/websocket/listener/permission-mode.d.ts.map +1 -0
  787. package/dist/types/websocket/listener/protocol-outbound.d.ts +122 -0
  788. package/dist/types/websocket/listener/protocol-outbound.d.ts.map +1 -0
  789. package/dist/types/websocket/listener/remote-settings-lock.d.ts +24 -0
  790. package/dist/types/websocket/listener/remote-settings-lock.d.ts.map +1 -0
  791. package/dist/types/websocket/listener/remote-settings.d.ts +47 -0
  792. package/dist/types/websocket/listener/remote-settings.d.ts.map +1 -0
  793. package/dist/types/websocket/listener/runtime.d.ts +51 -0
  794. package/dist/types/websocket/listener/runtime.d.ts.map +1 -0
  795. package/dist/types/websocket/listener/scope.d.ts +15 -0
  796. package/dist/types/websocket/listener/scope.d.ts.map +1 -0
  797. package/dist/types/websocket/listener/stream-observers.d.ts +16 -0
  798. package/dist/types/websocket/listener/stream-observers.d.ts.map +1 -0
  799. package/dist/types/websocket/listener/transport.d.ts +30 -0
  800. package/dist/types/websocket/listener/transport.d.ts.map +1 -0
  801. package/dist/types/websocket/listener/turn-context.d.ts +7 -0
  802. package/dist/types/websocket/listener/turn-context.d.ts.map +1 -0
  803. package/dist/types/websocket/listener/turn-lifecycle.d.ts +89 -0
  804. package/dist/types/websocket/listener/turn-lifecycle.d.ts.map +1 -0
  805. package/dist/types/websocket/listener/types.d.ts +322 -0
  806. package/dist/types/websocket/listener/types.d.ts.map +1 -0
  807. package/dist/types/websocket/listener/worktree-ownership.d.ts +11 -0
  808. package/dist/types/websocket/listener/worktree-ownership.d.ts.map +1 -0
  809. package/dist/types/websocket/listener/worktree-watcher.d.ts +41 -0
  810. package/dist/types/websocket/listener/worktree-watcher.d.ts.map +1 -0
  811. package/letta.js +7744 -6453
  812. package/package.json +12 -1
  813. package/scripts/source-file-size-baseline.json +7 -9
@@ -0,0 +1,2190 @@
1
+ // src/tools/interactive-policy.ts
2
+ var INTERACTIVE_APPROVAL_TOOLS = new Set(["AskUserQuestion"]);
3
+ var INTERACTIVE_USER_INPUT_TOOL_NAMES = [
4
+ "AskUserQuestion"
5
+ ];
6
+ var RUNTIME_USER_INPUT_TOOLS = new Set(INTERACTIVE_USER_INPUT_TOOL_NAMES);
7
+ var HEADLESS_AUTO_ALLOW_TOOLS = new Set;
8
+ function getInteractiveApprovalKind(toolName) {
9
+ switch (toolName) {
10
+ case "AskUserQuestion":
11
+ return "ask_user_question";
12
+ default:
13
+ return null;
14
+ }
15
+ }
16
+
17
+ // src/channels/progress-formatting.ts
18
+ var MAX_PROGRESS_TEXT_LENGTH = 140;
19
+ var MAX_PROGRESS_DETAILS_LENGTH = 180;
20
+ var MAX_SHELL_PROGRESS_DETAILS_LENGTH = 64;
21
+ var MAX_SUBAGENT_PROGRESS_DETAILS_LENGTH = 180;
22
+ var ESCAPE_CODE = String.fromCharCode(27);
23
+ var ANSI_ESCAPE_RE = new RegExp(`${ESCAPE_CODE}\\[[0-9;?]*[ -/]*[@-~]`, "g");
24
+ var SECRET_ASSIGNMENT_RE = /\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|API[_-]?KEY|ACCESS[_-]?KEY)[A-Z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/gi;
25
+ var SECRET_JSON_RE = /(["']?(?:token|secret|password|api[_-]?key|access[_-]?key)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|\S+)/gi;
26
+ function isTaskTool(name) {
27
+ return name === "Task" || name === "task" || name === "Agent" || name === "agent";
28
+ }
29
+ function isShellTool(name) {
30
+ const normalized = name.toLowerCase();
31
+ return normalized === "bash" || normalized === "exec_command" || normalized === "shell_command" || normalized === "shell" || normalized === "runshellcommand";
32
+ }
33
+ function isWebSearchTool(name) {
34
+ const normalized = name.toLowerCase();
35
+ return normalized === "web_search" || normalized === "websearch";
36
+ }
37
+ function isSearchTool(name) {
38
+ const normalized = name.toLowerCase();
39
+ return normalized === "grep" || normalized === "grep_files" || normalized === "grepfiles" || normalized === "search_file_content" || normalized === "searchfilecontent";
40
+ }
41
+ function isGlobTool(name) {
42
+ const normalized = name.toLowerCase();
43
+ return normalized === "glob" || normalized === "glob_gemini";
44
+ }
45
+ function isFileReadTool(name) {
46
+ const normalized = name.toLowerCase();
47
+ return normalized === "read" || normalized === "read_file" || normalized === "readfile" || normalized === "read_file_gemini" || normalized === "readfilegemini";
48
+ }
49
+ function isFileWriteTool(name) {
50
+ const normalized = name.toLowerCase();
51
+ return normalized === "write" || normalized === "write_file" || normalized === "writefile" || normalized === "write_file_gemini" || normalized === "writefilegemini";
52
+ }
53
+ function isFileEditTool(name) {
54
+ const normalized = name.toLowerCase();
55
+ return normalized === "edit" || normalized === "multi_edit" || normalized === "multiedit" || normalized === "replace" || normalized === "apply_patch" || normalized === "applypatch";
56
+ }
57
+ function getPathBaseName(filePath) {
58
+ return filePath.split(/[\\/]/).filter(Boolean).pop() ?? filePath;
59
+ }
60
+ function asRecord(value) {
61
+ return value && typeof value === "object" ? value : null;
62
+ }
63
+ function firstNonEmptyString(...values) {
64
+ for (const value of values) {
65
+ if (typeof value === "string" && value.trim().length > 0) {
66
+ return value;
67
+ }
68
+ }
69
+ return;
70
+ }
71
+ function truncateChannelProgressText(value, maxLength, marker = "...") {
72
+ if (value.length <= maxLength) {
73
+ return value;
74
+ }
75
+ if (maxLength <= marker.length) {
76
+ return marker.slice(0, Math.max(0, maxLength));
77
+ }
78
+ return `${value.slice(0, maxLength - marker.length).trimEnd()}${marker}`;
79
+ }
80
+ function replaceControlCharacters(value) {
81
+ let result = "";
82
+ for (let index = 0;index < value.length; index += 1) {
83
+ const character = value[index] ?? "";
84
+ const code = character.charCodeAt(0);
85
+ result += code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31 || code === 127 ? " " : character;
86
+ }
87
+ return result;
88
+ }
89
+ function sanitizeChannelProgressCore(value) {
90
+ const raw = typeof value === "string" ? value : String(value ?? "");
91
+ const redacted = raw.replace(ANSI_ESCAPE_RE, "").replace(SECRET_ASSIGNMENT_RE, "$1=[redacted]").replace(SECRET_JSON_RE, "$1[redacted]");
92
+ return replaceControlCharacters(redacted).replace(/[\r\n\t]+/g, " ").replace(/@(?=channel|here|everyone|[A-Za-z0-9._-]+)/gi, "@​").replace(/\s+/g, " ").trim();
93
+ }
94
+ function sanitizeChannelProgressText(value, maxLength = MAX_PROGRESS_TEXT_LENGTH) {
95
+ return truncateChannelProgressText(sanitizeChannelProgressCore(value), maxLength);
96
+ }
97
+ function sanitizeChannelProgressIdentifier(value, fallback) {
98
+ const text = sanitizeChannelProgressText(value, 64);
99
+ if (!text) {
100
+ return fallback;
101
+ }
102
+ const cleaned = text.replace(/[^A-Za-z0-9_.:/ -]/g, "").trim();
103
+ return cleaned || fallback;
104
+ }
105
+ function summarizeShellCommand(command) {
106
+ const normalized = sanitizeChannelProgressText(command, 1e4);
107
+ if (!normalized) {
108
+ return "";
109
+ }
110
+ const segments = normalized.split(/\s*;\s*/).map((segment) => segment.trim()).filter(Boolean);
111
+ const firstTwoSegments = segments.slice(0, 2).join("; ");
112
+ const previewSource = firstTwoSegments.length > 0 && firstTwoSegments.length <= 70 ? firstTwoSegments : segments[0] ?? normalized;
113
+ const withoutPipeline = previewSource.split(/\s*\|\s*/)[0] ?? previewSource;
114
+ return sanitizeChannelProgressText(withoutPipeline.trim() || normalized, MAX_SHELL_PROGRESS_DETAILS_LENGTH);
115
+ }
116
+ function getSkillNameFromArguments(parsedArguments) {
117
+ return firstNonEmptyString(parsedArguments.skill, parsedArguments.skillName);
118
+ }
119
+ function getFragmentedSkillName(summary) {
120
+ const skillMatch = summary.argumentsText?.match(/"(?:skill|skillName)"\s*:\s*"([^"]+)"/);
121
+ return skillMatch?.[1];
122
+ }
123
+ function resolveSkillDescription(skillName, options) {
124
+ const lookup = options?.skillDescriptionsByName;
125
+ if (!skillName || !lookup) {
126
+ return;
127
+ }
128
+ if ("get" in lookup && typeof lookup.get === "function") {
129
+ return firstNonEmptyString(lookup.get(skillName));
130
+ }
131
+ return firstNonEmptyString(lookup[skillName]);
132
+ }
133
+ function formatSkillProgressTitleFromName(skillName) {
134
+ const sanitized = sanitizeChannelProgressText(skillName, MAX_PROGRESS_DETAILS_LENGTH);
135
+ return sanitized ? `Skill: ${sanitized}` : undefined;
136
+ }
137
+ function formatShellProgressDetailsFromArguments(parsedArguments) {
138
+ const description = firstNonEmptyString(parsedArguments.description);
139
+ if (description) {
140
+ return sanitizeChannelProgressText(description, MAX_PROGRESS_DETAILS_LENGTH) || undefined;
141
+ }
142
+ const commandPreview = firstNonEmptyString(parsedArguments.command, parsedArguments.cmd);
143
+ return summarizeShellCommand(commandPreview ?? "") || undefined;
144
+ }
145
+ function formatFragmentedShellProgressDetails(summary) {
146
+ const descriptionMatch = summary.argumentsText?.match(/"description"\s*:\s*"([^"]+)"/);
147
+ if (descriptionMatch?.[1]) {
148
+ return sanitizeChannelProgressText(descriptionMatch[1], MAX_PROGRESS_DETAILS_LENGTH) || undefined;
149
+ }
150
+ return;
151
+ }
152
+ function formatSubagentProgressDetailsFromArguments(parsedArguments) {
153
+ const preview = firstNonEmptyString(parsedArguments.prompt, parsedArguments.description, parsedArguments.subject);
154
+ const sanitized = sanitizeChannelProgressText(preview, MAX_SUBAGENT_PROGRESS_DETAILS_LENGTH);
155
+ return sanitized || undefined;
156
+ }
157
+ function formatFragmentedSubagentProgressDetails(summary) {
158
+ const previewMatch = summary.argumentsText?.match(/"(?:prompt|description|subject)"\s*:\s*"([^"]+)"/);
159
+ if (!previewMatch?.[1]) {
160
+ return;
161
+ }
162
+ const sanitized = sanitizeChannelProgressText(previewMatch[1], MAX_SUBAGENT_PROGRESS_DETAILS_LENGTH);
163
+ return sanitized || undefined;
164
+ }
165
+ function parseToolArguments(value) {
166
+ if (!value) {
167
+ return null;
168
+ }
169
+ try {
170
+ return asRecord(JSON.parse(value));
171
+ } catch {
172
+ return null;
173
+ }
174
+ }
175
+ function isFetchWebpageToolName(name) {
176
+ return name === "fetch_webpage" || name === "FetchWebpage" || name === "fetchWebpage";
177
+ }
178
+ function isSkillToolName(name) {
179
+ if (!name) {
180
+ return false;
181
+ }
182
+ const normalized = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : name;
183
+ return normalized === "Skill" || normalized === "skill";
184
+ }
185
+ function isFilePathToolName(name) {
186
+ return isFileReadTool(name) || isFileWriteTool(name) || isFileEditTool(name);
187
+ }
188
+ function getFileToolKind(name) {
189
+ if (isFileReadTool(name)) {
190
+ return "read";
191
+ }
192
+ if (isFileWriteTool(name)) {
193
+ return "write";
194
+ }
195
+ if (isFileEditTool(name)) {
196
+ return "update";
197
+ }
198
+ return null;
199
+ }
200
+ function countProgressLines(value) {
201
+ return value ? value.split(`
202
+ `).length : 0;
203
+ }
204
+ function formatLineChangeSummary(summary) {
205
+ if (!summary) {
206
+ return "";
207
+ }
208
+ const parts = [];
209
+ if (summary.additions !== undefined) {
210
+ parts.push(`+${summary.additions}`);
211
+ }
212
+ if (summary.deletions !== undefined) {
213
+ parts.push(`-${summary.deletions}`);
214
+ }
215
+ return parts.length > 0 ? ` ${parts.join(" ")}` : "";
216
+ }
217
+ function extractFilePathFromArguments(parsedArguments) {
218
+ return firstNonEmptyString(parsedArguments.file_path, parsedArguments.filePath, parsedArguments.path);
219
+ }
220
+ function formatProgressFileName(filePath) {
221
+ if (!filePath) {
222
+ return;
223
+ }
224
+ const fileName = getPathBaseName(filePath) || filePath;
225
+ return sanitizeChannelProgressText(fileName, MAX_PROGRESS_DETAILS_LENGTH) || undefined;
226
+ }
227
+ function getEditLineChangeSummary(parsedArguments) {
228
+ const oldString = firstNonEmptyString(parsedArguments.old_string);
229
+ const newString = firstNonEmptyString(parsedArguments.new_string);
230
+ if (oldString === undefined || newString === undefined) {
231
+ return null;
232
+ }
233
+ return {
234
+ additions: countProgressLines(newString),
235
+ deletions: countProgressLines(oldString)
236
+ };
237
+ }
238
+ function getMultiEditLineChangeSummary(parsedArguments) {
239
+ if (!Array.isArray(parsedArguments.edits)) {
240
+ return null;
241
+ }
242
+ let additions = 0;
243
+ let deletions = 0;
244
+ let counted = false;
245
+ for (const edit of parsedArguments.edits) {
246
+ const record = asRecord(edit);
247
+ if (!record) {
248
+ continue;
249
+ }
250
+ const oldString = firstNonEmptyString(record.old_string);
251
+ const newString = firstNonEmptyString(record.new_string);
252
+ if (oldString === undefined || newString === undefined) {
253
+ continue;
254
+ }
255
+ additions += countProgressLines(newString);
256
+ deletions += countProgressLines(oldString);
257
+ counted = true;
258
+ }
259
+ return counted ? { additions, deletions } : null;
260
+ }
261
+ function getWriteLineChangeSummary(parsedArguments) {
262
+ const content = firstNonEmptyString(parsedArguments.content);
263
+ if (content === undefined) {
264
+ return null;
265
+ }
266
+ return {
267
+ additions: countProgressLines(content)
268
+ };
269
+ }
270
+ function getFileLineChangeSummary(name, parsedArguments) {
271
+ if (isFileWriteTool(name)) {
272
+ return getWriteLineChangeSummary(parsedArguments);
273
+ }
274
+ if (name === "MultiEdit" || name === "multi_edit") {
275
+ return getMultiEditLineChangeSummary(parsedArguments);
276
+ }
277
+ if (isFileEditTool(name)) {
278
+ return getEditLineChangeSummary(parsedArguments);
279
+ }
280
+ return null;
281
+ }
282
+ function getFileToolVerb(kind, status) {
283
+ if (status === "error") {
284
+ if (kind === "read") {
285
+ return "Tried to read";
286
+ }
287
+ if (kind === "write") {
288
+ return "Tried to write";
289
+ }
290
+ return "Tried to update";
291
+ }
292
+ if (status === "started") {
293
+ if (kind === "read") {
294
+ return "Reading";
295
+ }
296
+ if (kind === "write") {
297
+ return "Writing";
298
+ }
299
+ return "Updating";
300
+ }
301
+ if (kind === "read") {
302
+ return "Read";
303
+ }
304
+ if (kind === "write") {
305
+ return "Wrote";
306
+ }
307
+ return "Updated";
308
+ }
309
+ function formatFileToolProgressTitle(name, parsedArguments, status) {
310
+ const kind = getFileToolKind(name);
311
+ if (!kind) {
312
+ return;
313
+ }
314
+ const fileName = formatProgressFileName(extractFilePathFromArguments(parsedArguments));
315
+ if (!fileName) {
316
+ return;
317
+ }
318
+ const stats = status === "completed" ? formatLineChangeSummary(getFileLineChangeSummary(name, parsedArguments)) : "";
319
+ return `${getFileToolVerb(kind, status)} ${fileName}${stats}`;
320
+ }
321
+ function formatFragmentedFileToolProgressTitle(summary, status) {
322
+ if (!summary.name || !summary.argumentsText) {
323
+ return;
324
+ }
325
+ const kind = getFileToolKind(summary.name);
326
+ if (!kind) {
327
+ return;
328
+ }
329
+ const filePathMatch = summary.argumentsText.match(/"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/);
330
+ const fileName = formatProgressFileName(filePathMatch?.[1]);
331
+ if (!fileName) {
332
+ return;
333
+ }
334
+ return `${getFileToolVerb(kind, status)} ${fileName}`;
335
+ }
336
+ function formatToolProgressTitle(summary, status) {
337
+ if (!summary.name || !summary.argumentsText) {
338
+ return;
339
+ }
340
+ const parsedArguments = parseToolArguments(summary.argumentsText);
341
+ if (parsedArguments) {
342
+ if (isSkillToolName(summary.name)) {
343
+ return formatSkillProgressTitleFromName(getSkillNameFromArguments(parsedArguments));
344
+ }
345
+ if (isFilePathToolName(summary.name)) {
346
+ return formatFileToolProgressTitle(summary.name, parsedArguments, status);
347
+ }
348
+ return;
349
+ }
350
+ if (isSkillToolName(summary.name)) {
351
+ return formatSkillProgressTitleFromName(getFragmentedSkillName(summary));
352
+ }
353
+ if (isFilePathToolName(summary.name)) {
354
+ return formatFragmentedFileToolProgressTitle(summary, status);
355
+ }
356
+ return;
357
+ }
358
+ function formatSkillProgressDetailsFromArguments(parsedArguments, options) {
359
+ const skillName = getSkillNameFromArguments(parsedArguments);
360
+ const detail = resolveSkillDescription(skillName, options) ?? skillName;
361
+ const sanitized = sanitizeChannelProgressText(detail, MAX_PROGRESS_DETAILS_LENGTH);
362
+ return sanitized || undefined;
363
+ }
364
+ function formatFragmentedSkillProgressDetails(summary, options) {
365
+ const skillName = getFragmentedSkillName(summary);
366
+ const detail = resolveSkillDescription(skillName, options) ?? skillName;
367
+ const sanitized = sanitizeChannelProgressText(detail, MAX_PROGRESS_DETAILS_LENGTH);
368
+ return sanitized || undefined;
369
+ }
370
+ function formatToolProgressDetails(summary, options) {
371
+ if (!summary.name || !summary.argumentsText) {
372
+ return;
373
+ }
374
+ const parsedArguments = parseToolArguments(summary.argumentsText);
375
+ if (parsedArguments) {
376
+ if (isWebSearchTool(summary.name)) {
377
+ const query = firstNonEmptyString(parsedArguments.query);
378
+ const sanitized = sanitizeChannelProgressText(query, MAX_PROGRESS_DETAILS_LENGTH);
379
+ return sanitized || undefined;
380
+ }
381
+ if (isFetchWebpageToolName(summary.name)) {
382
+ const url = firstNonEmptyString(parsedArguments.url);
383
+ const sanitized = sanitizeChannelProgressText(url, MAX_PROGRESS_DETAILS_LENGTH);
384
+ return sanitized || undefined;
385
+ }
386
+ if (isSkillToolName(summary.name)) {
387
+ return formatSkillProgressDetailsFromArguments(parsedArguments, options);
388
+ }
389
+ if (isTaskTool(summary.name)) {
390
+ return formatSubagentProgressDetailsFromArguments(parsedArguments);
391
+ }
392
+ if (isShellTool(summary.name)) {
393
+ return formatShellProgressDetailsFromArguments(parsedArguments);
394
+ }
395
+ if (isFilePathToolName(summary.name)) {
396
+ const filePath = firstNonEmptyString(parsedArguments.file_path, parsedArguments.filePath, parsedArguments.path);
397
+ const sanitized = sanitizeChannelProgressText(filePath, MAX_PROGRESS_DETAILS_LENGTH);
398
+ return sanitized || undefined;
399
+ }
400
+ if (isGlobTool(summary.name) || isSearchTool(summary.name)) {
401
+ const pattern = firstNonEmptyString(parsedArguments.pattern);
402
+ const sanitized = sanitizeChannelProgressText(pattern, MAX_PROGRESS_DETAILS_LENGTH);
403
+ return sanitized || undefined;
404
+ }
405
+ return;
406
+ }
407
+ if (isShellTool(summary.name)) {
408
+ return formatFragmentedShellProgressDetails(summary);
409
+ }
410
+ if (isSkillToolName(summary.name)) {
411
+ return formatFragmentedSkillProgressDetails(summary, options);
412
+ }
413
+ if (isTaskTool(summary.name)) {
414
+ return formatFragmentedSubagentProgressDetails(summary);
415
+ }
416
+ if (isFilePathToolName(summary.name)) {
417
+ const filePathMatch = summary.argumentsText.match(/"file_path"\s*:\s*"([^"]+)"/);
418
+ if (filePathMatch?.[1]) {
419
+ const sanitized = sanitizeChannelProgressText(filePathMatch[1], MAX_PROGRESS_DETAILS_LENGTH);
420
+ return sanitized || undefined;
421
+ }
422
+ }
423
+ return;
424
+ }
425
+
426
+ // src/channels/progress-builder.ts
427
+ function getMessageType(delta) {
428
+ return firstNonEmptyString(delta.message_type, delta.messageType) ?? null;
429
+ }
430
+ function getRunId(delta) {
431
+ return firstNonEmptyString(delta.run_id, delta.runId);
432
+ }
433
+ function withRunId(update, runId) {
434
+ return {
435
+ ...update,
436
+ ...runId ? { runId } : {}
437
+ };
438
+ }
439
+ function getCommandId(delta) {
440
+ const command = firstNonEmptyString(delta.command_id, delta.commandId);
441
+ return sanitizeChannelProgressIdentifier(command, "command");
442
+ }
443
+ function getSlashCommand(delta) {
444
+ const commandId = firstNonEmptyString(delta.command_id, delta.commandId);
445
+ const command = commandId ? `/${commandId.replace(/^\/+/, "")}` : "command";
446
+ return sanitizeChannelProgressIdentifier(command, "command");
447
+ }
448
+ function getToolStatus(delta) {
449
+ const status = firstNonEmptyString(delta.status)?.toLowerCase();
450
+ return status === "error" || status === "failed" ? "error" : "completed";
451
+ }
452
+ function stringifyProgressValue(value) {
453
+ if (typeof value === "string") {
454
+ return value;
455
+ }
456
+ if (value === undefined || value === null) {
457
+ return;
458
+ }
459
+ try {
460
+ return JSON.stringify(value);
461
+ } catch {
462
+ return String(value);
463
+ }
464
+ }
465
+ function formatToolErrorDetails(record) {
466
+ const toolReturn = record.tool_return ?? record.toolReturn;
467
+ const toolReturnRecord = asRecord(toolReturn);
468
+ const preview = firstNonEmptyString(record.stderr, record.error, record.message, toolReturnRecord?.stderr, toolReturnRecord?.error, toolReturnRecord?.message, toolReturnRecord?.output, stringifyProgressValue(toolReturn));
469
+ const sanitized = sanitizeChannelProgressText(preview, MAX_PROGRESS_DETAILS_LENGTH);
470
+ return sanitized || undefined;
471
+ }
472
+ function toolNameForMessage(summary) {
473
+ return summary?.name ? `: ${summary.name}` : "";
474
+ }
475
+ function createChannelTurnProgressBuilder(options = {}) {
476
+ const argumentsByToolCallId = new Map;
477
+ const namesByToolCallId = new Map;
478
+ function extractToolCallSummary(value) {
479
+ const record = asRecord(value);
480
+ if (!record) {
481
+ return null;
482
+ }
483
+ const id = firstNonEmptyString(record.tool_call_id);
484
+ const cacheId = id ? sanitizeChannelProgressIdentifier(id, "tool-call") : undefined;
485
+ const extractedName = firstNonEmptyString(record.name);
486
+ if (cacheId && extractedName) {
487
+ namesByToolCallId.set(cacheId, extractedName);
488
+ }
489
+ const resolvedName = extractedName ?? (cacheId ? namesByToolCallId.get(cacheId) : undefined);
490
+ const rawArguments = typeof record.arguments === "string" && record.arguments.length > 0 ? record.arguments : asRecord(record.arguments) ? JSON.stringify(record.arguments) : undefined;
491
+ let argumentsText;
492
+ if (cacheId && rawArguments !== undefined) {
493
+ const existing = argumentsByToolCallId.get(cacheId);
494
+ if (parseToolArguments(rawArguments)) {
495
+ argumentsByToolCallId.set(cacheId, rawArguments);
496
+ argumentsText = rawArguments;
497
+ } else if (existing) {
498
+ if (parseToolArguments(existing)) {
499
+ argumentsText = existing;
500
+ } else {
501
+ const accumulated = existing + rawArguments;
502
+ argumentsByToolCallId.set(cacheId, accumulated);
503
+ argumentsText = accumulated;
504
+ }
505
+ } else {
506
+ argumentsByToolCallId.set(cacheId, rawArguments);
507
+ argumentsText = rawArguments;
508
+ }
509
+ } else if (!id && rawArguments !== undefined) {
510
+ argumentsText = rawArguments;
511
+ }
512
+ if (!id && !resolvedName) {
513
+ return null;
514
+ }
515
+ return {
516
+ ...cacheId ? { id: cacheId } : {},
517
+ ...resolvedName ? { name: sanitizeChannelProgressIdentifier(resolvedName, "tool") } : {},
518
+ ...argumentsText ? { argumentsText } : {}
519
+ };
520
+ }
521
+ function extractClientToolSummary(record) {
522
+ const id = firstNonEmptyString(record.tool_call_id, record.toolCallId);
523
+ const cacheId = id ? sanitizeChannelProgressIdentifier(id, "tool-call") : undefined;
524
+ const extractedName = firstNonEmptyString(record.tool_name, record.toolName, record.name);
525
+ if (cacheId && extractedName) {
526
+ namesByToolCallId.set(cacheId, extractedName);
527
+ }
528
+ const resolvedName = extractedName ?? (cacheId ? namesByToolCallId.get(cacheId) : undefined);
529
+ const rawArguments = firstNonEmptyString(record.tool_args, record.toolArgs, record.arguments);
530
+ if (cacheId && rawArguments) {
531
+ argumentsByToolCallId.set(cacheId, rawArguments);
532
+ }
533
+ const argumentsText = rawArguments ?? (cacheId ? argumentsByToolCallId.get(cacheId) : undefined);
534
+ if (!cacheId && !resolvedName) {
535
+ return null;
536
+ }
537
+ return {
538
+ ...cacheId ? { id: cacheId } : {},
539
+ ...resolvedName ? { name: sanitizeChannelProgressIdentifier(resolvedName, "tool") } : {},
540
+ ...argumentsText ? { argumentsText } : {}
541
+ };
542
+ }
543
+ function extractToolCalls(delta) {
544
+ const candidates = Array.isArray(delta.tool_calls) ? delta.tool_calls : delta.tool_calls ? [delta.tool_calls] : delta.tool_call ? [delta.tool_call] : [];
545
+ const summaries = [];
546
+ const seen = new Set;
547
+ for (const candidate of candidates) {
548
+ const summary = extractToolCallSummary(candidate);
549
+ if (!summary) {
550
+ continue;
551
+ }
552
+ const key = `${summary.id ?? ""}:${summary.name ?? ""}`;
553
+ if (seen.has(key)) {
554
+ continue;
555
+ }
556
+ seen.add(key);
557
+ summaries.push(summary);
558
+ }
559
+ return summaries;
560
+ }
561
+ function extractToolReturns(delta) {
562
+ const candidates = Array.isArray(delta.tool_returns) ? delta.tool_returns : [delta];
563
+ const summaries = [];
564
+ const seen = new Set;
565
+ for (const candidate of candidates) {
566
+ const record = asRecord(candidate);
567
+ if (!record) {
568
+ continue;
569
+ }
570
+ const summary = extractToolCallSummary(record);
571
+ if (!summary) {
572
+ continue;
573
+ }
574
+ const key = `${summary.id ?? ""}:${summary.name ?? ""}`;
575
+ if (seen.has(key)) {
576
+ continue;
577
+ }
578
+ seen.add(key);
579
+ const status = getToolStatus(record);
580
+ summaries.push({
581
+ summary,
582
+ status,
583
+ ...status === "error" ? { errorDetails: formatToolErrorDetails(record) } : {}
584
+ });
585
+ }
586
+ return summaries;
587
+ }
588
+ function buildToolCallUpdates(record, runId) {
589
+ const tools = extractToolCalls(record);
590
+ const updates = [];
591
+ for (const tool of tools) {
592
+ const toolDetails = formatToolProgressDetails(tool, options);
593
+ const toolTitle = formatToolProgressTitle(tool, "started");
594
+ updates.push(withRunId({
595
+ kind: "tool",
596
+ state: "started",
597
+ message: `Preparing tool${toolNameForMessage(tool)}`,
598
+ ...tool.id ? { toolCallId: tool.id } : {},
599
+ ...tool.name ? { toolName: tool.name } : {},
600
+ ...toolDetails ? { toolDetails } : {},
601
+ ...toolTitle ? { toolTitle } : {}
602
+ }, runId));
603
+ }
604
+ return updates;
605
+ }
606
+ function buildUpdates(delta) {
607
+ const record = asRecord(delta);
608
+ if (!record) {
609
+ return [];
610
+ }
611
+ const messageType = getMessageType(record);
612
+ const runId = getRunId(record);
613
+ switch (messageType) {
614
+ case "reasoning_message":
615
+ return [
616
+ withRunId({
617
+ kind: "thinking",
618
+ state: "updated",
619
+ message: "Thinking"
620
+ }, runId)
621
+ ];
622
+ case "assistant_message":
623
+ return [
624
+ withRunId({
625
+ kind: "responding",
626
+ state: "updated",
627
+ message: "Writing reply"
628
+ }, runId)
629
+ ];
630
+ case "approval_request_message":
631
+ return buildToolCallUpdates(record, runId);
632
+ case "tool_call_message": {
633
+ const updates = buildToolCallUpdates(record, runId);
634
+ if (updates.length === 0) {
635
+ return [
636
+ withRunId({
637
+ kind: "tool",
638
+ state: "started",
639
+ message: "Preparing tool call"
640
+ }, runId)
641
+ ];
642
+ }
643
+ return updates;
644
+ }
645
+ case "tool_return_message": {
646
+ const toolReturns = extractToolReturns(record);
647
+ const updates = [];
648
+ for (const { summary, status, errorDetails } of toolReturns) {
649
+ const accumulatedArgs = summary.id ? argumentsByToolCallId.get(summary.id) : undefined;
650
+ if (summary.id) {
651
+ argumentsByToolCallId.delete(summary.id);
652
+ namesByToolCallId.delete(summary.id);
653
+ }
654
+ const toolWithAccumulatedArgs = accumulatedArgs ? { ...summary, argumentsText: accumulatedArgs } : summary;
655
+ const toolDetails = formatToolProgressDetails(toolWithAccumulatedArgs, options);
656
+ const toolTitle = formatToolProgressTitle(toolWithAccumulatedArgs, status);
657
+ updates.push(withRunId({
658
+ kind: "tool",
659
+ state: status,
660
+ message: status === "error" ? "Tool failed" : "Tool finished",
661
+ ...summary.id ? { toolCallId: summary.id } : {},
662
+ ...summary.name ? { toolName: summary.name } : {},
663
+ ...toolDetails ? { toolDetails } : {},
664
+ ...status === "error" && errorDetails ? { errorDetails } : {},
665
+ ...toolTitle ? { toolTitle } : {}
666
+ }, runId));
667
+ }
668
+ return updates;
669
+ }
670
+ case "client_tool_start": {
671
+ const tool = extractClientToolSummary(record);
672
+ const toolDetails = tool ? formatToolProgressDetails(tool, options) : undefined;
673
+ const toolTitle = tool ? formatToolProgressTitle(tool, "started") : undefined;
674
+ return [
675
+ withRunId({
676
+ kind: "tool",
677
+ state: "started",
678
+ message: "Running tool",
679
+ ...tool?.id ? { toolCallId: tool.id } : {},
680
+ ...tool?.name ? { toolName: tool.name } : {},
681
+ ...toolDetails ? { toolDetails } : {},
682
+ ...toolTitle ? { toolTitle } : {}
683
+ }, runId)
684
+ ];
685
+ }
686
+ case "client_tool_end": {
687
+ const state = getToolStatus(record);
688
+ const tool = extractClientToolSummary(record);
689
+ const accumulatedArgs = tool?.id ? argumentsByToolCallId.get(tool.id) : undefined;
690
+ if (tool?.id) {
691
+ argumentsByToolCallId.delete(tool.id);
692
+ namesByToolCallId.delete(tool.id);
693
+ }
694
+ const toolWithAccumulatedArgs = tool && accumulatedArgs ? { ...tool, argumentsText: accumulatedArgs } : tool;
695
+ const toolDetails = toolWithAccumulatedArgs ? formatToolProgressDetails(toolWithAccumulatedArgs, options) : undefined;
696
+ const errorDetails = state === "error" ? formatToolErrorDetails(record) : undefined;
697
+ const toolTitle = toolWithAccumulatedArgs ? formatToolProgressTitle(toolWithAccumulatedArgs, state) : undefined;
698
+ return [
699
+ withRunId({
700
+ kind: "tool",
701
+ state,
702
+ message: state === "error" ? "Tool failed" : "Tool finished",
703
+ ...tool?.id ? { toolCallId: tool.id } : {},
704
+ ...tool?.name ? { toolName: tool.name } : {},
705
+ ...toolDetails ? { toolDetails } : {},
706
+ ...errorDetails ? { errorDetails } : {},
707
+ ...toolTitle ? { toolTitle } : {}
708
+ }, runId)
709
+ ];
710
+ }
711
+ case "slash_command_start": {
712
+ const command = getSlashCommand(record);
713
+ return [
714
+ withRunId({
715
+ kind: "command",
716
+ state: "started",
717
+ message: `Running ${command}`,
718
+ command
719
+ }, runId)
720
+ ];
721
+ }
722
+ case "slash_command_end": {
723
+ const command = getSlashCommand(record);
724
+ const success = record.success !== false;
725
+ return [
726
+ withRunId({
727
+ kind: "command",
728
+ state: success ? "completed" : "error",
729
+ message: success ? `${command} finished` : `${command} failed`,
730
+ command
731
+ }, runId)
732
+ ];
733
+ }
734
+ case "command_start": {
735
+ const command = getCommandId(record);
736
+ return [
737
+ withRunId({
738
+ kind: "command",
739
+ state: "started",
740
+ message: "Running command",
741
+ command
742
+ }, runId)
743
+ ];
744
+ }
745
+ case "command_end": {
746
+ const command = getCommandId(record);
747
+ const success = record.success !== false;
748
+ return [
749
+ withRunId({
750
+ kind: "command",
751
+ state: success ? "completed" : "error",
752
+ message: success ? "Command finished" : "Command failed",
753
+ command
754
+ }, runId)
755
+ ];
756
+ }
757
+ case "status": {
758
+ const message = sanitizeChannelProgressText(record.message);
759
+ if (!message) {
760
+ return [];
761
+ }
762
+ return [
763
+ withRunId({
764
+ kind: "status",
765
+ state: "updated",
766
+ message
767
+ }, runId)
768
+ ];
769
+ }
770
+ case "retry": {
771
+ const attempt = Number(record.attempt);
772
+ const maxAttempts = Number(record.max_attempts ?? record.maxAttempts);
773
+ const suffix = Number.isFinite(attempt) && Number.isFinite(maxAttempts) ? ` (${attempt}/${maxAttempts})` : "";
774
+ return [
775
+ withRunId({
776
+ kind: "retry",
777
+ state: "updated",
778
+ message: `Retrying request${suffix}`
779
+ }, runId)
780
+ ];
781
+ }
782
+ case "loop_error":
783
+ return [
784
+ withRunId({
785
+ kind: "error",
786
+ state: "error",
787
+ message: "Encountered an error"
788
+ }, runId)
789
+ ];
790
+ default:
791
+ return [];
792
+ }
793
+ }
794
+ return { buildUpdates };
795
+ }
796
+
797
+ // src/channels/gateway-core.ts
798
+ var CHANNEL_GATEWAY_TOOL_SCOPE_ID = "channel-gateway";
799
+ var MAX_ACCEPTED_CLIENT_MESSAGE_IDS = 2048;
800
+ function runtimeKey(runtime) {
801
+ return `${runtime.agent_id}:${runtime.conversation_id}`;
802
+ }
803
+ function sourceKey(source) {
804
+ return [
805
+ source.channel,
806
+ source.accountId ?? "",
807
+ source.chatId,
808
+ source.threadId ?? ""
809
+ ].join(":");
810
+ }
811
+ function uniqueSources(sources) {
812
+ const byKey = new Map;
813
+ for (const source of sources)
814
+ byKey.set(sourceKey(source), source);
815
+ return [...byKey.values()];
816
+ }
817
+ function stopReasonFromDelta(message) {
818
+ const delta = message.delta;
819
+ return delta.message_type === "stop_reason" && "stop_reason" in delta && typeof delta.stop_reason === "string" ? delta.stop_reason : null;
820
+ }
821
+ function runIdFromDelta(message) {
822
+ const runId = "run_id" in message.delta ? message.delta.run_id : undefined;
823
+ return typeof runId === "string" && runId.length > 0 ? runId : undefined;
824
+ }
825
+ function lifecycleOutcome(stopReason) {
826
+ if (stopReason === "cancelled")
827
+ return "cancelled";
828
+ if (stopReason === "end_turn" || stopReason === "tool_rule") {
829
+ return "completed";
830
+ }
831
+ return "error";
832
+ }
833
+ function errorFromDelta(message) {
834
+ const delta = message.delta;
835
+ if (delta.message_type !== "loop_error")
836
+ return;
837
+ return delta.message;
838
+ }
839
+
840
+ class ChannelGateway {
841
+ client;
842
+ hooks;
843
+ states = new Map;
844
+ disposers = [];
845
+ constructor(client, hooks) {
846
+ this.client = client;
847
+ this.hooks = hooks;
848
+ this.disposers.push(client.onMessage((message) => this.handleMessage(message)), client.onExternalToolCall((request) => {
849
+ const sources = request.runtime ? this.states.get(runtimeKey(request.runtime))?.active?.sources ?? [] : [];
850
+ return hooks.executeExternalTool(request, sources);
851
+ }));
852
+ }
853
+ close() {
854
+ for (const dispose of this.disposers.splice(0))
855
+ dispose();
856
+ this.client.close();
857
+ this.states.clear();
858
+ }
859
+ async submit(delivery) {
860
+ const state = this.getState(delivery.runtime);
861
+ const submission = state.submissionQueue.then(() => this.submitDelivery(state, delivery));
862
+ state.submissionQueue = submission.then(() => {
863
+ return;
864
+ }, () => {
865
+ return;
866
+ });
867
+ return submission;
868
+ }
869
+ async submitDelivery(state, delivery) {
870
+ if (state.acceptedClientMessageIds.has(delivery.clientMessageId)) {
871
+ state.acceptedClientMessageIds.delete(delivery.clientMessageId);
872
+ state.acceptedClientMessageIds.add(delivery.clientMessageId);
873
+ return true;
874
+ }
875
+ state.pendingSourcesByClientMessageId.set(delivery.clientMessageId, {
876
+ sources: uniqueSources(delivery.sources),
877
+ disposition: "submitting"
878
+ });
879
+ try {
880
+ await this.ensureRuntimeRegistration(state, delivery);
881
+ const response = await this.client.submitInput({
882
+ runtime: delivery.runtime,
883
+ payload: {
884
+ kind: "create_message",
885
+ messages: [
886
+ {
887
+ role: "user",
888
+ content: delivery.content,
889
+ client_message_id: delivery.clientMessageId
890
+ }
891
+ ],
892
+ external_tool_scope_ids: [CHANNEL_GATEWAY_TOOL_SCOPE_ID],
893
+ image_failure_mode: "drop"
894
+ }
895
+ });
896
+ if (!response.accepted) {
897
+ state.pendingSourcesByClientMessageId.delete(delivery.clientMessageId);
898
+ return false;
899
+ }
900
+ state.acceptedClientMessageIds.add(delivery.clientMessageId);
901
+ if (state.acceptedClientMessageIds.size > MAX_ACCEPTED_CLIENT_MESSAGE_IDS) {
902
+ const oldest = state.acceptedClientMessageIds.values().next().value;
903
+ if (oldest)
904
+ state.acceptedClientMessageIds.delete(oldest);
905
+ }
906
+ const queuedEvents = delivery.sources.map((source) => this.enqueueHook(state, () => this.hooks.onLifecycle({ type: "queued", source })));
907
+ if (response.disposition === "started") {
908
+ this.activateSources(state, delivery.clientMessageId, delivery.sources);
909
+ state.pendingSourcesByClientMessageId.delete(delivery.clientMessageId);
910
+ } else if (response.disposition === "queued") {
911
+ const pending = state.pendingSourcesByClientMessageId.get(delivery.clientMessageId);
912
+ if (pending) {
913
+ pending.disposition = "queued";
914
+ pending.acceptedAtQueueRevision = state.queueRevision;
915
+ }
916
+ }
917
+ await Promise.all(queuedEvents);
918
+ return true;
919
+ } catch (error) {
920
+ state.pendingSourcesByClientMessageId.delete(delivery.clientMessageId);
921
+ throw error;
922
+ }
923
+ }
924
+ async restoreRuntime(runtime, sources) {
925
+ const state = this.getState(runtime);
926
+ state.replayedControlRequestIds.clear();
927
+ let recoveredTurn = null;
928
+ if (!state.active) {
929
+ recoveredTurn = {
930
+ batchId: `channel-recovered-${crypto.randomUUID()}`,
931
+ sources: uniqueSources(sources),
932
+ progress: createChannelTurnProgressBuilder(),
933
+ richDraft: null
934
+ };
935
+ state.active = recoveredTurn;
936
+ }
937
+ try {
938
+ await this.registerRuntime(runtime, sources);
939
+ } catch (error) {
940
+ if (state.active === recoveredTurn)
941
+ state.active = null;
942
+ throw error;
943
+ }
944
+ const replayedRequestIds = new Set(state.replayedControlRequestIds);
945
+ if (replayedRequestIds.size === 0 && state.active === recoveredTurn) {
946
+ state.active = null;
947
+ }
948
+ return replayedRequestIds;
949
+ }
950
+ async registerRuntime(runtime, sources = [], defaultPermissionMode) {
951
+ const state = this.getState(runtime);
952
+ await this.ensureRuntimeRegistration(state, {
953
+ runtime,
954
+ content: "",
955
+ sources,
956
+ clientMessageId: "recovered",
957
+ ...defaultPermissionMode ? { defaultPermissionMode } : {}
958
+ });
959
+ }
960
+ async submitApprovalResponse(runtime, response) {
961
+ const result = await this.client.submitInput({
962
+ runtime,
963
+ payload: { kind: "approval_response", ...response }
964
+ });
965
+ return result.accepted;
966
+ }
967
+ getModelStatus(runtime) {
968
+ return this.states.get(runtimeKey(runtime))?.modelStatus ?? null;
969
+ }
970
+ updateModelStatus(runtime, modelHandle) {
971
+ const state = this.getState(runtime);
972
+ state.modelStatus = {
973
+ modelHandle,
974
+ scope: runtime.conversation_id === "default" ? "agent" : "conversation"
975
+ };
976
+ }
977
+ getState(runtime) {
978
+ const key = runtimeKey(runtime);
979
+ let state = this.states.get(key);
980
+ if (!state) {
981
+ state = {
982
+ runtime,
983
+ pendingSourcesByClientMessageId: new Map,
984
+ queueRevision: 0,
985
+ active: null,
986
+ registrationSignature: null,
987
+ registration: null,
988
+ replayedControlRequestIds: new Set,
989
+ submissionQueue: Promise.resolve(),
990
+ hookQueue: null,
991
+ acceptedClientMessageIds: new Set,
992
+ modelStatus: null
993
+ };
994
+ this.states.set(key, state);
995
+ }
996
+ return state;
997
+ }
998
+ enqueueHook(state, hook) {
999
+ let pending;
1000
+ if (state.hookQueue) {
1001
+ pending = state.hookQueue.then(hook);
1002
+ } else {
1003
+ try {
1004
+ pending = Promise.resolve(hook());
1005
+ } catch (error) {
1006
+ pending = Promise.reject(error);
1007
+ }
1008
+ }
1009
+ const settled = pending.then(() => {
1010
+ return;
1011
+ }, () => {
1012
+ return;
1013
+ });
1014
+ state.hookQueue = settled;
1015
+ settled.then(() => {
1016
+ if (state.hookQueue === settled)
1017
+ state.hookQueue = null;
1018
+ });
1019
+ return pending;
1020
+ }
1021
+ async ensureRuntimeRegistration(state, delivery) {
1022
+ const tool = await this.hooks.buildExternalTool(delivery.runtime, delivery.sources);
1023
+ const signature = JSON.stringify({
1024
+ mode: delivery.defaultPermissionMode ?? null,
1025
+ tool
1026
+ });
1027
+ if (state.registrationSignature === signature && state.registration) {
1028
+ return state.registration;
1029
+ }
1030
+ const registration = this.client.runtimeStart({
1031
+ agent_id: delivery.runtime.agent_id,
1032
+ conversation_id: delivery.runtime.conversation_id,
1033
+ ...delivery.defaultPermissionMode ? { mode: delivery.defaultPermissionMode } : {},
1034
+ recover_approvals: true,
1035
+ force_device_status: false,
1036
+ wait_for_replay: true,
1037
+ client_info: { name: "channel-gateway", title: "Channel Gateway" },
1038
+ external_tools: [
1039
+ {
1040
+ scope_id: CHANNEL_GATEWAY_TOOL_SCOPE_ID,
1041
+ tools: [tool]
1042
+ }
1043
+ ]
1044
+ }).then((response) => {
1045
+ if (!response.success) {
1046
+ throw new Error(response.error ?? "Failed to register channel runtime");
1047
+ }
1048
+ const agentRecord = response.agent;
1049
+ const conversationRecord = response.conversation;
1050
+ const agentModel = typeof agentRecord?.model === "string" ? agentRecord.model : response.agent?.llm_config?.model ?? null;
1051
+ const conversationModel = typeof conversationRecord?.model === "string" ? conversationRecord.model : null;
1052
+ state.modelStatus = {
1053
+ modelHandle: delivery.runtime.conversation_id === "default" ? agentModel : conversationModel ?? agentModel,
1054
+ scope: delivery.runtime.conversation_id === "default" ? "agent" : "conversation"
1055
+ };
1056
+ });
1057
+ state.registrationSignature = signature;
1058
+ state.registration = registration;
1059
+ try {
1060
+ await registration;
1061
+ } catch (error) {
1062
+ if (state.registration === registration) {
1063
+ state.registration = null;
1064
+ state.registrationSignature = null;
1065
+ }
1066
+ throw error;
1067
+ }
1068
+ }
1069
+ handleMessage(message) {
1070
+ if (message.type === "update_queue") {
1071
+ this.handleQueueUpdate(message);
1072
+ return;
1073
+ }
1074
+ if (message.type === "stream_delta") {
1075
+ this.handleStreamDelta(message);
1076
+ return;
1077
+ }
1078
+ if (message.type === "turn_finished") {
1079
+ this.handleTurnFinished(message.runtime, {
1080
+ stopReason: message.stop_reason,
1081
+ runId: message.run_id,
1082
+ error: message.error
1083
+ });
1084
+ return;
1085
+ }
1086
+ if (message.type === "control_request") {
1087
+ this.handleControlRequest(message);
1088
+ }
1089
+ }
1090
+ handleQueueUpdate(message) {
1091
+ const state = this.getState(message.runtime);
1092
+ state.queueRevision += 1;
1093
+ const nextQueued = new Set(message.queue.map((entry) => entry.client_message_id));
1094
+ const removed = [];
1095
+ for (const [
1096
+ clientMessageId,
1097
+ pending
1098
+ ] of state.pendingSourcesByClientMessageId) {
1099
+ if (pending.disposition === "queued" && state.queueRevision > (pending.acceptedAtQueueRevision ?? -1) && !nextQueued.has(clientMessageId)) {
1100
+ removed.push({ clientMessageId, sources: pending.sources });
1101
+ state.pendingSourcesByClientMessageId.delete(clientMessageId);
1102
+ }
1103
+ }
1104
+ if (!state.active && removed.length > 0) {
1105
+ const first = removed[0];
1106
+ if (first) {
1107
+ this.activateSources(state, first.clientMessageId, removed.flatMap((entry) => entry.sources));
1108
+ }
1109
+ }
1110
+ }
1111
+ activateSources(state, clientMessageId, sources) {
1112
+ if (state.active) {
1113
+ return;
1114
+ }
1115
+ state.active = {
1116
+ batchId: `channel-${clientMessageId}`,
1117
+ sources: uniqueSources(sources),
1118
+ progress: createChannelTurnProgressBuilder(),
1119
+ richDraft: this.hooks.createRichDraft?.({
1120
+ batchId: `channel-${clientMessageId}`,
1121
+ sources
1122
+ }) ?? null
1123
+ };
1124
+ const processingEvent = {
1125
+ type: "processing",
1126
+ batchId: state.active.batchId,
1127
+ sources: state.active.sources
1128
+ };
1129
+ this.enqueueHook(state, () => this.hooks.onLifecycle(processingEvent));
1130
+ }
1131
+ handleStreamDelta(message) {
1132
+ const state = this.getState(message.runtime);
1133
+ const active = state.active;
1134
+ if (!active)
1135
+ return;
1136
+ const runId = runIdFromDelta(message);
1137
+ if (runId)
1138
+ active.runId = runId;
1139
+ const deltaError = errorFromDelta(message);
1140
+ if (deltaError)
1141
+ active.error = deltaError;
1142
+ for (const update of active.progress.buildUpdates(message.delta)) {
1143
+ this.enqueueHook(state, () => this.hooks.onProgress({
1144
+ type: "progress",
1145
+ batchId: active.batchId,
1146
+ sources: active.sources,
1147
+ ...update
1148
+ }));
1149
+ }
1150
+ active.richDraft?.handleDelta(message.delta);
1151
+ const stopReason = stopReasonFromDelta(message);
1152
+ if (!stopReason)
1153
+ return;
1154
+ if (stopReason === "requires_approval") {
1155
+ active.richDraft?.flushPending();
1156
+ return;
1157
+ }
1158
+ if (stopReason === "end_turn")
1159
+ active.richDraft?.flushPending();
1160
+ this.handleTurnFinished(message.runtime, {
1161
+ stopReason,
1162
+ runId: active.runId,
1163
+ error: errorFromDelta(message)
1164
+ });
1165
+ }
1166
+ handleTurnFinished(runtime, terminal) {
1167
+ const state = this.getState(runtime);
1168
+ const active = state.active;
1169
+ if (!active || terminal.stopReason === "requires_approval")
1170
+ return;
1171
+ state.active = null;
1172
+ active.richDraft?.dispose();
1173
+ this.enqueueHook(state, () => this.hooks.onLifecycle({
1174
+ type: "finished",
1175
+ batchId: active.batchId,
1176
+ sources: active.sources,
1177
+ outcome: lifecycleOutcome(terminal.stopReason),
1178
+ stopReason: terminal.stopReason,
1179
+ ...terminal.runId ?? active.runId ? { runId: terminal.runId ?? active.runId } : {},
1180
+ ...terminal.error ?? active.error ? { error: terminal.error ?? active.error } : {}
1181
+ }));
1182
+ }
1183
+ handleControlRequest(message) {
1184
+ if (!message.agent_id || !message.conversation_id)
1185
+ return;
1186
+ const state = this.states.get(runtimeKey({
1187
+ agent_id: message.agent_id,
1188
+ conversation_id: message.conversation_id
1189
+ }));
1190
+ if (!state)
1191
+ return;
1192
+ const sources = state.active?.sources ?? [];
1193
+ state.replayedControlRequestIds.add(message.request_id);
1194
+ const sourceScopes = new Map(sources.map((source2) => [sourceKey(source2), source2]));
1195
+ if (sourceScopes.size !== 1)
1196
+ return;
1197
+ const source = [...sourceScopes.values()][0];
1198
+ if (!source)
1199
+ return;
1200
+ this.enqueueHook(state, () => this.hooks.onControlRequest({
1201
+ requestId: message.request_id,
1202
+ kind: getInteractiveApprovalKind(message.request.tool_name) ?? "generic_tool_approval",
1203
+ source,
1204
+ toolName: message.request.tool_name,
1205
+ input: message.request.input
1206
+ }));
1207
+ }
1208
+ }
1209
+ // src/channels/message-channel-formatting.ts
1210
+ var TELEGRAM_CHANNEL_ID = "telegram";
1211
+ var SIGNAL_CHANNEL_ID = "signal";
1212
+ var TELEGRAM_PLACEHOLDER_PREFIX = "LCTELEGRAMHTMLPLACEHOLDER";
1213
+ var TELEGRAM_PLACEHOLDER_SUFFIX = "X";
1214
+ var TELEGRAM_PLACEHOLDER_PATTERN = /LCTELEGRAMHTMLPLACEHOLDER(\d+)X/g;
1215
+ var SLACK_PLACEHOLDER_PREFIX = "LCSLACKMRKDWNPLACEHOLDER";
1216
+ var SLACK_PLACEHOLDER_SUFFIX = "X";
1217
+ var SLACK_PLACEHOLDER_PATTERN = /LCSLACKMRKDWNPLACEHOLDER(\d+)X/g;
1218
+ var SLACK_ANGLE_TOKEN_RE = /<[^>\n]+>/g;
1219
+ function decodeBasicXmlEntities(text) {
1220
+ return text.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
1221
+ }
1222
+ function escapeTelegramHtml(text) {
1223
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1224
+ }
1225
+ function escapeTelegramHtmlAttribute(text) {
1226
+ return escapeTelegramHtml(text).replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1227
+ }
1228
+ function createTelegramPlaceholder(placeholders, value) {
1229
+ const placeholder = `${TELEGRAM_PLACEHOLDER_PREFIX}${placeholders.length}${TELEGRAM_PLACEHOLDER_SUFFIX}`;
1230
+ placeholders.push(value);
1231
+ return placeholder;
1232
+ }
1233
+ function restoreTelegramPlaceholders(text, placeholders) {
1234
+ return text.replace(TELEGRAM_PLACEHOLDER_PATTERN, (_match, index) => {
1235
+ return placeholders[Number(index)] ?? "";
1236
+ });
1237
+ }
1238
+ function createSlackPlaceholder(placeholders, value) {
1239
+ const placeholder = `${SLACK_PLACEHOLDER_PREFIX}${placeholders.length}${SLACK_PLACEHOLDER_SUFFIX}`;
1240
+ placeholders.push(value);
1241
+ return placeholder;
1242
+ }
1243
+ function restoreSlackPlaceholders(text, placeholders) {
1244
+ return text.replace(SLACK_PLACEHOLDER_PATTERN, (_match, index) => {
1245
+ return placeholders[Number(index)] ?? "";
1246
+ });
1247
+ }
1248
+ function replaceFencedCodeBlocks(text, placeholders) {
1249
+ return text.replace(/```([^\n`]*)\n?([\s\S]*?)```/g, (_match, _lang, code) => {
1250
+ return createTelegramPlaceholder(placeholders, `<pre>${escapeTelegramHtml(String(code).trimEnd())}</pre>`);
1251
+ });
1252
+ }
1253
+ function replaceInlineCode(text, placeholders) {
1254
+ return text.replace(/`([^`\n]+)`/g, (_match, code) => {
1255
+ return createTelegramPlaceholder(placeholders, `<code>${escapeTelegramHtml(String(code))}</code>`);
1256
+ });
1257
+ }
1258
+ function parseMarkdownLink(text, startIndex) {
1259
+ if (text[startIndex] !== "[") {
1260
+ return null;
1261
+ }
1262
+ let labelEnd = startIndex + 1;
1263
+ let bracketDepth = 1;
1264
+ while (labelEnd < text.length) {
1265
+ const char = text[labelEnd];
1266
+ if (char === "\\") {
1267
+ labelEnd += 2;
1268
+ continue;
1269
+ }
1270
+ if (char === "[") {
1271
+ bracketDepth++;
1272
+ } else if (char === "]") {
1273
+ bracketDepth--;
1274
+ if (bracketDepth === 0) {
1275
+ break;
1276
+ }
1277
+ }
1278
+ labelEnd++;
1279
+ }
1280
+ if (bracketDepth !== 0 || text[labelEnd + 1] !== "(") {
1281
+ return null;
1282
+ }
1283
+ let urlEnd = labelEnd + 2;
1284
+ let parenDepth = 1;
1285
+ while (urlEnd < text.length) {
1286
+ const char = text[urlEnd];
1287
+ if (char === "\\") {
1288
+ urlEnd += 2;
1289
+ continue;
1290
+ }
1291
+ if (char === "(") {
1292
+ parenDepth++;
1293
+ } else if (char === ")") {
1294
+ parenDepth--;
1295
+ if (parenDepth === 0) {
1296
+ break;
1297
+ }
1298
+ }
1299
+ urlEnd++;
1300
+ }
1301
+ if (parenDepth !== 0) {
1302
+ return null;
1303
+ }
1304
+ const label = text.slice(startIndex + 1, labelEnd);
1305
+ const url = text.slice(labelEnd + 2, urlEnd).trim();
1306
+ if (!url) {
1307
+ return null;
1308
+ }
1309
+ return {
1310
+ label,
1311
+ url,
1312
+ endIndex: urlEnd + 1
1313
+ };
1314
+ }
1315
+ function replaceMarkdownLinks(text, placeholders, renderLabel) {
1316
+ let result = "";
1317
+ let index = 0;
1318
+ while (index < text.length) {
1319
+ if (text[index] !== "[") {
1320
+ result += text[index];
1321
+ index++;
1322
+ continue;
1323
+ }
1324
+ const link = parseMarkdownLink(text, index);
1325
+ if (!link) {
1326
+ result += text[index];
1327
+ index++;
1328
+ continue;
1329
+ }
1330
+ result += createTelegramPlaceholder(placeholders, `<a href="${escapeTelegramHtmlAttribute(link.url)}">${renderLabel(link.label)}</a>`);
1331
+ index = link.endIndex;
1332
+ }
1333
+ return result;
1334
+ }
1335
+ function applyTelegramInlineFormatting(text) {
1336
+ return text.replace(/\*\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*\*/g, "<b><i>$1</i></b>").replace(/___([^\s_](?:[\s\S]*?[^\s_])?)___/g, "<b><i>$1</i></b>").replace(/\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*/g, "<b>$1</b>").replace(/__([^\s_](?:[\s\S]*?[^\s_])?)__/g, "<b>$1</b>").replace(/~~([^\s~](?:[\s\S]*?[^\s~])?)~~/g, "<s>$1</s>").replace(/(^|[^\w*])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\w)/g, "$1<i>$2</i>").replace(/(^|[^\w_])_([^\s_](?:[\s\S]*?[^\s_])?)_(?!\w)/g, "$1<i>$2</i>");
1337
+ }
1338
+ function replaceTelegramBlockQuotes(text, placeholders) {
1339
+ const lines = text.split(`
1340
+ `);
1341
+ const formattedLines = [];
1342
+ for (let index = 0;index < lines.length; index++) {
1343
+ const quoteMatch = lines[index]?.match(/^ {0,3}> ?(.*)$/);
1344
+ if (!quoteMatch) {
1345
+ formattedLines.push(lines[index] ?? "");
1346
+ continue;
1347
+ }
1348
+ const quoteLines = [quoteMatch[1] ?? ""];
1349
+ while (index + 1 < lines.length) {
1350
+ const nextMatch = lines[index + 1]?.match(/^ {0,3}> ?(.*)$/);
1351
+ if (!nextMatch) {
1352
+ break;
1353
+ }
1354
+ quoteLines.push(nextMatch[1] ?? "");
1355
+ index++;
1356
+ }
1357
+ formattedLines.push(createTelegramPlaceholder(placeholders, `<blockquote>${formatTelegramText(quoteLines.join(`
1358
+ `), {
1359
+ enableBlockQuotes: false
1360
+ })}</blockquote>`));
1361
+ }
1362
+ return formattedLines.join(`
1363
+ `);
1364
+ }
1365
+ function formatTelegramText(text, options) {
1366
+ const placeholders = [];
1367
+ let result = replaceFencedCodeBlocks(text, placeholders);
1368
+ result = replaceInlineCode(result, placeholders);
1369
+ if (options?.enableLinks !== false) {
1370
+ result = replaceMarkdownLinks(result, placeholders, (label) => formatTelegramText(label, {
1371
+ enableBlockQuotes: false,
1372
+ enableLinks: false
1373
+ }));
1374
+ }
1375
+ if (options?.enableBlockQuotes !== false) {
1376
+ result = replaceTelegramBlockQuotes(result, placeholders);
1377
+ }
1378
+ result = escapeTelegramHtml(result);
1379
+ result = applyTelegramInlineFormatting(result);
1380
+ return restoreTelegramPlaceholders(result, placeholders);
1381
+ }
1382
+ function markdownToTelegramHtml(text) {
1383
+ return formatTelegramText(text);
1384
+ }
1385
+ function escapeSlackMrkdwnSegment(text) {
1386
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1387
+ }
1388
+ function isAllowedSlackAngleToken(token) {
1389
+ if (!token.startsWith("<") || !token.endsWith(">")) {
1390
+ return false;
1391
+ }
1392
+ const inner = token.slice(1, -1);
1393
+ return inner.startsWith("@") || inner.startsWith("#") || inner.startsWith("!") || inner.startsWith("mailto:") || inner.startsWith("tel:") || inner.startsWith("http://") || inner.startsWith("https://") || inner.startsWith("slack://");
1394
+ }
1395
+ function escapeSlackMrkdwnContent(text) {
1396
+ if (!text) {
1397
+ return "";
1398
+ }
1399
+ if (!text.includes("&") && !text.includes("<") && !text.includes(">")) {
1400
+ return text;
1401
+ }
1402
+ SLACK_ANGLE_TOKEN_RE.lastIndex = 0;
1403
+ const out = [];
1404
+ let lastIndex = 0;
1405
+ for (let match = SLACK_ANGLE_TOKEN_RE.exec(text);match; match = SLACK_ANGLE_TOKEN_RE.exec(text)) {
1406
+ const matchIndex = match.index ?? 0;
1407
+ out.push(escapeSlackMrkdwnSegment(text.slice(lastIndex, matchIndex)));
1408
+ const token = match[0] ?? "";
1409
+ out.push(isAllowedSlackAngleToken(token) ? token : escapeSlackMrkdwnSegment(token));
1410
+ lastIndex = matchIndex + token.length;
1411
+ }
1412
+ out.push(escapeSlackMrkdwnSegment(text.slice(lastIndex)));
1413
+ return out.join("");
1414
+ }
1415
+ function escapeSlackMrkdwnText(text) {
1416
+ if (!text) {
1417
+ return "";
1418
+ }
1419
+ if (!text.includes("&") && !text.includes("<") && !text.includes(">")) {
1420
+ return text;
1421
+ }
1422
+ return text.split(`
1423
+ `).map((line) => {
1424
+ if (line.startsWith("> ")) {
1425
+ return `> ${escapeSlackMrkdwnContent(line.slice(2))}`;
1426
+ }
1427
+ return escapeSlackMrkdwnContent(line);
1428
+ }).join(`
1429
+ `);
1430
+ }
1431
+ function replaceSlackFencedCodeBlocks(text, placeholders) {
1432
+ return text.replace(/```([^\n`]*)\n?([\s\S]*?)```/g, (_match, _lang, code) => {
1433
+ const normalized = String(code).trimEnd();
1434
+ return createSlackPlaceholder(placeholders, normalized.length > 0 ? `\`\`\`
1435
+ ${normalized}
1436
+ \`\`\`` : "```\n```");
1437
+ });
1438
+ }
1439
+ function replaceSlackInlineCode(text, placeholders) {
1440
+ return text.replace(/`([^`\n]+)`/g, (_match, code) => {
1441
+ return createSlackPlaceholder(placeholders, `\`${String(code)}\``);
1442
+ });
1443
+ }
1444
+ function applySlackInlineFormatting(text) {
1445
+ return text.replace(/~~([^\s~](?:[\s\S]*?[^\s~])?)~~/g, "~$1~").replace(/(^|[^\w*])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\w)/g, "$1_$2_").replace(/\*\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*\*/g, "_*$1*_").replace(/___([^\s_](?:[\s\S]*?[^\s_])?)___/g, "_*$1*_").replace(/\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*/g, "*$1*").replace(/__([^\s_](?:[\s\S]*?[^\s_])?)__/g, "*$1*");
1446
+ }
1447
+ function formatSlackLinkLabel(text) {
1448
+ return applySlackInlineFormatting(escapeSlackMrkdwnText(text));
1449
+ }
1450
+ function replaceSlackMarkdownLinks(text, placeholders) {
1451
+ let result = "";
1452
+ let index = 0;
1453
+ while (index < text.length) {
1454
+ if (text[index] !== "[") {
1455
+ result += text[index];
1456
+ index++;
1457
+ continue;
1458
+ }
1459
+ const link = parseMarkdownLink(text, index);
1460
+ if (!link) {
1461
+ result += text[index];
1462
+ index++;
1463
+ continue;
1464
+ }
1465
+ result += createSlackPlaceholder(placeholders, `<${escapeSlackMrkdwnSegment(link.url)}|${formatSlackLinkLabel(link.label)}>`);
1466
+ index = link.endIndex;
1467
+ }
1468
+ return result;
1469
+ }
1470
+ function normalizeSlackBlockFormatting(text) {
1471
+ return text.split(`
1472
+ `).map((line) => {
1473
+ const headingMatch = line.match(/^\s{0,3}#{1,6}\s+(.+)$/);
1474
+ if (headingMatch) {
1475
+ return `*${headingMatch[1]?.trim() ?? ""}*`;
1476
+ }
1477
+ const bulletMatch = line.match(/^(\s*)[-+*]\s+(.+)$/);
1478
+ if (bulletMatch) {
1479
+ return `${bulletMatch[1] ?? ""}- ${bulletMatch[2] ?? ""}`;
1480
+ }
1481
+ return line;
1482
+ }).join(`
1483
+ `);
1484
+ }
1485
+ function formatSlackText(text, options) {
1486
+ const placeholders = [];
1487
+ let result = replaceSlackFencedCodeBlocks(text, placeholders);
1488
+ result = replaceSlackInlineCode(result, placeholders);
1489
+ if (options?.enableLinks !== false) {
1490
+ result = replaceSlackMarkdownLinks(result, placeholders);
1491
+ }
1492
+ result = escapeSlackMrkdwnText(result);
1493
+ result = applySlackInlineFormatting(result);
1494
+ result = normalizeSlackBlockFormatting(result);
1495
+ return restoreSlackPlaceholders(result, placeholders);
1496
+ }
1497
+ function markdownToSlackMrkdwn(text) {
1498
+ return formatSlackText(text);
1499
+ }
1500
+ var SIGNAL_INLINE_MARKERS = [
1501
+ { delimiter: "***", styles: ["BOLD", "ITALIC"] },
1502
+ { delimiter: "___", styles: ["BOLD", "ITALIC"] },
1503
+ { delimiter: "**", styles: ["BOLD"] },
1504
+ { delimiter: "__", styles: ["BOLD"] },
1505
+ { delimiter: "~~", styles: ["STRIKETHROUGH"] },
1506
+ { delimiter: "||", styles: ["SPOILER"] },
1507
+ { delimiter: "*", styles: ["ITALIC"], requireWordBoundary: true },
1508
+ { delimiter: "_", styles: ["ITALIC"], requireWordBoundary: true }
1509
+ ];
1510
+ function isEscaped(text, index) {
1511
+ let slashCount = 0;
1512
+ for (let i = index - 1;i >= 0 && text[i] === "\\"; i--) {
1513
+ slashCount++;
1514
+ }
1515
+ return slashCount % 2 === 1;
1516
+ }
1517
+ function isWordLike(char) {
1518
+ return !!char && /[A-Za-z0-9_]/.test(char);
1519
+ }
1520
+ function addSignalStyle(state, start, style) {
1521
+ const length = state.text.length - start;
1522
+ if (length <= 0) {
1523
+ return;
1524
+ }
1525
+ state.ranges.push({ start, length, style });
1526
+ }
1527
+ function canOpenSignalMarker(text, index, marker) {
1528
+ const next = text[index + marker.delimiter.length];
1529
+ if (!next || /\s/.test(next)) {
1530
+ return false;
1531
+ }
1532
+ if (!marker.requireWordBoundary) {
1533
+ return true;
1534
+ }
1535
+ const previous = text[index - 1];
1536
+ return !isWordLike(previous);
1537
+ }
1538
+ function isValidSignalMarkerContent(text, closeIndex, content, marker) {
1539
+ if (content.length === 0 || /^\s|\s$/.test(content)) {
1540
+ return false;
1541
+ }
1542
+ if (!marker.requireWordBoundary) {
1543
+ return true;
1544
+ }
1545
+ const next = text[closeIndex + marker.delimiter.length];
1546
+ return !isWordLike(next);
1547
+ }
1548
+ function findSignalClosingMarker(text, contentStart, marker) {
1549
+ let searchIndex = contentStart;
1550
+ while (searchIndex < text.length) {
1551
+ const closeIndex = text.indexOf(marker.delimiter, searchIndex);
1552
+ if (closeIndex < 0) {
1553
+ return -1;
1554
+ }
1555
+ if (isEscaped(text, closeIndex)) {
1556
+ searchIndex = closeIndex + marker.delimiter.length;
1557
+ continue;
1558
+ }
1559
+ const content = text.slice(contentStart, closeIndex);
1560
+ if (isValidSignalMarkerContent(text, closeIndex, content, marker)) {
1561
+ return closeIndex;
1562
+ }
1563
+ searchIndex = closeIndex + marker.delimiter.length;
1564
+ }
1565
+ return -1;
1566
+ }
1567
+ function parseSignalInline(text, state) {
1568
+ let index = 0;
1569
+ while (index < text.length) {
1570
+ if (text[index] === "\\" && index + 1 < text.length) {
1571
+ state.text += text[index + 1] ?? "";
1572
+ index += 2;
1573
+ continue;
1574
+ }
1575
+ if (text[index] === "`") {
1576
+ const closeIndex = text.indexOf("`", index + 1);
1577
+ if (closeIndex > index + 1 && !text.slice(index + 1, closeIndex).includes(`
1578
+ `)) {
1579
+ const start = state.text.length;
1580
+ state.text += text.slice(index + 1, closeIndex);
1581
+ addSignalStyle(state, start, "MONOSPACE");
1582
+ index = closeIndex + 1;
1583
+ continue;
1584
+ }
1585
+ }
1586
+ if (text[index] === "[") {
1587
+ const link = parseMarkdownLink(text, index);
1588
+ if (link) {
1589
+ parseSignalInline(link.label, state);
1590
+ state.text += ` (${link.url})`;
1591
+ index = link.endIndex;
1592
+ continue;
1593
+ }
1594
+ }
1595
+ const marker = SIGNAL_INLINE_MARKERS.find((candidate) => text.startsWith(candidate.delimiter, index) && !isEscaped(text, index) && canOpenSignalMarker(text, index, candidate));
1596
+ if (marker) {
1597
+ const contentStart = index + marker.delimiter.length;
1598
+ const closeIndex = findSignalClosingMarker(text, contentStart, marker);
1599
+ if (closeIndex >= 0) {
1600
+ const start = state.text.length;
1601
+ parseSignalInline(text.slice(contentStart, closeIndex), state);
1602
+ for (const style of marker.styles) {
1603
+ addSignalStyle(state, start, style);
1604
+ }
1605
+ index = closeIndex + marker.delimiter.length;
1606
+ continue;
1607
+ }
1608
+ }
1609
+ state.text += text[index] ?? "";
1610
+ index++;
1611
+ }
1612
+ }
1613
+ function parseSignalMarkdownLine(line, state) {
1614
+ const lineStyles = [];
1615
+ let content = line;
1616
+ const headingMatch = content.match(/^\s{0,3}#{1,6}\s+(.+)$/);
1617
+ if (headingMatch) {
1618
+ content = headingMatch[1]?.trim() ?? "";
1619
+ lineStyles.push("BOLD");
1620
+ } else {
1621
+ const quoteMatch = content.match(/^\s{0,3}> ?(.*)$/);
1622
+ if (quoteMatch) {
1623
+ content = quoteMatch[1] ?? "";
1624
+ lineStyles.push("ITALIC");
1625
+ } else {
1626
+ const bulletMatch = content.match(/^(\s*)[+*]\s+(.+)$/);
1627
+ if (bulletMatch) {
1628
+ content = `${bulletMatch[1] ?? ""}- ${bulletMatch[2] ?? ""}`;
1629
+ }
1630
+ }
1631
+ }
1632
+ const start = state.text.length;
1633
+ parseSignalInline(content, state);
1634
+ for (const style of lineStyles) {
1635
+ addSignalStyle(state, start, style);
1636
+ }
1637
+ }
1638
+ function flushSignalCodeBlock(state, lines) {
1639
+ const code = lines.join(`
1640
+ `).trimEnd();
1641
+ if (code.length === 0) {
1642
+ return;
1643
+ }
1644
+ const start = state.text.length;
1645
+ state.text += code;
1646
+ addSignalStyle(state, start, "MONOSPACE");
1647
+ }
1648
+ function signalTextStyleToString(range) {
1649
+ return `${range.start}:${range.length}:${range.style}`;
1650
+ }
1651
+ function markdownToSignalTextStyles(text) {
1652
+ const state = { text: "", ranges: [] };
1653
+ const lines = text.split(`
1654
+ `);
1655
+ let inCodeBlock = false;
1656
+ let codeBlockLines = [];
1657
+ for (let index = 0;index < lines.length; index++) {
1658
+ const line = lines[index] ?? "";
1659
+ const isLastLine = index === lines.length - 1;
1660
+ if (inCodeBlock) {
1661
+ if (/^\s{0,3}```\s*$/.test(line)) {
1662
+ flushSignalCodeBlock(state, codeBlockLines);
1663
+ codeBlockLines = [];
1664
+ inCodeBlock = false;
1665
+ if (!isLastLine) {
1666
+ state.text += `
1667
+ `;
1668
+ }
1669
+ } else {
1670
+ codeBlockLines.push(line);
1671
+ }
1672
+ continue;
1673
+ }
1674
+ if (/^\s{0,3}```[^`]*$/.test(line)) {
1675
+ inCodeBlock = true;
1676
+ codeBlockLines = [];
1677
+ continue;
1678
+ }
1679
+ parseSignalMarkdownLine(line, state);
1680
+ if (!isLastLine) {
1681
+ state.text += `
1682
+ `;
1683
+ }
1684
+ }
1685
+ if (inCodeBlock) {
1686
+ flushSignalCodeBlock(state, codeBlockLines);
1687
+ }
1688
+ const seenStyles = new Set;
1689
+ const textStyle = state.ranges.map(signalTextStyleToString).filter((style) => {
1690
+ if (seenStyles.has(style)) {
1691
+ return false;
1692
+ }
1693
+ seenStyles.add(style);
1694
+ return true;
1695
+ });
1696
+ return {
1697
+ text: state.text,
1698
+ ...textStyle.length > 0 ? { textStyle } : {}
1699
+ };
1700
+ }
1701
+ var CHANNEL_OUTBOUND_FORMATTERS = {
1702
+ [SIGNAL_CHANNEL_ID](text) {
1703
+ return markdownToSignalTextStyles(text);
1704
+ },
1705
+ [TELEGRAM_CHANNEL_ID](text) {
1706
+ return {
1707
+ text: markdownToTelegramHtml(text),
1708
+ parseMode: "HTML"
1709
+ };
1710
+ },
1711
+ slack(text) {
1712
+ return {
1713
+ text: markdownToSlackMrkdwn(text)
1714
+ };
1715
+ }
1716
+ };
1717
+ function formatOutboundChannelMessage(channel, text) {
1718
+ const normalizedText = decodeBasicXmlEntities(text);
1719
+ const formatter = CHANNEL_OUTBOUND_FORMATTERS[channel];
1720
+ if (!formatter) {
1721
+ return { text: normalizedText };
1722
+ }
1723
+ return formatter(normalizedText);
1724
+ }
1725
+
1726
+ // src/channels/message-channel-executor.ts
1727
+ function firstNonEmptyString2(...values) {
1728
+ for (const value of values) {
1729
+ if (typeof value === "string") {
1730
+ const trimmed = value.trim();
1731
+ if (trimmed.length > 0)
1732
+ return trimmed;
1733
+ }
1734
+ }
1735
+ return;
1736
+ }
1737
+ function firstDefinedBoolean(...values) {
1738
+ for (const value of values) {
1739
+ if (typeof value === "boolean")
1740
+ return value;
1741
+ }
1742
+ return;
1743
+ }
1744
+ function normalizeChatTarget(channel, value) {
1745
+ const trimmed = value.trim();
1746
+ if (channel === "signal")
1747
+ return trimmed;
1748
+ const parts = trimmed.split(":").map((part) => part.trim()).filter(Boolean);
1749
+ if (parts.length === 2 && /^[a-z_-]+$/i.test(parts[0] ?? "")) {
1750
+ return parts[1] ?? trimmed;
1751
+ }
1752
+ if (parts.length === 3 && /^[a-z_-]+$/i.test(parts[0] ?? "") && /^[a-z_-]+$/i.test(parts[1] ?? "")) {
1753
+ return parts[2] ?? trimmed;
1754
+ }
1755
+ return trimmed;
1756
+ }
1757
+ function normalizeMessageChannelInput(input, resolver) {
1758
+ const channel = firstNonEmptyString2(input.channel)?.toLowerCase();
1759
+ if (!channel)
1760
+ return "Error: MessageChannel requires channel.";
1761
+ if (!resolver.isSupportedChannel(channel)) {
1762
+ return `Error: Unsupported channel "${channel}".`;
1763
+ }
1764
+ const rawAction = firstNonEmptyString2(input.action);
1765
+ if (!rawAction)
1766
+ return "Error: MessageChannel requires action.";
1767
+ const action = rawAction.trim().toLowerCase();
1768
+ if (!action) {
1769
+ return `Error: Unsupported MessageChannel action "${input.action}".`;
1770
+ }
1771
+ const rawChatId = firstNonEmptyString2(input.chat_id);
1772
+ const rawTarget = firstNonEmptyString2(input.target);
1773
+ if (!rawChatId && !rawTarget || rawChatId && rawTarget) {
1774
+ return "Error: MessageChannel requires exactly one of chat_id or target.";
1775
+ }
1776
+ return {
1777
+ action,
1778
+ channel,
1779
+ ...rawChatId ? { chatId: normalizeChatTarget(channel, rawChatId) } : {},
1780
+ ...rawTarget ? { target: rawTarget } : {},
1781
+ accountId: firstNonEmptyString2(input.accountId),
1782
+ message: firstNonEmptyString2(input.message),
1783
+ replyToMessageId: firstNonEmptyString2(input.replyTo),
1784
+ threadId: firstNonEmptyString2(input.threadId) ?? null,
1785
+ messageId: firstNonEmptyString2(input.messageId),
1786
+ attachmentId: firstNonEmptyString2(input.attachmentId),
1787
+ emoji: firstNonEmptyString2(input.emoji),
1788
+ remove: firstDefinedBoolean(input.remove),
1789
+ mediaPath: firstNonEmptyString2(input.media),
1790
+ filename: firstNonEmptyString2(input.filename),
1791
+ title: firstNonEmptyString2(input.title)
1792
+ };
1793
+ }
1794
+ function buildMessageChannelRequest(input, chatId, threadId) {
1795
+ return {
1796
+ action: input.action,
1797
+ channel: input.channel,
1798
+ chatId,
1799
+ message: input.message,
1800
+ replyToMessageId: input.replyToMessageId,
1801
+ threadId: threadId ?? input.threadId ?? null,
1802
+ messageId: input.messageId,
1803
+ attachmentId: input.attachmentId,
1804
+ emoji: input.emoji,
1805
+ remove: input.remove,
1806
+ mediaPath: input.mediaPath,
1807
+ filename: input.filename,
1808
+ title: input.title
1809
+ };
1810
+ }
1811
+ function inferAccountIdFromChannelTurnSources(params) {
1812
+ const chatId = params.input.chatId;
1813
+ if (!chatId)
1814
+ return;
1815
+ const accountIds = new Set;
1816
+ for (const source of params.channelTurnSources ?? []) {
1817
+ if (source.channel !== params.input.channel || source.chatId !== chatId || source.agentId !== params.scope.agentId || source.conversationId !== params.scope.conversationId || params.input.threadId !== null && source.threadId !== params.input.threadId) {
1818
+ continue;
1819
+ }
1820
+ if (source.accountId?.trim())
1821
+ accountIds.add(source.accountId.trim());
1822
+ }
1823
+ return accountIds.size === 1 ? [...accountIds][0] : undefined;
1824
+ }
1825
+ function inferThreadIdFromChannelTurnSources(params) {
1826
+ if (!params.input.chatId || params.input.threadId !== null)
1827
+ return;
1828
+ const threadIds = new Set;
1829
+ for (const source of params.channelTurnSources ?? []) {
1830
+ if (source.channel !== params.input.channel || source.chatId !== params.input.chatId || source.agentId !== params.scope.agentId || source.conversationId !== params.scope.conversationId || params.accountId && source.accountId !== params.accountId) {
1831
+ continue;
1832
+ }
1833
+ const fallbackThreadId = params.input.channel === "slack" && source.chatType !== "direct" ? source.messageId : null;
1834
+ threadIds.add(source.threadId ?? fallbackThreadId ?? null);
1835
+ }
1836
+ return threadIds.size === 1 ? [...threadIds][0] : undefined;
1837
+ }
1838
+ function noRouteError(params) {
1839
+ return params.accountId ? `Error: No route for chat_id "${params.input.chatId}" on "${params.input.channel}" account "${params.accountId}" for this agent/conversation.` : `Error: No route for chat_id "${params.input.chatId}" on "${params.input.channel}" for this agent/conversation. If multiple channel accounts can receive this chat, pass accountId (from the channel notification's account_id) to disambiguate.`;
1840
+ }
1841
+ function validateResolvedRoute(context, scope, chatId, accountId) {
1842
+ const route = context.route;
1843
+ if (route.chatId !== chatId || route.agentId !== scope.agentId || route.conversationId !== scope.conversationId || accountId !== undefined && route.accountId !== accountId) {
1844
+ return "Error: Resolved MessageChannel route is outside the current execution scope.";
1845
+ }
1846
+ return null;
1847
+ }
1848
+ function buildProactiveRoute(params) {
1849
+ return {
1850
+ accountId: params.context.accountId,
1851
+ chatId: params.context.target.chatId,
1852
+ chatType: params.context.target.chatType,
1853
+ threadId: params.context.target.threadId ?? null,
1854
+ agentId: params.scope.agentId,
1855
+ conversationId: params.scope.conversationId
1856
+ };
1857
+ }
1858
+ async function dispatchMessageChannelAction(params) {
1859
+ const discovery = params.context.messageActions.describeMessageTool({
1860
+ accountId: params.context.route.accountId ?? null
1861
+ });
1862
+ const supportedActions = new Set(["send"]);
1863
+ for (const action of discovery.actions ?? [])
1864
+ supportedActions.add(action);
1865
+ if (!supportedActions.has(params.request.action)) {
1866
+ return `Error: Action "${params.request.action}" is not supported on ${params.request.channel}.`;
1867
+ }
1868
+ return await params.context.messageActions.handleAction({
1869
+ request: params.request,
1870
+ route: params.context.route,
1871
+ adapter: params.context.transport,
1872
+ formatText: (text) => formatOutboundChannelMessage(params.request.channel, text)
1873
+ });
1874
+ }
1875
+ async function executeMessageChannel(input, options) {
1876
+ const normalized = normalizeMessageChannelInput(input, options.resolver);
1877
+ if (typeof normalized === "string")
1878
+ return normalized;
1879
+ if (normalized.channel === "slack" && normalized.action === "download-file" && normalized.target) {
1880
+ return "Error: Slack download-file requires chat_id from a routed channel context; target is not supported.";
1881
+ }
1882
+ try {
1883
+ if (normalized.chatId) {
1884
+ const accountId = normalized.accountId ?? inferAccountIdFromChannelTurnSources({
1885
+ input: normalized,
1886
+ scope: options.scope,
1887
+ channelTurnSources: options.channelTurnSources
1888
+ });
1889
+ const context2 = await options.resolver.resolveRoutedContext({
1890
+ channel: normalized.channel,
1891
+ chatId: normalized.chatId,
1892
+ accountId,
1893
+ scope: options.scope
1894
+ });
1895
+ if (typeof context2 === "string")
1896
+ return context2;
1897
+ if (!context2)
1898
+ return noRouteError({ input: normalized, accountId });
1899
+ const routeError = validateResolvedRoute(context2, options.scope, normalized.chatId, accountId);
1900
+ if (routeError)
1901
+ return routeError;
1902
+ const inferredThreadId = inferThreadIdFromChannelTurnSources({
1903
+ input: normalized,
1904
+ scope: options.scope,
1905
+ accountId,
1906
+ channelTurnSources: options.channelTurnSources
1907
+ });
1908
+ const requestThreadId = normalized.action === "download-file" ? normalized.threadId : inferredThreadId ?? (normalized.channel === "telegram" && context2.route.chatType === "direct" ? normalized.threadId : context2.route.threadId ?? normalized.threadId);
1909
+ return await dispatchMessageChannelAction({
1910
+ request: buildMessageChannelRequest(normalized, normalized.chatId, requestThreadId),
1911
+ context: context2
1912
+ });
1913
+ }
1914
+ if (normalized.channel !== "slack") {
1915
+ return `Error: Explicit MessageChannel targets are not supported on ${normalized.channel}.`;
1916
+ }
1917
+ if (!options.resolver.resolveProactiveContext) {
1918
+ return "Error: Explicit MessageChannel targets are not supported on slack.";
1919
+ }
1920
+ const proactive = await options.resolver.resolveProactiveContext({
1921
+ channel: normalized.channel,
1922
+ target: normalized.target ?? "",
1923
+ accountId: normalized.accountId,
1924
+ scope: options.scope
1925
+ });
1926
+ if (typeof proactive === "string")
1927
+ return proactive;
1928
+ const context = {
1929
+ route: buildProactiveRoute({ context: proactive, scope: options.scope }),
1930
+ transport: proactive.transport,
1931
+ messageActions: proactive.messageActions
1932
+ };
1933
+ return await dispatchMessageChannelAction({
1934
+ request: buildMessageChannelRequest(normalized, proactive.target.chatId, proactive.target.threadId),
1935
+ context
1936
+ });
1937
+ } catch (error) {
1938
+ const message = error instanceof Error ? error.message : "unknown error";
1939
+ return `Error sending message to ${normalized.channel}: ${message}`;
1940
+ }
1941
+ }
1942
+ // src/tools/descriptions/MessageChannel.md
1943
+ var MessageChannel_default = '# MessageChannel\n\nSend a message or channel action to an external channel.\n\nWhen you receive a `<channel-notification>`, use this tool to reply directly to the user on the same external channel. A normal assistant response is not delivered back to the external channel automatically.\n\nThere are two supported send modes:\n- Reply mode: use `channel` + `chat_id` from the notification to respond in the current routed chat.\n- Proactive mode: use `channel` + `target` on supported channels to send to an explicit outbound destination.\n\nPreferred reply pattern:\n- `action="send"` to send a normal reply\n- `channel` + `chat_id` from the notification attributes\n- `message` for the text body\n\nParameters:\n- `action`: The action to perform. The exact available actions depend on the active channel plugins and are reflected in the JSON schema.\n- `channel`: The platform to send to.\n- `chat_id`: Reply target for the current routed chat. Use this when responding to a channel notification.\n- `target`: Explicit outbound target for proactive sends on supported channels.\n- `accountId`: Optional channel account selector when multiple eligible accounts are available.\n- `message`: Text body for `action="send"`.\n- `replyTo`: Optional message ID to reply to. Omit this unless you intentionally want the platform\'s quote/reply UI.\n- `messageId`: Optional target message id for message-scoped actions like reactions.\n- `emoji`: Optional reaction payload for channels that support reactions.\n- `remove`: Optional boolean to remove a reaction instead of adding it.\n- `media`: Optional absolute local file path for file/media uploads on channels that support uploads.\n- `filename`: Optional uploaded filename override when supported by the channel.\n- `title`: Optional uploaded attachment title when supported by the channel.\n\nRules:\n- Always pass `action` explicitly, even for a normal reply.\n- Pass exactly one of `chat_id` or `target`.\n- `react` should be its own call.\n- `upload-file` can include both `media` and `message` so the uploaded file has a caption/comment when the channel supports it.\n- Telegram supports `action="send-rich"` for Bot API Rich Messages from Markdown content. Use it for headings, lists, tables, rich block quotes, details blocks, formulas, and longer structured messages; use `upload-file` for local media files.\n\nTelegram rich messages:\n- In Telegram private chats, normal `action="send"` messages are sent through Bot API Rich Messages by default when the Telegram account enables `rich_private_chat_default`; with that setting disabled, use explicit `action="send-rich"` for rich delivery.\n- Use `action="send-rich"` with `channel="telegram"` for structured Markdown rendered by Telegram Bot API Rich Messages.\n- Use this when the output benefits from real headings, tables, block quotes, collapsible details, footnotes, task lists, or formulas.\n- The `message` field is passed as Telegram rich Markdown. Supported examples include:\n - headings: `# Heading`, `## Heading`\n - lists: `- item`, `1. item`, `- [ ] task`, `- [x] done`\n - tables: GitHub-style pipe tables\n - block quotes: `> quoted text`\n - collapsible details: `<details><summary>Title</summary>content</details>`\n - inline math: `$E = mc^2$`\n - display math: `$$E = mc^2$$` or fenced `math` code blocks\n - footnotes: `text[^id]` with `[^id]: definition`\n- Prefer dollar-delimited math. `\\(...\\)` and `\\[...\\]` do not reliably render as formulas in Telegram rich Markdown.\n- Do not use `send-rich` for local file uploads. Use `upload-file`; rich Markdown media blocks only support HTTP/HTTPS URLs.\n- Rich messages persist only when the final `send-rich` call executes. If Telegram draft streaming is enabled for the account, the channel runtime may show ephemeral previews automatically; do not try to manage draft lifecycle from the tool call.\n';
1944
+ // src/tools/schemas/MessageChannel.json
1945
+ var MessageChannel_default2 = {
1946
+ type: "object",
1947
+ properties: {
1948
+ action: {
1949
+ type: "string",
1950
+ description: "Action to perform. Prefer explicit values like 'send', 'react', or 'upload-file'."
1951
+ },
1952
+ channel: {
1953
+ type: "string",
1954
+ description: "The channel to send the message to (e.g., 'telegram')"
1955
+ },
1956
+ chat_id: {
1957
+ type: "string",
1958
+ description: "The chat/conversation ID to reply to (usually from the channel-notification attributes). Use this for replies in the current routed chat."
1959
+ },
1960
+ target: {
1961
+ type: "string",
1962
+ description: "Explicit outbound target for proactive sends on supported channels (for example, a Slack channel like '#general' or 'channel:C12345678', or a Slack user DM like 'user:U12345678')."
1963
+ },
1964
+ accountId: {
1965
+ type: "string",
1966
+ description: "Optional channel account identifier when multiple eligible channel accounts are available for proactive sends."
1967
+ },
1968
+ message: {
1969
+ type: "string",
1970
+ description: "Text body for action='send'."
1971
+ },
1972
+ replyTo: {
1973
+ type: "string",
1974
+ description: "Optional message ID to reply to. Omit unless you intentionally want the platform's quote/reply UI."
1975
+ },
1976
+ threadId: {
1977
+ type: "string",
1978
+ description: "Optional thread identifier override for threaded channels."
1979
+ },
1980
+ messageId: {
1981
+ type: "string",
1982
+ description: "Target message ID for actions like react."
1983
+ },
1984
+ emoji: {
1985
+ type: "string",
1986
+ description: "Emoji name for action='react'."
1987
+ },
1988
+ remove: {
1989
+ type: "boolean",
1990
+ description: "Set to true to remove the reaction instead of adding it."
1991
+ },
1992
+ media: {
1993
+ type: "string",
1994
+ description: "Absolute local file path for action='upload-file'."
1995
+ },
1996
+ filename: {
1997
+ type: "string",
1998
+ description: "Optional uploaded filename override for media attachments"
1999
+ },
2000
+ title: {
2001
+ type: "string",
2002
+ description: "Optional uploaded title override for media attachments"
2003
+ }
2004
+ },
2005
+ required: ["action", "channel"],
2006
+ additionalProperties: false
2007
+ };
2008
+
2009
+ // src/channels/message-channel-tool-definition.ts
2010
+ var TELEGRAM_RICH_RULE_RE = /\n- Telegram supports `action="send-rich"`[^\n]*\n?/;
2011
+ var TELEGRAM_RICH_SECTION_RE = /\n\nTelegram rich messages:\n[\s\S]*$/;
2012
+ var MESSAGE_CHANNEL_PARAMETER_LINE = (name) => new RegExp(`\\n- \`${name}\`:[^\\n]*`, "g");
2013
+ function asSchemaContributionArray(schema) {
2014
+ if (!schema)
2015
+ return [];
2016
+ return Array.isArray(schema) ? schema : [schema];
2017
+ }
2018
+ function collectDiscoveryActions(discovery) {
2019
+ return discovery?.actions ? Array.from(discovery.actions) : [];
2020
+ }
2021
+ function resolveMessageChannelToolChannels(channels) {
2022
+ const uniqueChannels = new Map;
2023
+ const accountIds = new Set;
2024
+ const actions = new Set(["send"]);
2025
+ const schemaContributions = [];
2026
+ for (const channel of channels) {
2027
+ if (!uniqueChannels.has(channel.channelId)) {
2028
+ uniqueChannels.set(channel.channelId, channel);
2029
+ }
2030
+ const accountId = channel.accountId?.trim();
2031
+ if (accountId)
2032
+ accountIds.add(accountId);
2033
+ const discovery = channel.messageActions?.describeMessageTool({
2034
+ accountId: accountId ?? null
2035
+ });
2036
+ for (const action of collectDiscoveryActions(discovery))
2037
+ actions.add(action);
2038
+ schemaContributions.push(...asSchemaContributionArray(discovery?.schema));
2039
+ }
2040
+ return {
2041
+ activeChannels: [...uniqueChannels.keys()],
2042
+ displayNames: [...uniqueChannels.values()].map((channel) => channel.displayName),
2043
+ accountIds: [...accountIds],
2044
+ actions: [...actions],
2045
+ schemaContributions
2046
+ };
2047
+ }
2048
+ function mergeSchemaContributions(schema, contributions) {
2049
+ const properties = schema.properties;
2050
+ if (!properties)
2051
+ return schema;
2052
+ for (const contribution of contributions) {
2053
+ Object.assign(properties, structuredClone(contribution.properties));
2054
+ }
2055
+ return schema;
2056
+ }
2057
+ function buildMessageChannelSchemaFromDiscovery(baseSchema, discovery, allowProactiveTargets = true) {
2058
+ const schema = structuredClone(baseSchema);
2059
+ const properties = schema.properties;
2060
+ if (!properties)
2061
+ return schema;
2062
+ if (properties.channel && discovery.activeChannels.length > 0) {
2063
+ properties.channel.enum = [...discovery.activeChannels];
2064
+ properties.channel.description = `Channel to send the message to. Available channels: ${discovery.activeChannels.join(", ")}.`;
2065
+ }
2066
+ if (properties.accountId && discovery.accountIds.length > 0) {
2067
+ properties.accountId.enum = [...discovery.accountIds];
2068
+ }
2069
+ if (properties.action) {
2070
+ properties.action.enum = [...discovery.actions];
2071
+ properties.action.description = `Action to perform. Available actions: ${discovery.actions.join(", ")}.`;
2072
+ }
2073
+ if (!discovery.actions.includes("react")) {
2074
+ delete properties.emoji;
2075
+ delete properties.remove;
2076
+ }
2077
+ if (!discovery.actions.includes("react") && !discovery.actions.includes("download-file")) {
2078
+ delete properties.messageId;
2079
+ }
2080
+ if (!discovery.actions.includes("upload-file")) {
2081
+ delete properties.media;
2082
+ delete properties.filename;
2083
+ delete properties.title;
2084
+ }
2085
+ if (!allowProactiveTargets) {
2086
+ delete properties.target;
2087
+ if (properties.accountId) {
2088
+ properties.accountId.description = "Optional channel account identifier from the channel notification, used to disambiguate routed replies.";
2089
+ }
2090
+ }
2091
+ return mergeSchemaContributions(schema, discovery.schemaContributions);
2092
+ }
2093
+ function pruneProactiveTargetGuidance(description) {
2094
+ return description.replace(/There are two supported send modes:\n- Reply mode: ([^\n]*)\n- Proactive mode:[^\n]*/, "Reply mode: $1").replace(MESSAGE_CHANNEL_PARAMETER_LINE("target"), "").replace(/\n- Pass exactly one of `chat_id` or `target`\./, "\n- Pass `chat_id` from the channel notification.");
2095
+ }
2096
+ function pruneInactiveChannelGuidance(baseDescription, activeChannels, actions) {
2097
+ let description = baseDescription.trim();
2098
+ if (!actions.includes("react")) {
2099
+ description = description.replace(MESSAGE_CHANNEL_PARAMETER_LINE("emoji"), "").replace(MESSAGE_CHANNEL_PARAMETER_LINE("remove"), "").replace(/\n- `react` should be its own call\./g, "");
2100
+ }
2101
+ if (!actions.includes("react") && !actions.includes("download-file")) {
2102
+ description = description.replace(MESSAGE_CHANNEL_PARAMETER_LINE("messageId"), "");
2103
+ }
2104
+ if (!actions.includes("upload-file")) {
2105
+ description = description.replace(MESSAGE_CHANNEL_PARAMETER_LINE("media"), "").replace(MESSAGE_CHANNEL_PARAMETER_LINE("filename"), "").replace(MESSAGE_CHANNEL_PARAMETER_LINE("title"), "").replace(/\n- `upload-file` can include[^\n]*/g, "");
2106
+ }
2107
+ if (!activeChannels.includes("telegram")) {
2108
+ description = description.replace(TELEGRAM_RICH_RULE_RE, `
2109
+ `).replace(TELEGRAM_RICH_SECTION_RE, "");
2110
+ }
2111
+ return description.trim();
2112
+ }
2113
+ function buildMessageChannelDescriptionFromDiscovery(baseDescription, discovery, scoped, allowProactiveTargets = true) {
2114
+ const description = (allowProactiveTargets ? pruneInactiveChannelGuidance(baseDescription, discovery.activeChannels, discovery.actions) : pruneProactiveTargetGuidance(pruneInactiveChannelGuidance(baseDescription, discovery.activeChannels, discovery.actions))).trim();
2115
+ if (discovery.activeChannels.length === 0) {
2116
+ return `${description}
2117
+
2118
+ No external channel adapters are currently running.`;
2119
+ }
2120
+ const channelList = discovery.displayNames.join(", ");
2121
+ const actionList = discovery.actions.join(", ");
2122
+ const hasAction = (action) => discovery.actions.includes(action);
2123
+ const scopedReplyContract = scoped ? `
2124
+
2125
+ This tool is currently scoped to a routed external channel turn. Plain assistant text is not delivered to that external user. If a user-visible reply is appropriate, your final action for the turn must be one MessageChannel call with action="send", channel from the notification, chat_id from the notification, and message containing the reply. If no user-visible response is appropriate, do not call MessageChannel and do not send an empty acknowledgement. For lightweight acknowledgement, prefer action="react" when supported. If the useful response belongs later, schedule the follow-up instead of sending a placeholder.` : "";
2126
+ const slackWorkAcknowledgement = discovery.activeChannels.includes("slack") ? `
2127
+
2128
+ For Slack requests that require nontrivial work or several tool calls, send one short MessageChannel call with action="send" before starting other tools. This gives the Slack user verbal acknowledgement and a View in web link. Do not do this for no-ops, reaction-only responses, or simple no-tool answers.` : "";
2129
+ const slackAttachmentDownload = discovery.activeChannels.includes("slack") && hasAction("download-file") ? `
2130
+
2131
+ Slack attachments that exceed the automatic download limit include an exact recovery instruction. Use action="download-file" with channel, chat_id, attachmentId, and messageId from that instruction. The action saves the file in the normal Slack inbound attachment directory and returns its local_path. Downloads that outlast the synchronous window return a task_id instead; wait for the local_path with TaskOutput (block: true, timeout: 600000) or cancel with TaskStop.` : "";
2132
+ const slackThreadGuidance = scoped && discovery.activeChannels.includes("slack") ? `
2133
+
2134
+ Replies to routed Slack threads stay in the current thread automatically.` : "";
2135
+ const telegramTopicGuidance = scoped && discovery.activeChannels.includes("telegram") ? `
2136
+
2137
+ Replies to routed Telegram topics stay in the current topic automatically.` : "";
2138
+ const slackCapabilities = discovery.activeChannels.includes("slack") ? [
2139
+ hasAction("react") ? 'action="react" with emoji + messageId' : "",
2140
+ hasAction("upload-file") ? 'action="upload-file" with media' : "",
2141
+ hasAction("download-file") ? 'action="download-file" with attachmentId + messageId' : ""
2142
+ ].filter(Boolean) : [];
2143
+ const slackCapabilityGuidance = slackCapabilities.length > 0 ? `
2144
+
2145
+ On Slack, this tool also supports ${slackCapabilities.join(", ")}.` : "";
2146
+ const telegramCapabilities = discovery.activeChannels.includes("telegram") ? `
2147
+
2148
+ On Telegram, this tool also supports action="react" with emoji + messageId and action="upload-file" with media.` : "";
2149
+ const discordCapabilities = discovery.activeChannels.includes("discord") ? `
2150
+
2151
+ On Discord, this tool also supports action="react" with emoji + messageId and action="upload-file" with media. Discord reactions accept native Unicode emoji and custom emoji syntax like <:name:id>.` : "";
2152
+ const whatsappCapabilities = discovery.activeChannels.includes("whatsapp") ? `
2153
+
2154
+ On WhatsApp, this tool also supports action="react" with emoji + messageId and action="upload-file" with media. Voice memo/audio uploads must be Ogg/Opus (.ogg, .oga, or .opus), not MP3/M4A/WAV. Replies are sent as the linked WhatsApp number.` : "";
2155
+ const signalCapabilities = discovery.activeChannels.includes("signal") ? `
2156
+
2157
+ On Signal, this tool also supports action="react" with emoji + messageId and action="upload-file" with media. Replies are sent as the linked Signal account through signal-cli-rest-api.` : "";
2158
+ return `${description}${scopedReplyContract}${slackThreadGuidance}${telegramTopicGuidance}${slackCapabilityGuidance}${slackWorkAcknowledgement}${slackAttachmentDownload}${telegramCapabilities}${discordCapabilities}${whatsappCapabilities}${signalCapabilities}
2159
+
2160
+ Currently active channels: ${channelList}. Available actions across the active channels: ${actionList}. The JSON schema reflects the currently active channel plugins.`;
2161
+ }
2162
+ function buildMessageChannelToolFromDiscovery(params) {
2163
+ return {
2164
+ description: buildMessageChannelDescriptionFromDiscovery(params.baseDescription, params.discovery, params.scoped, params.allowProactiveTargets),
2165
+ schema: buildMessageChannelSchemaFromDiscovery(params.baseSchema, params.discovery, params.allowProactiveTargets)
2166
+ };
2167
+ }
2168
+ function buildMessageChannelExternalToolDefinition(options) {
2169
+ const resolved = buildMessageChannelToolFromDiscovery({
2170
+ baseDescription: MessageChannel_default.trim(),
2171
+ baseSchema: MessageChannel_default2,
2172
+ discovery: resolveMessageChannelToolChannels(options.channels),
2173
+ scoped: options.scoped,
2174
+ allowProactiveTargets: options.allowProactiveTargets ?? false
2175
+ });
2176
+ return {
2177
+ name: "MessageChannel",
2178
+ label: "Message Channel",
2179
+ description: resolved.description,
2180
+ parameters: resolved.schema
2181
+ };
2182
+ }
2183
+ export {
2184
+ executeMessageChannel,
2185
+ buildMessageChannelExternalToolDefinition,
2186
+ ChannelGateway,
2187
+ CHANNEL_GATEWAY_TOOL_SCOPE_ID
2188
+ };
2189
+
2190
+ //# debugId=3477006DB55C244E64756E2164756E21